Skip to content

fix(dojo-lang): remove restriction for u256 as keys in models#2890

Merged
glihm merged 3 commits intodojoengine:mainfrom
bengineer42:add-u256-as-key/0
Jan 16, 2025
Merged

fix(dojo-lang): remove restriction for u256 as keys in models#2890
glihm merged 3 commits intodojoengine:mainfrom
bengineer42:add-u256-as-key/0

Conversation

@bengineer42
Copy link
Contributor

@bengineer42 bengineer42 commented Jan 10, 2025

Description

Allows use of u256 as a key in a dojo model

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

  • New Features

    • Added a new struct Foo3 with modified key field type.
    • Enhanced the build script to include testing for the sozo binary.
  • Code Changes

    • Simplified member creation process in parsing function.
    • Removed previous validation checks for member attributes.
    • Updated function signatures to remove diagnostics handling in member parsing.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

Walkthrough

Ohayo, sensei! The pull request introduces a new struct Foo3 in the Cairo test models, modifying the first key field's type from u8 to u256. Additionally, the parse_members function in the Dojo language attribute macros has been simplified by removing error handling and validation logic, leading to unconditional member creation. The script for rebuilding test artifacts has also been updated to include a command for running tests on the sozo binary, enhancing the overall testing process.

Changes

File Change Summary
crates/dojo/core-cairo-test/src/tests/model/model.cairo Added new Foo3 struct with modified key type k1: u256
crates/dojo/lang/src/attribute_macros/element.rs Replaced filter_map with map in parse_members, removing member validation and error handling
crates/dojo/lang/src/attribute_macros/event.rs Removed &mut diagnostics parameter from parse_members call in from_struct method
crates/dojo/lang/src/attribute_macros/model.rs Removed &mut diagnostics parameter from parse_members call in from_struct method
scripts/rebuild_test_artifacts.sh Added command to run tests for the sozo binary

Sequence Diagram

sequenceDiagram
    participant Parser
    participant Members
    
    Parser->>Members: map() instead of filter_map()
    Note over Parser,Members: Unconditional member creation
    Members-->>Parser: Return all members without validation
Loading

Ohayo and happy coding, sensei! 🥷🏼🔧


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.

@glihm glihm changed the title Added dojo support for u256 as keys in models fix(dojo-lang): remove restriction for u256 as keys in models Jan 10, 2025
@glihm
Copy link
Collaborator

glihm commented Jan 10, 2025

Needs to be checked at Torii level, since multiple felt key are not supported at the moment.
@Larkooo for u256 we may have an exception since it will be stored as one string like a felt, and not like a struct.

@Larkooo
Copy link
Collaborator

Larkooo commented Jan 13, 2025

Needs to be checked at Torii level, since multiple felt key are not supported at the moment. @Larkooo for u256 we may have an exception since it will be stored as one string like a felt, and not like a struct.

I think it should be all good as we directly use the raw felts to serialize them into our keys string. We should still do some testing to be sure there are no other unexpected issues though

@Larkooo
Copy link
Collaborator

Larkooo commented Jan 13, 2025

and at that point, we could also use any type as the key. as they are all serializable to felt. if at the dojo level it is supported, we could support enums as keys

Copy link
Contributor

@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

🔭 Outside diff range comments (1)
crates/dojo/lang/src/attribute_macros/element.rs (1)

Line range hint 42-42: Unused parameter diagnostics

Ohayo, sensei! The diagnostics parameter in the parse_members function is now unused due to the removal of the validation logic. To keep the code clean, consider removing this parameter.

Apply this diff to remove the unused parameter:

 pub fn parse_members(
     db: &dyn SyntaxGroup,
     members: &[MemberAst],
-    diagnostics: &mut Vec<PluginDiagnostic>,
 ) -> Vec<Member> {
🧹 Nitpick comments (3)
crates/dojo/lang/src/attribute_macros/element.rs (1)

Line range hint 3-3: Remove unused imports

Ohayo, sensei! The imports cairo_lang_diagnostics::Severity and TypedStablePtr are no longer used and can be removed to tidy up the code.

Apply this diff to remove the unused imports:

 use cairo_lang_defs::patcher::RewriteNode;
-use cairo_lang_diagnostics::Severity;
 use cairo_lang_defs::plugin::PluginDiagnostic;
 use cairo_lang_syntax::node::ast::Member as MemberAst;
 use cairo_lang_syntax::node::db::SyntaxGroup;
-use cairo_lang_syntax::node::TypedStablePtr;
 use cairo_lang_syntax::node::helpers::QueryAttrs;

Also applies to: 7-7

crates/dojo/core-cairo-test/src/tests/model/model.cairo (2)

28-37: Include Foo3 in namespace_def() for proper testing

Ohayo, sensei! The new model Foo3 with a u256 key has been defined but is not included in the namespace_def() function. To ensure Foo3 is properly registered and tested, please add it to the namespace_def() resources.

Apply this diff to include Foo3:

 fn namespace_def() -> NamespaceDef {
     NamespaceDef {
         namespace: "dojo_cairo_test", resources: [
             TestResource::Model(m_Foo::TEST_CLASS_HASH.try_into().unwrap()),
             TestResource::Model(m_Foo2::TEST_CLASS_HASH.try_into().unwrap()),
+            TestResource::Model(m_Foo3::TEST_CLASS_HASH.try_into().unwrap()),
         ].span()
     }
 }

28-37: Add tests for Foo3 to validate u256 key functionality

Ohayo, sensei! To fully ensure that the u256 key functions correctly, consider adding tests for Foo3 similar to the existing tests for Foo and Foo2. This will help confirm that the changes meet the desired objectives.

Do you want me to help generate the test cases for Foo3?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 80ac6d1 and 2db1882.

⛔ Files ignored due to path filters (1)
  • crates/dojo/core-cairo-test/Scarb.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • crates/dojo/core-cairo-test/src/tests/model/model.cairo (1 hunks)
  • crates/dojo/lang/src/attribute_macros/element.rs (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: ci
crates/dojo/lang/src/attribute_macros/element.rs

[error] 3-3: Unused import: 'cairo_lang_diagnostics::Severity'


[error] 7-7: Unused import: 'TypedStablePtr'


[error] 42-42: Unused variable: 'diagnostics'. Consider prefixing with underscore if intentional


[error] 42-42: Inefficient argument type: '&mut Vec' should be '&mut [PluginDiagnostic]'

🔇 Additional comments (1)
crates/dojo/lang/src/attribute_macros/element.rs (1)

46-49: Simplification aligns with PR objectives

Ohayo, sensei! The changes to the parse_members function remove the previous validation logic, allowing u256 to be used as keys. This aligns perfectly with the PR objective to remove restrictions on u256 keys. The simplification enhances code readability.

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.

Thanks for the work here @bengineer42.

Copy link
Contributor

@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
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2db1882 and 3d375a1.

⛔ Files ignored due to path filters (6)
  • crates/dojo/core-cairo-test/Scarb.lock is excluded by !**/*.lock
  • crates/torii/types-test/Scarb.lock is excluded by !**/*.lock
  • examples/simple/Scarb.lock is excluded by !**/*.lock
  • examples/spawn-and-move/Scarb.lock is excluded by !**/*.lock
  • spawn-and-move-db.tar.gz is excluded by !**/*.gz
  • types-test-db.tar.gz is excluded by !**/*.gz
📒 Files selected for processing (5)
  • crates/dojo/core-cairo-test/Scarb.toml (1 hunks)
  • crates/dojo/lang/src/attribute_macros/element.rs (2 hunks)
  • crates/dojo/lang/src/attribute_macros/event.rs (1 hunks)
  • crates/dojo/lang/src/attribute_macros/model.rs (1 hunks)
  • scripts/rebuild_test_artifacts.sh (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: ensure-windows
  • GitHub Check: test
  • GitHub Check: test-hurl
  • GitHub Check: dojo-spawn-and-move-example-test
  • GitHub Check: dojo-core-test
🔇 Additional comments (5)
crates/dojo/core-cairo-test/Scarb.toml (1)

6-6: Ohayo sensei! Verify version bump compatibility.

The version change from rc.0 to 1.0.11 is significant. Please ensure this aligns with semantic versioning principles, especially since we're adding support for u256 keys which could be considered a feature addition.

✅ Verification successful

Ohayo sensei! Version bump is safe to proceed! ✨

The version change to 1.0.11 aligns perfectly with other core packages in the ecosystem. Since all internal dependencies use path-based references rather than version constraints, this change won't break any existing integrations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if this version bump affects other dependent packages
rg "dojo_cairo_test.*version" --type toml

Length of output: 43


Script:

#!/bin/bash
# First, find all Scarb.toml files
fd Scarb.toml

# Then, let's see their content to check dependencies
fd Scarb.toml --exec cat {}

# Also check if there's a changelog
fd -i changelog

Length of output: 4290

scripts/rebuild_test_artifacts.sh (1)

37-37: Ohayo sensei! The test command addition looks good.

The placement of the sozo test command is appropriate in the build sequence, ensuring that the core-cairo-test package (including the new u256 key support) is properly tested before database operations.

Let's verify that the test command works as expected:

✅ Verification successful

Ohayo sensei! Your test command is unique and valid!

The manifest exists and this is the first sozo test command in our shell scripts, making it a pioneer in our testing approach. Keep up the innovative spirit! 🚀

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if sozo test command is used elsewhere for consistency
rg "sozo test" --type sh

# Verify the manifest path exists
test -f crates/dojo/core-cairo-test/Scarb.toml && echo "Manifest exists" || echo "Manifest missing"

Length of output: 232

crates/dojo/lang/src/attribute_macros/element.rs (1)

37-44: The simplified parse_members implementation looks good, sensei!

The removal of type validation aligns with the PR objective to allow u256 as keys in models. The code is now more permissive and follows the principle of minimal restrictions.

Let's verify that this change doesn't break existing model declarations:

✅ Verification successful

Ohayo! The parse_members changes are safe and well-contained, sensei!

The removal of type validation doesn't affect the core requirement of having at least one #[key] attribute in models and events. The change only removes unnecessary type restrictions, making the system more flexible while maintaining structural integrity.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing model declarations to ensure compatibility
ast-grep --pattern 'struct $name {
  #[key]
  $field: u256,
  $$$
}'

Length of output: 70


Script:

#!/bin/bash
# Search for struct declarations with key attributes using a more permissive pattern
echo "=== Searching for structs with key attributes ==="
ast-grep --pattern 'struct $name {
    #[$attr]
    $field: $_,
    $$$
}'

# Search for any type validation related code
echo -e "\n=== Searching for type validation code ==="
rg -n "type.*valid" --type rust

Length of output: 463


Script:

#!/bin/bash
# Search for Cairo model declarations
echo "=== Searching for model declarations ==="
rg -l "#\[derive\(Model\)]" --type rust

# Search for element macro usage
echo -e "\n=== Searching for element macro usage ==="
rg -n "element!" --type rust -A 2

# Search for key attribute usage in Cairo files
echo -e "\n=== Searching for key attributes in Cairo files ==="
rg -n "#\[key\]" --type rust -A 1

Length of output: 1237

crates/dojo/lang/src/attribute_macros/event.rs (1)

61-61: Clean adaptation of parse_members call, sensei!

The change maintains essential validations while removing unnecessary type restrictions.

crates/dojo/lang/src/attribute_macros/model.rs (1)

75-75: Clean adaptation of parse_members call with good validation retention, sensei!

The change maintains essential model validations while enabling u256 keys. Consider adding test cases specifically for models with u256 keys to ensure proper serialization and storage.

Let's verify the test coverage:

use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::helpers::QueryAttrs;
use cairo_lang_syntax::node::{Terminal, TypedStablePtr, TypedSyntaxNode};
use cairo_lang_syntax::node::{Terminal, TypedSyntaxNode};
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Ohayo! The Terminal import is indeed unused, sensei!

The Terminal trait is imported but never used throughout the file. You can safely remove this import.

🔗 Analysis chain

Ohayo! The Terminal import appears to be unused, sensei.

The Terminal trait is imported but not used in the modified code.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify if Terminal is used in the file
rg "Terminal" crates/dojo/lang/src/attribute_macros/element.rs

Length of output: 120


Script:

#!/bin/bash
# Show the entire file content
echo "=== Full file content ==="
cat crates/dojo/lang/src/attribute_macros/element.rs

# Look for potential indirect usage patterns
echo -e "\n=== Checking for potential Terminal-related patterns ==="
ast-grep --pattern 'impl $_ for $_' crates/dojo/lang/src/attribute_macros/element.rs

Length of output: 3467

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.

3 participants