Skip to content

Various fixes for generics handling #3185

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
Jun 20, 2025

Conversation

josesimoes
Copy link
Member

@josesimoes josesimoes commented Jun 20, 2025

Description

  • Fix several APIs to deal with closed generic types and find types of generic VAR types.
  • Fix wrong setting of assembly index when resolving a MethodRef from a TypeSpec.
  • Fix bug with dummy assembly index in ResolveMethodRef().
  • CLR_RT_Assembly::FindMethodDef() can now find MethodDef from TypeSpec in the same or referenced assembly.
  • Major rework of CLR_RT_TypeSystem::BuildTypeName() for TypeSpec.
  • Major rework of BuildMethodName().

Motivation and Context

How Has This Been Tested?

Screenshots

Types of changes

  • Improvement (non-breaking change that improves a feature, code or algorithm)
  • Bug fix (non-breaking change which fixes an issue with code or algorithm)
  • New feature (non-breaking change which adds functionality to code)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Config and build (change in the configuration and build system, has no impact on code or features)
  • Dev Containers (changes related with Dev Containers, has no impact on code or features)
  • Dependencies/declarations (update dependencies or assembly declarations and changes associated, has no impact on code or features)
  • Documentation (changes or updates in the documentation, has no impact on code or features)

Checklist

  • My code follows the code style of this project (only if there are changes in source code).
  • My changes require an update to the documentation (there are changes that require the docs website to be updated).
  • I have updated the documentation accordingly (the changes require an update on the docs in this repo).
  • I have read the CONTRIBUTING document.
  • I have tested everything locally and all new and existing tests passed (only if there are changes in source code).

Summary by CodeRabbit

  • Bug Fixes
    • Improved accuracy when displaying and resolving generic types and methods, ensuring correct names and references are shown for complex generic scenarios.
  • Refactor
    • Enhanced internal logic for handling generic type and method resolution, resulting in more robust and reliable type and method name generation in user-facing outputs.

- Fix several APIs to deal with closed generic types and find types of generic VAR types.
- Fix wrong setting of assembly index when resolving a MethodRef from a TypeSpec.
- Fix bug with dummy assembly index in ResolveMethodRef().
- CLR_RT_Assembly::FindMethodDef() can now find MethodDef from TypeSpec in the same or referenced assembly.
- Major rework of CLR_RT_TypeSystem::BuildTypeName() for TypeSpec.
- Major rework of BuildMethodName().
@josesimoes josesimoes added the Area: Interpreter Everything related with the interpreter, execution engine and such label Jun 20, 2025
Copy link

coderabbitai bot commented Jun 20, 2025

Walkthrough

The changes enhance the CLR type system's handling of generic types and methods. They refine generic method initialization, method reference resolution, type name construction, and validation for type/method indices. Several method signatures are updated to support improved parsing, resolution, and name-building for generics, ensuring more robust and accurate behavior.

Changes

File(s) Change Summary
src/CLR/Core/TypeSystem.cpp Improved generic type/method handling: refined initialization, resolution, signature parsing, type and method name building, and index validation. Updated several method signatures for enhanced robustness and correctness.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant TypeSystem
    participant Assembly
    participant MethodDefInstance

    Caller->>TypeSystem: BuildMethodName(md, genericType, szBuffer, iBuffer)
    TypeSystem->>MethodDefInstance: InitializeFromIndex(md, genericType)
    MethodDefInstance->>Assembly: FindGenericParamAtTypeSpec(typeSpecIndex, paramPos)
    Assembly-->>MethodDefInstance: Return resolved typeDef and dataType
    MethodDefInstance-->>TypeSystem: Initialization complete
    TypeSystem->>TypeSystem: BuildTypeName(typeIndex, szBuffer, iBuffer)
    TypeSystem-->>Caller: Return method name
Loading
sequenceDiagram
    participant Caller
    participant MethodDefInstance
    participant Assembly

    Caller->>MethodDefInstance: ResolveToken(token, assembly, callerGeneric)
    MethodDefInstance->>Assembly: ResolveMethodRef(token, callerGeneric)
    Assembly-->>MethodDefInstance: Return method index and assembly index
    MethodDefInstance-->>Caller: Token resolved
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@josesimoes
Copy link
Member Author

@coderabbitai review

Copy link

coderabbitai bot commented Jun 20, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4fab260 and 16df335.

📒 Files selected for processing (1)
  • src/CLR/Core/TypeSystem.cpp (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: nf-interpreter (Check_Code_Style)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALX)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALTHREE)
  • GitHub Check: nf-interpreter (Nightly build) (Check_Build_Options)
  • GitHub Check: nf-interpreter (Check_Build_Options)
🔇 Additional comments (6)
src/CLR/Core/TypeSystem.cpp (6)

1269-1320: Good improvement for generic type initialization

The refactored InitializeFromIndex method now properly handles generic types by:

  1. Creating a CLR_RT_TypeSpec_Instance to parse the type specification
  2. Using signature parser to extract generic instance elements
  3. Correctly handling VAR types by resolving to the real owner type via FindGenericParamAtTypeSpec
  4. Properly rebinding the method definition index to the declaring assembly

This is a solid improvement that should prevent issues with generic method resolution.


3304-3304: Improved consistency for dummy assembly index

Changing from 0xffff to 0xffffffff aligns with the CLR_UINT32 type and provides a clearer sentinel value that won't conflict with valid assembly indices.


5031-5045: Excellent defensive programming for TypeSpec method resolution

The addition of bounds checking for typeDefIdx prevents potential crashes from out-of-range indices. The fallback to TypeSpec parsing provides a robust alternative path for resolving methods in generic types. This should improve stability when dealing with complex generic type hierarchies.


4796-4796: Minor formatting improvement

Adding a trailing newline for better code readability.


6269-6304: Major improvement in generic type name resolution

The enhanced BuildTypeName now properly resolves generic type parameters (VAR) to their concrete types in closed generic instantiations. This means that instead of seeing cryptic parameter placeholders like !T, users will see the actual type names like System.Int32. This significantly improves debugging and error messages.

The recursive approach for building nested generic type names is well-structured.


6379-6439: Significant rework of method name building for generics

This refactoring properly handles the complexity of building method names for generic types:

  1. Correct type association: The code now verifies that the provided genericType actually corresponds to the method's declaring type before using it
  2. Fallback mechanism: If the types don't match, it falls back to non-generic initialization, preventing incorrect type associations
  3. Proper ownership resolution: Uses InitializeFromMethod to correctly determine the method's owner

This should resolve issues with method name generation for generic types and their instantiations.

@@ -1401,7 +1424,7 @@ bool CLR_RT_MethodDef_Instance::ResolveToken(
return false;
}

Set(assemblyIndex - 1, methodIndex.Method());
Set(assemblyIndex, methodIndex.Method());
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical bug fix: Corrected assembly index calculation

The removal of - 1 from assemblyIndex fixes an off-by-one error when setting the method index for TypeSpec-owned method references. This ensures the correct assembly is referenced.

🤖 Prompt for AI Agents
In src/CLR/Core/TypeSystem.cpp at line 1427, fix the off-by-one error by
removing the subtraction of 1 from assemblyIndex when calling Set with
assemblyIndex and methodIndex.Method(). This correction ensures the correct
assembly is referenced for TypeSpec-owned method references.

@josesimoes josesimoes merged commit 927f73d into nanoframework:develop Jun 20, 2025
24 checks passed
@josesimoes josesimoes deleted the fix-generic-handling branch June 20, 2025 12:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area: Interpreter Everything related with the interpreter, execution engine and such Type: bug Type: enhancement
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants