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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

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.

@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 stricter validation for key members. The modification enforces a rule that key members must be declared before non-key members and restricts key members to core types that are 1 felt long when serialized. This ensures more robust type checking and consistent member attribute definitions in the Dojo language implementation.

Changes

File Change Summary
crates/dojo/lang/src/attribute_macros/element.rs - Added parsing_keys boolean to track key member ordering
- Implemented validation to ensure key members precede non-key members
- Added type constraint check preventing u256 as a key member type
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

Sequence Diagram

sequenceDiagram
    participant Parser
    participant Member
    participant Diagnostics

    Parser->>Member: Parse member attributes
    alt Key Member Validation
        Parser->>Parser: Check key member ordering
        Parser->>Diagnostics: Push error if keys out of order
        Parser->>Parser: Validate key member type
        Parser->>Diagnostics: Push error for invalid key type
    end
Loading

The sequence diagram illustrates the enhanced validation process for member parsing, showing how the parser checks key member ordering and type constraints before finalizing the member definition.


📜 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 70be593 and d84fb23.

📒 Files selected for processing (2)
  • crates/dojo/lang/src/attribute_macros/element.rs (2 hunks)
  • examples/spawn-and-move/src/models.cairo (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • examples/spawn-and-move/src/models.cairo
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/dojo/lang/src/attribute_macros/element.rs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt

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

@@ -41,9 +41,12 @@ pub fn parse_members(
members: &[MemberAst],
diagnostics: &mut Vec<PluginDiagnostic>,
) -> Vec<Member> {
let mut keys = true;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
let mut keys = true;
let mut parsing_keys = true;

members
.iter()
.filter_map(|member_ast| {
let key = member_ast.has_attr(db, "key");
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
let key = member_ast.has_attr(db, "key");
let is_key = member_ast.has_attr(db, "key");

Copy link

codecov bot commented Jan 10, 2025

Codecov Report

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

Project coverage is 55.79%. Comparing base (dd1ccce) to head (70be593).

Files with missing lines Patch % Lines
crates/dojo/lang/src/attribute_macros/element.rs 0.00% 16 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2891      +/-   ##
==========================================
- Coverage   55.81%   55.79%   -0.03%     
==========================================
  Files         449      449              
  Lines       57697    57719      +22     
==========================================
- Hits        32206    32202       -4     
- Misses      25491    25517      +26     

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

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