Skip to content
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

refactor: update & fix unity bindgen #2631

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Nov 5, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced handling of models and enums during code generation for improved accuracy and relevance.
    • Updated representation of contract addresses in generated C# code for better clarity.
  • Bug Fixes

    • Improved error handling to prevent potential issues during formatting by ensuring model struct identification.
  • Documentation

    • Minor adjustments made to ensure consistency and correctness in the generated output.

Copy link

coderabbitai bot commented Nov 5, 2024

Walkthrough

Ohayo, sensei! The changes in this pull request focus on the UnityPlugin implementation within the mod.rs file. Key updates include modifications to the handle_model function for improved processing of structs and enums, ensuring only relevant tokens are formatted based on their relationship to the model struct. The format_system function has also been adjusted to wrap the contract address in a FieldElement. Additionally, error handling has been enhanced to prevent panics if the model struct is not found, alongside minor formatting adjustments for the generated C# code.

Changes

File Path Change Summary
crates/dojo/bindgen/src/plugins/unity/mod.rs - Updated handle_model function to filter tokens based on model struct relationships.
- Modified format_system to wrap contract address in FieldElement.
- Improved error handling to prevent panics when model struct is not found.
- Minor formatting adjustments in generated C# code.
crates/dojo/bindgen/src/plugins/unity/mod.rs - Method signature updated for async fn generate_code in BuiltinPlugin trait for UnityPlugin (context of usage modified).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UnityPlugin
    participant ModelStruct
    participant CSharpCode

    User->>UnityPlugin: Request code generation
    UnityPlugin->>ModelStruct: Check for model struct
    alt Model struct found
        UnityPlugin->>UnityPlugin: Filter tokens
        UnityPlugin->>CSharpCode: Format relevant tokens
        UnityPlugin->>CSharpCode: Wrap contract address in FieldElement
    else Model struct not found
        UnityPlugin-->>User: Error: Model struct not found
    end
    UnityPlugin-->>User: Return generated C# code
Loading

🪧 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.

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d09cbcf and d8fa31d.

📒 Files selected for processing (1)
  • crates/dojo/bindgen/src/plugins/unity/mod.rs (2 hunks)
🔇 Additional comments (3)
crates/dojo/bindgen/src/plugins/unity/mod.rs (3)

280-282: LGTM! Proper enum filtering implementation.

The check ensures that only enums referenced by the model structs are formatted, maintaining consistency with the struct handling approach.


287-288: LGTM! Clean model formatting with proper namespace.

The implementation correctly uses the namespace from tag and formats the model using the filtered struct.


490-490: LGTM! Proper contract address wrapping.

The contract address is correctly wrapped in FieldElement, ensuring proper type conversion for Starknet interaction.

Let's verify that all contract address usages are consistently wrapped:

✅ Verification successful

Let me modify the search to look for specific patterns in both C# and Rust code to verify the contract address handling consistency. The previous regex was too complex and unsupported. This will help us see the surrounding context of how contract addresses are used.


Contract address wrapping is correctly implemented, sensei!

The verification shows that contract addresses are properly handled across the codebase:

  • In Unity (C#), the contract address is wrapped with FieldElement as seen in the reviewed line
  • In TypeScript bindings, contract addresses are handled as strings and properly converted during execution
  • In GraphQL/Rust code, addresses are consistently handled as strings for external interfaces
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any direct contract address usage without FieldElement wrapping
rg -g '*.cs' 'contractAddress(?!.*FieldElement)'

Length of output: 302


Script:

#!/bin/bash
# Search for contract address usage patterns with proper context
rg --pcre2 "contractAddress" -g "*.cs" -B2 -A2

# Also search in Rust code to understand the context better
rg --pcre2 "contractAddress" -g "*.rs" -B2 -A2

Length of output: 9190

Comment on lines +261 to +273
let model_struct = model_struct.expect("model struct not found");
handled_tokens
.iter()
.filter(|(_, s)| {
model_struct.inners.iter().any(|inner| {
inner.token.type_name() == s.type_name()
&& inner.token.type_name() != "ByteArray"
})
})
.for_each(|(_, s)| {
out += UnityPlugin::format_struct(s).as_str();
});

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ohayo sensei! Consider improving error handling for model struct lookup.

While the filtering logic for handled tokens is well-implemented, the expect() call on line 261 could cause a panic if the model struct is not found. Consider using a more graceful error handling approach.

-        let model_struct = model_struct.expect("model struct not found");
+        let model_struct = model_struct.ok_or_else(|| {
+            anyhow::anyhow!("Model struct not found for {}", model.tag)
+        })?;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let model_struct = model_struct.expect("model struct not found");
handled_tokens
.iter()
.filter(|(_, s)| {
model_struct.inners.iter().any(|inner| {
inner.token.type_name() == s.type_name()
&& inner.token.type_name() != "ByteArray"
})
})
.for_each(|(_, s)| {
out += UnityPlugin::format_struct(s).as_str();
});
let model_struct = model_struct.ok_or_else(|| {
anyhow::anyhow!("Model struct not found for {}", model.tag)
})?;
handled_tokens
.iter()
.filter(|(_, s)| {
model_struct.inners.iter().any(|inner| {
inner.token.type_name() == s.type_name()
&& inner.token.type_name() != "ByteArray"
})
})
.for_each(|(_, s)| {
out += UnityPlugin::format_struct(s).as_str();
});

Copy link

codecov bot commented Nov 5, 2024

Codecov Report

Attention: Patch coverage is 0% with 18 lines in your changes missing coverage. Please review.

Project coverage is 56.88%. Comparing base (d09cbcf) to head (d8fa31d).

Files with missing lines Patch % Lines
crates/dojo/bindgen/src/plugins/unity/mod.rs 0.00% 18 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2631      +/-   ##
==========================================
- Coverage   56.91%   56.88%   -0.03%     
==========================================
  Files         397      397              
  Lines       49467    49476       +9     
==========================================
- Hits        28153    28144       -9     
- Misses      21314    21332      +18     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Now the tokens should contains the whole children tokens. It may simplify some use case where you may don't have anymore to lookup in handled tokens.

But both approaches are still valid.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants