8000 Fix AOT warnings by not using MakeGenericType (refactor) by snakefoot · Pull Request #5718 · NLog/NLog · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Fix AOT warnings by not using MakeGenericType (refactor) #5718

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 5, 2025

Conversation

snakefoot
Copy link
Contributor
@snakefoot snakefoot commented Mar 4, 2025

Trimming doesn't like unknown existing types, but AOT doesn't like trying to make new generic types. Trying to find a middle road.

@snakefoot snakefoot added this to the 6.0 milestone Mar 4, 2025
Copy link
coderabbitai bot commented Mar 4, 2025
Loading

Walkthrough

The changes refactor the conversion of string inputs to collection objects in the TryFlatListConversion method. The refactored logic now immediately verifies if the property type is a generic collection implementing IEnumerable. The separate collection creation logic has been moved into a renamed method, which now supports both List<T> and HashSet<T> via dedicated helper methods. Error handling has been updated to throw an exception with a detailed message instead of simply logging an error and returning false.

Changes

File Change Summary
src/NLog/Internal/PropertyHelper.cs • Refactored TryFlatListConversion to immediately check for generic collection types.
• Renamed and modified TryResolveCollectionType to TryCreateCollectionObject for flexible collection creation.
• Added TryCreateListCollection<T> and TryCreateHashSetCollection<T> helper methods.
• Updated TryMakeGenericCollectionType to TryCreateTypeCollection.
• Changed error handling to throw NLogConfigurationException on failure.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant TH as TryFlatListConversion
    participant TC as TryCreateCollectionObject
    participant LHelper as TryCreateListCollection<T>
    participant HHelper as TryCreateHashSetCollection<T>

    Caller->>TH: Call TryFlatListConversion(value)
    alt Not a generic collection
        TH-->>Caller: return false (newValue = null)
    else Is a generic collection
        TH->>TC: Call TryCreateCollectionObject(propertyType)
        alt Collection is List<T>
            TC->>LHelper: Attempt List creation
        else Collection is HashSet<T>
            TC->>HHelper: Attempt HashSet creation
        end
        alt Creation fails
            TC-->>TH: Error -> throw NLogConfigurationException
            TH-->>Caller: Exception propagates
        else Creation succeeds
            TC-->>TH: Return collection object, add method, item type
            TH-->>Caller: return true with newValue
        end
    end
Loading

Poem

I'm a rabbit in the codewarren deep,
Hopping through changes while others sleep.
List and HashSet now share the light,
Their helpers guide with skills so bright.
I nibble on bugs and skip the fright,
Celebrating clean code with a joyful leap!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3e6e670 and 7cfc82d.

📒 Files selected for processing (1)
  • src/NLog/Internal/PropertyHelper.cs (1 hunks)
🔇 Additional comments (17)
src/NLog/Internal/PropertyHelper.cs (17)

392-398: Improved type checking in TryFlatListConversion.

The refactored code now immediately checks if the property type is a valid generic collection implementing IEnumerable before proceeding with any conversion attempts. This is a good defensive programming practice that prevents unnecessary processing for unsupported types.


402-419: Enhanced string parsing workflow.

The refactored implementation correctly processes comma-separated values and applies appropriate type conversion for each item. The code effectively handles different conversion strategies (enum values, NLog-specific conversions, implicit conversions, and type converter conversions) before falling back to standard Convert.ChangeType.


427-427: Improved error handling with detailed exception message.

The error handling has been enhanced to throw a more informative NLogConfigurationException with specific details about the property, type, and value that failed to parse. This will make debugging configuration issues much easier.


431-438: Renamed method with improved parameters.

The method has been renamed from TryResolveCollectionType to TryCreateCollectionObject, which better reflects its purpose. The parameter changes from collectionType to collectionObject and hashSetComparer to collectionItemType make the method's purpose and return values clearer.


439-445: Support for fast-path collection creation.

The addition of specific type checks for common collection types (List and List) provides an optimization that avoids unnecessary reflection in common scenarios. This is a good performance enhancement.


449-452: Simplified List handling.

The refactored code now uses Activator.CreateInstance directly for the collection type and properly retrieves the Add method and item type from the generic collection. This approach provides a cleaner implementation for List creation.


455-461: Improved collection type checking.

The code now correctly handles more collection types, including HashSet and ISet (for non-NET35 targets), making the implementation more comprehensive and adaptable to different collection interfaces.


467-471: Fixed variable naming for clarity.

The refactored code uses more descriptive variable names like existingType instead of simply reusing collectionType, which improves readability and maintainability by making it clear that this is the type of an existing collection object.


476-497: Enhanced HashSet handling with comparer preservation.

The implementation now correctly handles HashSet collections by preserving any custom comparer that might have been used in the existing collection. This ensures that the behavior of the new collection matches that of the original collection when a custom comparer is involved.


501-505: Added optimized paths for HashSet collections.

Similar to the List optimizations, the code now includes specialized handlers for HashSet and HashSet, which are common collection types. This avoids unnecessary reflection for these types.


507-513: Simplified HashSet handling.

The code now uses a cleaner approach for creating HashSet instances using Activator.CreateInstance directly and properly retrieving the Add method and item type from the generic collection.


515-517: Improved fallback strategy with better method name.

The fallback strategy now uses a more appropriately named method (TryCreateTypeCollection instead of TryMakeGenericCollectionType) that better reflects its purpose of creating collection objects rather than just resolving types.


519-533: New helper method for creating List collections.

The addition of the TryCreateListCollection<T> method provides a clean, reusable way to create List collections of specific types. This helps reduce code duplication and improves maintainability.


535-549: New helper method for creating HashSet collections.

Similar to the List helper, the TryCreateHashSetCollection<T> method provides a clean, reusable way to create HashSet collections of specific types, further improving code organization and maintainability.


551-571: Refactored type collection creation.

The TryCreateTypeCollection method (renamed from TryMakeGenericCollectionType) now creates and returns the collection object directly instead of just resolving the type. This change aligns with the AOT compilation requirements mentioned in the PR description by avoiding dynamically creating new generic types at runtime.


558-562: AOT-friendly collection creation for ISet.

This implementation now uses a pre-constructed HashSet type with MakeGenericType, which is more friendly to AOT compilation than dynamically creating new generic types. This directly addresses the PR objective of fixing AOT warnings related to MakeGenericType usage.


566-570: AOT-friendly List creation.

Similar to the ISet handling, this implementation uses a pre-constructed List type with MakeGenericType, which aligns with the PR's goal of addressing AOT compilation warnings.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/NLog/Internal/PropertyHelper.cs (3)

403-419: Consider partial parsing vs. all-or-nothing approach.
Currently, the code attempts to parse all items in a single pass, throwing an exception if any item fails. Depending on your use case, consider whether partial success (some items parsed correctly) is preferable; if so, you could gather errors and proceed with partially valid results. Otherwise, this all-or-nothing approach is perfectly acceptable.


434-461: Potential code duplication for handling string and int collections.
This method checks for List<string>, List<int>, and then falls back to more generalized solutions. While it works, consider consolidating these special cases into a single dynamic approach if you anticipate future expansions (e.g., List<bool>, List<double>).


535-548: Parallel approach for HashSet creation.
Similar to the list logic above, this is a straightforward approach, but there is some repeated code. Consider unifying the logic if you need to branch out to more type-specific overrides in the future.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 308b551 and 3e6e670.

📒 Files selected for processing (1)
  • src/NLog/Internal/PropertyHelper.cs (1 hunks)
🔇 Additional comments (8)
src/NLog/Internal/PropertyHelper.cs (8)

393-398: Well-structured check for generic collection.
The preliminary check for generic IEnumerable types ensures we only proceed with valid collection targets. This helps avoid erroneous parsing attempts and simplifies subsequent logic.


423-424: Clearer exception handling.
Throwing an NLogConfigurationException clarifies the source of the error and provides more explicit feedback than logging. This is a beneficial improvement for diagnosing configuration issues.


427-428: Fallback approach is consistent.
Returning false with newValue = null ensures the caller understands that the flat list conversion was not applied. This aligns with typical “TryXyz” patterns and is easy to follow.


431-433: Suppression attributes are appropriate for AOT/trimming scenarios.
Using [UnconditionalSuppressMessage] avoids undesired warnings when trimming is involved. This is consistent with many .NET AOT patterns.


462-498: Good reuse of existing instance for list/hashset properties.
Reusing an existing collection instance or replicating its comparer ensures consistent behavior and user expectations. The reflection logic is a bit verbose, but it effectively handles specialized comparers.


501-517: Structured fallback path to hash-set creation.
The fallback logic for creating or re-creating a HashSet<> object with the correct comparer is well handled. It promotes consistency when dealing with various property value states.


519-533: Generically creating List is concise and robust.
Utilizing TryCreateListCollection<T> for strongly typed lists is a neat approach. It reads clearly and makes the intended behavior obvious.


552-552: Fallback to generic type creation is smooth.
The final fallback that dynamically constructs a List<> or HashSet<> ensures a last-resort resolution with descriptive debug info. This is a well-structured solution for advanced collection conversions.

Also applies to: 559-562, 566-570

Copy link
sonarqubecloud bot commented Mar 4, 2025

@snakefoot snakefoot merged commit 489cb81 into NLog:dev Mar 5, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant
0