Skip to content

Commit

Permalink
AST validate that a contract does not have a function with contract n…
Browse files Browse the repository at this point in the history
…ame (#117)

* AST validate that a contract does not have a function with contract name

* Update test

* Address feedback

* Change tests

* Update crates/sema/src/ast_passes.rs

Co-authored-by: DaniPopes <57450786+DaniPopes@users.noreply.github.com>

* Update crates/sema/src/ast_passes.rs

Co-authored-by: DaniPopes <57450786+DaniPopes@users.noreply.github.com>

* Add changes

---------

Co-authored-by: DaniPopes <57450786+DaniPopes@users.noreply.github.com>
  • Loading branch information
ferranbt and DaniPopes authored Nov 18, 2024
1 parent 7e164f4 commit c3b47d5
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
26 changes: 26 additions & 0 deletions crates/sema/src/ast_passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,32 @@ impl<'ast> Visit<'ast> for AstValidator<'_> {
self.walk_stmt(stmt)
}

fn visit_item_contract(
&mut self,
contract: &'ast ast::ItemContract<'ast>,
) -> ControlFlow<Self::BreakValue> {
let ast::ItemContract { kind: _, name: _, bases: _, body } = contract;

for item in body.iter() {
if let ast::ItemKind::Function(ast::ItemFunction { kind, header, body: _ }) = &item.kind
{
if *kind == ast::FunctionKind::Function {
if let Some(func_name) = header.name {
if func_name == contract.name {
self.dcx()
.err("functions are not allowed to have the same name as the contract")
.note("if you intend this to be a constructor, use `constructor(...) { ... }` to define it")
.span(func_name.span)
.emit();
}
}
}
}
}

self.walk_item_contract(contract)
}

// Intentionally override unused default implementations to reduce bloat.
fn visit_expr(&mut self, _expr: &'ast ast::Expr<'ast>) -> ControlFlow<Self::BreakValue> {
ControlFlow::Continue(())
Expand Down
5 changes: 5 additions & 0 deletions tests/ui/parser/contract_function_shared_name.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
contract C {
function C() public {} //~ ERROR: functions are not allowed to have the same name as the contract

function c() public {}
}
10 changes: 10 additions & 0 deletions tests/ui/parser/contract_function_shared_name.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
error: functions are not allowed to have the same name as the contract
--> ROOT/tests/ui/parser/contract_function_shared_name.sol:LL:CC
|
LL | function C() public {}
| ^
|
= note: if you intend this to be a constructor, use `constructor(...) { ... }` to define it

error: aborting due to 1 previous error

0 comments on commit c3b47d5

Please sign in to comment.