Skip to content
This repository has been archived by the owner on Nov 11, 2024. It is now read-only.

feat: makes models upgradeable #14

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions crates/compiler/src/compiler/annotation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ const DOJO_ANNOTATION_FILE_NAME: &str = "annotations";

pub trait AnnotationInfo {
fn filename(&self) -> String;
fn qualified_path(&self) -> String;
fn tag(&self) -> String;
}

/// Represents a member of a struct.
Expand Down Expand Up @@ -115,30 +117,60 @@ impl AnnotationInfo for ModelAnnotation {
fn filename(&self) -> String {
naming::get_filename_from_tag(&self.tag)
}
fn qualified_path(&self) -> String {
self.qualified_path.clone()
}
fn tag(&self) -> String {
self.tag.clone()
}
}

impl AnnotationInfo for EventAnnotation {
fn filename(&self) -> String {
naming::get_filename_from_tag(&self.tag)
}
fn qualified_path(&self) -> String {
self.qualified_path.clone()
}
fn tag(&self) -> String {
self.tag.clone()
}
}

impl AnnotationInfo for ContractAnnotation {
fn filename(&self) -> String {
naming::get_filename_from_tag(&self.tag)
}
fn qualified_path(&self) -> String {
self.qualified_path.clone()
}
fn tag(&self) -> String {
self.tag.clone()
}
}

impl AnnotationInfo for StarknetContractAnnotation {
fn filename(&self) -> String {
self.qualified_path.replace(CAIRO_PATH_SEPARATOR, "_")
}
fn qualified_path(&self) -> String {
self.qualified_path.clone()
}
fn tag(&self) -> String {
self.name.clone()
}
}

impl AnnotationInfo for WorldAnnotation {
fn filename(&self) -> String {
WORLD_CONTRACT_TAG.to_string()
}
fn qualified_path(&self) -> String {
self.qualified_path.clone()
}
fn tag(&self) -> String {
self.tag.clone()
}
}

/// An abstract representation of the annotations of dojo resources.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,16 +258,7 @@ fn get_version(
match arg_value {
Expr::Literal(ref value) => {
if let Ok(value) = value.text(db).parse::<u8>() {
if value <= DEFAULT_VERSION {
value
} else {
diagnostics.push(PluginDiagnostic {
message: format!("{attribute_name} version {} not supported", value),
stable_ptr: arg_value.stable_ptr().untyped(),
severity: Severity::Error,
});
DEFAULT_VERSION
}
value
} else {
diagnostics.push(PluginDiagnostic {
message: format!(
Expand Down
2 changes: 1 addition & 1 deletion crates/compiler/src/plugin/attribute_macros/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use crate::plugin::derive_macros::{
extract_derive_attr_names, handle_derive_attrs, DOJO_INTROSPECT_DERIVE, DOJO_PACKED_DERIVE,
};

use super::element::{
use super::common::{
compute_namespace, parse_members, serialize_keys_and_values, CommonStructParameters,
StructParameterParser,
};
Expand Down
2 changes: 1 addition & 1 deletion crates/compiler/src/plugin/attribute_macros/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
//!
//! An attribute macros is a macro that is used to generate code generally for a struct, enum, module or trait.

pub mod common;
pub mod contract;
pub mod element;
pub mod event;
pub mod interface;
pub mod model;
Expand Down
21 changes: 6 additions & 15 deletions crates/compiler/src/plugin/attribute_macros/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ use crate::plugin::derive_macros::{
extract_derive_attr_names, handle_derive_attrs, DOJO_INTROSPECT_DERIVE, DOJO_PACKED_DERIVE,
};

use super::element::{
use super::common::{
compute_namespace, deserialize_keys_and_values, parse_members, serialize_keys_and_values,
serialize_member_ty, CommonStructParameters, StructParameterParser, DEFAULT_VERSION,
serialize_member_ty, CommonStructParameters, StructParameterParser,
};
use super::patches::MODEL_PATCH;
use super::DOJO_MODEL_ATTR;
Expand Down Expand Up @@ -86,19 +86,10 @@ impl DojoModel {
let model_name_hash = naming::compute_bytearray_hash(&model_name);
let model_namespace_hash = naming::compute_bytearray_hash(&model_namespace);

let (model_version, model_selector) = match parameters.version {
0 => (
RewriteNode::Text("0".to_string()),
RewriteNode::Text(format!("\"{model_name}\"")),
),
_ => (
RewriteNode::Text(DEFAULT_VERSION.to_string()),
RewriteNode::Text(
naming::compute_selector_from_hashes(model_namespace_hash, model_name_hash)
.to_string(),
),
),
};
let model_version = RewriteNode::Text(parameters.version.to_string());
let model_selector = RewriteNode::Text(
naming::compute_selector_from_hashes(model_namespace_hash, model_name_hash).to_string(),
);

let members = parse_members(db, &struct_ast.members(db).elements(db), &mut diagnostics);
let mut serialized_keys: Vec<RewriteNode> = vec![];
Expand Down
96 changes: 83 additions & 13 deletions crates/compiler/src/plugin/attribute_macros/patches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,16 @@ pub impl $type_name$ModelImpl of dojo::model::Model<$type_name$> {
Self::layout()
}

#[inline(always)]
fn schema() -> dojo::meta::introspect::Struct {
if let dojo::meta::introspect::Ty::Struct(s) = dojo::meta::introspect::Introspect::<$type_name$>::ty() {
s
}
else {
panic!(\"Model `$type_name$`: invalid schema.\")
}
}

#[inline(always)]
fn packed_size() -> Option<usize> {
dojo::meta::layout::compute_packed_size(Self::layout())
Expand Down Expand Up @@ -440,8 +450,38 @@ pub mod $contract_name$ {
use super::$type_name$;
use super::I$contract_name$;

use dojo::contract::components::world_provider::{world_provider_cpt, world_provider_cpt::InternalTrait as WorldProviderInternal, IWorldProvider};
use dojo::contract::components::upgradeable::upgradeable_cpt;

component!(path: world_provider_cpt, storage: world_provider, event: WorldProviderEvent);
component!(path: upgradeable_cpt, storage: upgradeable, event: UpgradeableEvent);

#[abi(embed_v0)]
impl WorldProviderImpl = world_provider_cpt::WorldProviderImpl<ContractState>;

#[abi(embed_v0)]
impl UpgradeableImpl = upgradeable_cpt::UpgradeableImpl<ContractState>;

#[event]
#[derive(Drop, starknet::Event)]
enum Event {
UpgradeableEvent: upgradeable_cpt::Event,
WorldProviderEvent: world_provider_cpt::Event,
}

#[storage]
struct Storage {}
struct Storage {
#[substorage(v0)]
upgradeable: upgradeable_cpt::Storage,

#[substorage(v0)]
world_provider: world_provider_cpt::Storage,
}

#[constructor]
fn constructor(ref self: ContractState) {
self.world_provider.initializer();
}

#[abi(embed_v0)]
impl DojoModelImpl of dojo::model::IModel<ContractState>{
Expand Down Expand Up @@ -485,8 +525,8 @@ pub mod $contract_name$ {
dojo::model::Model::<$type_name$>::layout()
}

fn schema(self: @ContractState) -> dojo::meta::introspect::Ty {
dojo::meta::introspect::Introspect::<$type_name$>::ty()
fn schema(self: @ContractState) -> dojo::meta::introspect::Struct {
dojo::model::Model::<$type_name$>::schema()
}
}

Expand Down Expand Up @@ -543,11 +583,6 @@ pub impl $type_name$EventImpl of dojo::event::Event<$type_name$> {
$event_selector$
}

#[inline(always)]
fn instance_selector(self: @$type_name$) -> felt252 {
Self::selector()
}

#[inline(always)]
fn name_hash() -> felt252 {
$event_name_hash$
Expand All @@ -564,8 +599,13 @@ pub impl $type_name$EventImpl of dojo::event::Event<$type_name$> {
}

#[inline(always)]
fn schema(self: @$type_name$) -> dojo::meta::introspect::Ty {
dojo::meta::introspect::Introspect::<$type_name$>::ty()
fn schema() -> dojo::meta::introspect::Struct {
if let dojo::meta::introspect::Ty::Struct(s) = dojo::meta::introspect::Introspect::<$type_name$>::ty() {
s
}
else {
panic!(\"Event `$type_name$`: invalid schema.\")
}
}

#[inline(always)]
Expand Down Expand Up @@ -608,8 +648,38 @@ pub impl $type_name$EventImplTest of dojo::event::EventTest<$type_name$> {
pub mod $contract_name$ {
use super::$type_name$;

use dojo::contract::components::world_provider::{world_provider_cpt, world_provider_cpt::InternalTrait as WorldProviderInternal, IWorldProvider};
use dojo::contract::components::upgradeable::upgradeable_cpt;

component!(path: world_provider_cpt, storage: world_provider, event: WorldProviderEvent);
component!(path: upgradeable_cpt, storage: upgradeable, event: UpgradeableEvent);

#[abi(embed_v0)]
impl WorldProviderImpl = world_provider_cpt::WorldProviderImpl<ContractState>;

#[abi(embed_v0)]
impl UpgradeableImpl = upgradeable_cpt::UpgradeableImpl<ContractState>;

#[event]
#[derive(Drop, starknet::Event)]
enum Event {
UpgradeableEvent: upgradeable_cpt::Event,
WorldProviderEvent: world_provider_cpt::Event,
}

#[storage]
struct Storage {}
struct Storage {
#[substorage(v0)]
upgradeable: upgradeable_cpt::Storage,

#[substorage(v0)]
world_provider: world_provider_cpt::Storage,
}

#[constructor]
fn constructor(ref self: ContractState) {
self.world_provider.initializer();
}

#[abi(embed_v0)]
impl DojoEventImpl of dojo::event::IEvent<ContractState>{
Expand Down Expand Up @@ -645,8 +715,8 @@ pub mod $contract_name$ {
dojo::event::Event::<$type_name$>::layout()
}

fn schema(self: @ContractState) -> dojo::meta::introspect::Ty {
dojo::meta::introspect::Introspect::<$type_name$>::ty()
fn schema(self: @ContractState) -> dojo::meta::introspect::Struct {
dojo::event::Event::<$type_name$>::schema()
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use cairo_lang_diagnostics::Severity;
use cairo_lang_syntax::node::{ast, TypedStablePtr, TypedSyntaxNode};

use super::unsupported_arg_diagnostic;
use super::utils::{extract_namespaces, load_manifest_models_and_namespaces};
use super::utils::{extract_namespaces, load_resources_and_namespaces_from_annotations};

#[derive(Debug, Default)]
pub struct GetModelsTestClassHashes;
Expand Down Expand Up @@ -62,22 +62,24 @@ impl InlineMacroExprPlugin for GetModelsTestClassHashes {
vec![]
};

let (_namespaces, models) =
match load_manifest_models_and_namespaces(metadata.cfg_set, &whitelisted_namespaces) {
Ok((namespaces, models)) => (namespaces, models),
Err(_e) => {
return InlinePluginResult {
code: None,
diagnostics: vec![PluginDiagnostic {
stable_ptr: syntax.stable_ptr().untyped(),
message: "Failed to load models and namespaces, ensure you have run \
let (_namespaces, models) = match load_resources_and_namespaces_from_annotations(
metadata.cfg_set,
&whitelisted_namespaces,
) {
Ok((namespaces, models, _)) => (namespaces, models),
Err(_e) => {
return InlinePluginResult {
code: None,
diagnostics: vec![PluginDiagnostic {
stable_ptr: syntax.stable_ptr().untyped(),
message: "Failed to load models and namespaces, ensure you have run \
`sozo build` first."
.to_string(),
severity: Severity::Error,
}],
};
}
};
.to_string(),
severity: Severity::Error,
}],
};
}
};

let mut builder = PatchBuilder::new(db, syntax);

Expand Down
Loading
Loading