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

Merged
merged 5 commits into from
Nov 5, 2024

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.
    • Introduced a new helper function for recursive token type checking, streamlining dependency management.
  • 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 enhance 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. A new helper function, check_token_in_recursively, has been introduced to improve clarity and maintainability. The format_system function has been simplified by removing the handled_tokens parameter, streamlining the argument handling process.

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.
- Added check_token_in_recursively helper function.
- Simplified format_system function by removing handled_tokens parameter.
- 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
    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 53 lines in your changes missing coverage. Please review.

Project coverage is 56.79%. Comparing base (d09cbcf) to head (528bdaa).
Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
crates/dojo/bindgen/src/plugins/unity/mod.rs 0.00% 53 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2631      +/-   ##
==========================================
- Coverage   56.91%   56.79%   -0.13%     
==========================================
  Files         397      397              
  Lines       49467    49560      +93     
==========================================
- Hits        28153    28146       -7     
- Misses      21314    21414     +100     

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

@Larkooo Larkooo enabled auto-merge (squash) November 5, 2024 15:41
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

🧹 Outside diff range and nitpick comments (2)
crates/dojo/bindgen/src/plugins/unity/mod.rs (2)

264-274: Consider consolidating duplicate filtering logic.

The filtering logic for structs and enums is very similar. Consider extracting this into a shared helper function to improve maintainability.

+ fn filter_dependencies(
+     handled_tokens: &HashMap<String, Composite>,
+     model_struct: &Composite,
+     composite_type: CompositeType,
+ ) -> Vec<String> {
+     handled_tokens
+         .iter()
+         .filter(|(_, s)| {
+             model_struct.inners.iter().any(|inner| {
+                 s.r#type == composite_type
+                     && check_token_in_recursively(&inner.token, &s.type_name())
+                     && (composite_type != CompositeType::Struct 
+                         || inner.token.type_name() != "ByteArray")
+             })
+         })
+         .map(|(k, _)| k.clone())
+         .collect()
+ }

- let struct_keys: Vec<String> = handled_tokens
-     .iter()
-     .filter(|(_, s)| {
-         model_struct.inners.iter().any(|inner| {
-             s.r#type == CompositeType::Struct
-                 && check_token_in_recursively(&inner.token, &s.type_name())
-                 && inner.token.type_name() != "ByteArray"
-         })
-     })
-     .map(|(k, _)| k.clone())
-     .collect();
+ let struct_keys = filter_dependencies(handled_tokens, model_struct, CompositeType::Struct);

- let enum_keys: Vec<String> = handled_tokens
-     .iter()
-     .filter(|(_, s)| {
-         model_struct.inners.iter().any(|inner| {
-             s.r#type == CompositeType::Enum
-                 && check_token_in_recursively(&inner.token, &s.type_name())
-         })
-     })
-     .map(|(k, _)| k.clone())
-     .collect();
+ let enum_keys = filter_dependencies(handled_tokens, model_struct, CompositeType::Enum);

Also applies to: 292-301


568-582: Ohayo sensei! Consider adding documentation for the recursive checker.

The check_token_in_recursively function is well-implemented but could benefit from documentation explaining its purpose and behavior.

+/// Recursively checks if a token or any of its nested tokens match the given type name.
+/// 
+/// # Arguments
+/// * `token` - The token to check
+/// * `type_name` - The type name to match against
+/// 
+/// # Returns
+/// `true` if the token or any of its nested tokens match the type name
 fn check_token_in_recursively(token: &Token, type_name: &str) -> bool {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 78abe15 and 528bdaa.

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

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

The expect() call could cause a panic if the model struct is not found. Consider using a more graceful error handling approach.

crates/dojo/bindgen/src/plugins/unity/mod.rs Show resolved Hide resolved
@Larkooo Larkooo merged commit 447ba4f into dojoengine:main Nov 5, 2024
12 checks passed
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