Skip to content

contract self implementation #7030

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

Open
wants to merge 26 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
e5a5bcc
feat: anonymuos abi for contract self impl
hey-ewan Mar 23, 2025
167c7f8
refactor: live swaylang test
hey-ewan Mar 23, 2025
36f83ca
code comments
hey-ewan Mar 23, 2025
1ec63fc
Merge branch 'master' into contract-self-impl
hey-ewan Mar 24, 2025
25b03ab
reversed altered test
hey-ewan Mar 24, 2025
722eac6
fix: breaking changes
hey-ewan Mar 24, 2025
492cf37
Merge branch 'master' into contract-self-impl
hey-ewan Mar 26, 2025
a09c390
Merge branch 'master' into contract-self-impl
hey-ewan Mar 28, 2025
a2c4e25
refactor: `__AnonymousAbi_{}` > `_AnonymousAbi_{}`
hey-ewan Mar 28, 2025
6902f46
`contract_abi_auto_impl` test
hey-ewan Mar 28, 2025
8c76a52
fix: forced `_AnonymousAbi_N` generation
hey-ewan Mar 28, 2025
79b1ea2
removed `std` dep from test
hey-ewan Mar 31, 2025
1bcc27e
fix: bad tests
hey-ewan Mar 31, 2025
1ef79a5
Merge branch 'master' into contract-self-impl
hey-ewan Mar 31, 2025
6787f51
fix: breaking changes
hey-ewan Mar 31, 2025
57a41e3
Merge branch 'master' into contract-self-impl
IGI-111 Apr 4, 2025
4026959
fix: breaking changes
hey-ewan Apr 4, 2025
2d5a8cc
Merge branch 'master' into contract-self-impl
hey-ewan Apr 7, 2025
e03feea
Merge branch 'master' into contract-self-impl
hey-ewan Apr 8, 2025
68bdc9a
refactor: included `validate_abi` to `test.toml`
hey-ewan Apr 8, 2025
9698e97
Merge branch 'master' into contract-self-impl
hey-ewan Apr 8, 2025
5255d0a
chore: derive names from project manifest `Forc.toml`
hey-ewan Apr 8, 2025
ab8ecd7
Merge branch 'master' into contract-self-impl
hey-ewan Apr 9, 2025
702ea46
Merge branch 'master' into contract-self-impl
hey-ewan Apr 10, 2025
48af8e8
Merge branch 'master' into contract-self-impl
hey-ewan Apr 14, 2025
2a13667
Merge branch 'master' into contract-self-impl
hey-ewan Apr 21, 2025
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
10 changes: 10 additions & 0 deletions sway-core/src/transform/to_parsed_lang/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ pub struct Context {

/// Keeps track of the implementing type as we convert the tree.
pub(crate) implementing_type: Option<Declaration>,

/// Unique suffix used to generate unique names for anonymous ABIs
anon_abi_suffix: usize,
}

impl Context {
Expand All @@ -47,9 +50,16 @@ impl Context {
for_unique_suffix: std::default::Default::default(),
program_type: std::default::Default::default(),
implementing_type: None,
anon_abi_suffix: 0,
}
}

/// Returns a unique suffix used to generate a unique name for an anonymous ABI
pub fn next_anon_suffix(&mut self) -> usize {
self.anon_abi_suffix += 1;
self.anon_abi_suffix
}

/// Updates the value of `module_has_configurable_block`.
pub fn set_module_has_configurable_block(&mut self, val: bool) {
self.module_has_configurable_block = val;
Expand Down
130 changes: 127 additions & 3 deletions sway-core/src/transform/to_parsed_lang/convert_parse_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,13 @@ pub fn item_to_ast_nodes(
decl(trait_decl)
}
ItemKind::Impl(item_impl) => {
let impl_decl = item_impl_to_declaration(context, handler, engines, item_impl)?;
context.implementing_type = Some(impl_decl.clone());
decl(impl_decl)
match handle_impl_contract(context, handler, engines, item_impl.clone(), span.clone()) {
Ok(contents) if !contents.is_empty() => contents,
_ => {
let impl_decl = item_impl_to_declaration(context, handler, engines, item_impl)?;
decl(impl_decl)
}
}
}
ItemKind::Abi(item_abi) => {
let abi_decl = Declaration::AbiDeclaration(item_abi_to_abi_declaration(
Expand Down Expand Up @@ -846,6 +850,126 @@ pub fn item_impl_to_declaration(
}
}

fn handle_impl_contract(
context: &mut Context,
handler: &Handler,
engines: &Engines,
item_impl: ItemImpl,
span: Span,
) -> Result<Vec<AstNodeContent>, ErrorEmitted> {
let implementing_for = ty_to_type_argument(context, handler, engines, item_impl.ty)?;

// Only handle if this is an impl Contract block
if let TypeInfo::Contract = &*engines.te().get(implementing_for.type_id) {
// Check if there's an explicit trait being implemented
match item_impl.trait_opt {
Some((_, _)) => return Ok(vec![]),
None => {
// Generate unique name for anonymous ABI
let anon_abi_name = Ident::new_with_override(
format!("_AnonymousAbi_{}", context.next_anon_suffix()),
span.clone(),
);

// Convert the methods to ABI interface
let mut interface_surface = Vec::new();
for item in &item_impl.contents.inner {
match &item.value {
sway_ast::ItemImplItem::Fn(fn_item) => {
let fn_decl = fn_signature_to_trait_fn(
context,
handler,
engines,
fn_item.fn_signature.clone(),
Attributes::default(),
)?;

// Validate parameters for mutability
let fn_decl_ref = engines.pe().get_trait_fn(&fn_decl);
error_if_self_param_is_not_allowed(
context,
handler,
engines,
&fn_decl_ref.parameters,
"an ABI method signature",
)?;

interface_surface.push(TraitItem::TraitFn(fn_decl));
}
_ => continue,
}
}

// Create ABI declaration
let abi_decl = AbiDeclaration {
name: anon_abi_name.clone(),
attributes: Attributes::default(),
interface_surface: interface_surface.clone(),
methods: vec![],
supertraits: vec![],
span: span.clone(),
};

// Insert ABI declaration
let abi_decl_id = engines.pe().insert(abi_decl);
let impl_item_parent = (&*engines.te().get(implementing_for.type_id)).into();

// Convert original impl items to ImplItems
let items = item_impl
.contents
.inner
.into_iter()
.filter_map(|item| {
let (_, attributes) = attr_decls_to_attributes(
&item.attributes,
|attr| attr.can_annotate_impl_item(&item.value, impl_item_parent),
item.value.friendly_name(impl_item_parent),
);
match item.value {
sway_ast::ItemImplItem::Fn(fn_item) => item_fn_to_function_declaration(
context, handler, engines, fn_item, attributes, None, None, None,
)
.ok()
.map(ImplItem::Fn),
_ => None,
}
})
.collect();

// Convert impl Contract to impl trait
let impl_trait = ImplSelfOrTrait {
is_self: false,
impl_type_parameters: vec![],
impl_const_generics_parameters: vec![],
trait_name: CallPath {
prefixes: vec![],
suffix: anon_abi_name,
callpath_type: CallPathType::Ambiguous,
},
trait_type_arguments: vec![],
trait_decl_ref: Some(crate::decl_engine::ParsedInterfaceDeclId::Abi(
abi_decl_id,
)),
implementing_for,
items,
block_span: span.clone(),
};

let impl_trait_id = engines.pe().insert(impl_trait);

// Return both declarations as AST nodes
return Ok(vec![
AstNodeContent::Declaration(Declaration::AbiDeclaration(abi_decl_id)),
AstNodeContent::Declaration(Declaration::ImplSelfOrTrait(impl_trait_id)),
]);
}
}
}

// Not a Contract impl, return None
Ok(vec![])
}

fn path_type_to_call_path_and_type_arguments(
context: &mut Context,
handler: &Handler,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[[package]]
name = "contract_abi_auto_impl"
source = "member"
dependencies = ["std"]

[[package]]
name = "std"
source = "path+from-root-8ECB7FD43A4A6D77"
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[project]
name = "contract_abi_auto_impl"
authors = ["Fuel Labs <[email protected]>"]
entry = "main.sw"
license = "Apache-2.0"

[dependencies]
std = { path = "../../../../reduced_std_libs/sway-lib-std-assert" }
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
contract;

impl Contract {
fn impl_method() -> u64 { 42 }
}

#[test]
fn tests() {
let caller = abi(_AnonymousAbi_1, CONTRACT_ID);
assert(caller.impl_method() == 42)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
category = "unit_tests_pass"
Loading