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

fix(dojo-lang): raise an error on value before key in model #2891

Merged
merged 9 commits into from
Jan 16, 2025

Conversation

bengineer42
Copy link
Contributor

@bengineer42 bengineer42 commented Jan 10, 2025

Description

Raise an error when a value appears before a key in a model eg:

#[dojo::model]
struct Foo2 {
    #[key]
    k1: u8,
    v1: u128,
    #[key]
    k2: felt252,
    v2: u32
}

Related issue

Tests

  • Yes
  • No, because they aren't needed
  • No, because I need help

Added to documentation?

  • README.md
  • Dojo Book
  • [] No documentation needed

Checklist

  • I've formatted my code (scripts/prettier.sh, scripts/rust_fmt.sh, scripts/cairo_fmt.sh)
  • I've linted my code (scripts/clippy.sh, scripts/docs.sh)
  • I've commented my code
  • I've requested a review after addressing the comments

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced validation for key members in struct definitions.
    • Enforced strict rules for key member placement and type constraints.
    • Improved error reporting for incorrect key member configurations.
  • Refactor

    • Updated the order of fields in the Message struct for better organization.
  • Chores

    • Updated dependencies for scarb and scarb-ui to the latest commit for potential improvements and fixes.

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
@glihm
Copy link
Collaborator

glihm commented Jan 10, 2025

to complement the reason, since the keys are serialized before the values by dojo before returning the model when read from the storage, the order does matter.

Thanks @bengineer42 for the good catch.

@glihm glihm changed the title fix: Raise an error on value before key in model fix(dojo-lang): raise an error on value before key in model Jan 10, 2025
Copy link

coderabbitai bot commented Jan 10, 2025

Walkthrough

Ohayo, sensei! The changes in the parse_members function of the Dojo language attribute macros introduce enhancements for validating the order of key and non-key members during parsing. A diagnostics parameter has been added to collect error messages, and a new boolean variable tracks whether key members have been defined before non-key members. The logic now ensures that key members must precede non-key members, improving the robustness of member attribute definitions.

Changes

File Change Summary
crates/dojo/lang/src/attribute_macros/element.rs - Added diagnostics parameter to parse_members function
- Introduced parsing_keys boolean to track key member ordering
- Implemented validation to ensure key members precede non-key members
- Assigned key field from local is_key variable based on the "key" attribute
examples/spawn-and-move/src/models.cairo - Reordered fields in Message struct: salt now precedes message
- Updated salt field declaration to include a trailing comma
Cargo.toml - Updated scarb and scarb-ui dependencies to a more recent commit hash

Possibly related PRs


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e524f28 and 4f7d7ae.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • Cargo.toml (1 hunks)
🔇 Additional comments (1)
Cargo.toml (1)

215-216: Ohayo sensei! Let's verify the stability of the scarb dependency update.

The update to a new commit hash (c811c5bcb073afa21cb9b1307adafe733c203eb9) for both scarb and scarb-ui dependencies needs verification.

Let's run this script to check the commit details and changes:

✅ Verification successful

Ohayo sensei! The scarb dependency update looks safe and routine!

The update is a simple dependency bump with minimal changes:

  • Single commit with no breaking changes
  • Only modifies dependency management files
  • No core functionality changes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the stability and changes in the new scarb commit

# Check commit details
echo "Checking commit details..."
gh api repos/dojoengine/scarb/commits/c811c5bcb073afa21cb9b1307adafe733c203eb9 --jq '.commit.message'

# Check if this is a tagged release
echo "Checking if commit is tagged..."
gh api repos/dojoengine/scarb/tags --jq '.[] | select(.commit.sha == "c811c5bcb073afa21cb9b1307adafe733c203eb9") | .name'

# Look for breaking changes in commit history between old and new versions
echo "Checking for breaking changes..."
gh api repos/dojoengine/scarb/compare/7eac49b3e61236ce466e712225d9c989f9db1ef3...c811c5bcb073afa21cb9b1307adafe733c203eb9 --jq '.commits[].commit.message' | grep -i "breaking"

Length of output: 629


Script:

#!/bin/bash
# Description: Check the actual changes between the commits

# Get the files changed and their status
echo "Files changed between commits:"
gh api repos/dojoengine/scarb/compare/7eac49b3e61236ce466e712225d9c989f9db1ef3...c811c5bcb073afa21cb9b1307adafe733c203eb9 --jq '.files[] | {filename: .filename, status: .status, additions: .additions, deletions: .deletions}'

# Get commit count between versions
echo -e "\nNumber of commits between versions:"
gh api repos/dojoengine/scarb/compare/7eac49b3e61236ce466e712225d9c989f9db1ef3...c811c5bcb073afa21cb9b1307adafe733c203eb9 --jq '.total_commits'

Length of output: 686


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 0

🧹 Nitpick comments (2)
crates/dojo/lang/src/attribute_macros/element.rs (2)

63-74: Consider adding documentation for the key validation logic, sensei!

While the implementation is solid, adding a doc comment explaining why keys must precede non-key members would help future maintainers understand the design decision.

+    // Keys must be defined before non-key members to ensure consistent
+    // serialization order and to maintain a predictable storage layout.
     if key {
         if !keys {

Line range hint 76-87: Enhance the error message with alternative type suggestions, sensei!

The error message explains why u256 isn't supported, but it would be more helpful to also suggest what types can be used instead.

-                    message: "Key is only supported for core types that are 1 felt long once \
-                              serialized. `u256` is a struct of 2 u128, hence not supported."
+                    message: "Key is only supported for core types that are 1 felt long once \
+                              serialized. `u256` is a struct of 2 u128, hence not supported. \
+                              Consider using `felt252` or `u128` instead."
                         .into(),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd1ccce and 70be593.

📒 Files selected for processing (1)
  • crates/dojo/lang/src/attribute_macros/element.rs (2 hunks)
🔇 Additional comments (2)
crates/dojo/lang/src/attribute_macros/element.rs (2)

44-44: Ohayo! Clean implementation of the key tracking mechanism, sensei!

The initialization and usage of the keys flag is well-structured and follows Rust idioms.

Also applies to: 48-49, 59-59


Line range hint 44-87: Ohayo! The implementation successfully achieves the PR objectives!

The code effectively enforces the requirement that key members must be defined before non-key members, with proper error handling and clear messages. The additional validation for key types adds robust type safety.

Let's verify that there are no existing models that would be affected by this change:

✅ Verification successful

Ohayo! The implementation correctly enforces key member ordering, sensei!

The codebase scan confirms that all models consistently define key members before non-key members, with no violations found. The implementation successfully enforces this constraint with proper error handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for models with key attributes after non-key members
ast-grep --pattern 'struct $name {
    $$$
    $field: $_,
    #[key]
    $key_field: $_,
    $$$
}'

Length of output: 102


Script:

#!/bin/bash
# Search for struct definitions with key attributes using ripgrep
rg "#\[key\]" -B 2 -A 2

# Search for all struct definitions with attributes to analyze patterns
ast-grep --pattern 'struct $name {
  #[$attr]
  $field: $_,
  $$$
}'

Length of output: 63041

crates/dojo/lang/src/attribute_macros/element.rs Outdated Show resolved Hide resolved
crates/dojo/lang/src/attribute_macros/element.rs Outdated Show resolved Hide resolved
Copy link

codecov bot commented Jan 10, 2025

Codecov Report

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

Project coverage is 56.03%. Comparing base (e57d820) to head (f61570e).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
crates/dojo/lang/src/attribute_macros/element.rs 0.00% 36 Missing ⚠️
crates/dojo/lang/src/attribute_macros/event.rs 0.00% 1 Missing ⚠️
crates/dojo/lang/src/attribute_macros/model.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2891      +/-   ##
==========================================
+ Coverage   55.21%   56.03%   +0.81%     
==========================================
  Files         449      449              
  Lines       58338    57944     -394     
==========================================
+ Hits        32213    32469     +256     
+ Misses      26125    25475     -650     

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

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 (1)
crates/dojo/lang/src/attribute_macros/element.rs (1)

44-44: Consider adding a doc comment for parsing_keys

Adding a brief doc comment would help future maintainers understand the significance of this flag.

+    // Tracks whether we're still in the keys section. Once we encounter a non-key member,
+    // this becomes false and no more key members are allowed.
     let mut parsing_keys = true;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d84fb23 and e524f28.

📒 Files selected for processing (1)
  • crates/dojo/lang/src/attribute_macros/element.rs (2 hunks)
🔇 Additional comments (3)
crates/dojo/lang/src/attribute_macros/element.rs (3)

39-43: Ohayo! The function signature enhancement looks solid, sensei!

The addition of the diagnostics parameter enables proper error reporting for model structure violations.


44-44: Elegant key tracking implementation, sensei!

The parsing_keys flag with the &= update is a clean way to enforce the key-before-value requirement.

Also applies to: 75-75


63-73: Excellent error handling approach, sensei!

The validation logic provides clear error messages while continuing to process remaining members, which helps developers fix all issues at once rather than one at a time.

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.

Good catch on this one, thanks @bengineer42 for the fix.

@glihm glihm enabled auto-merge (squash) January 16, 2025 03:19
@glihm glihm merged commit 9928558 into dojoengine:main Jan 16, 2025
14 of 15 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.

None yet

2 participants