Skip to content

Commit

Permalink
[cpp] fixed an issue where defining a free function with the same nam…
Browse files Browse the repository at this point in the history
…e as any struct's methods would cause them to be looked up wrongly. it is now completely safe to name a method the same as a free function. this relies on methods being a function_definition who's grandparent node is a struct_definition (struct_definition -> block -> function_definition)
  • Loading branch information
harrand committed May 24, 2024
1 parent a697d07 commit bcb5c1c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
15 changes: 11 additions & 4 deletions cpp/src/semal.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -201,14 +201,21 @@ namespace semal
while(path.size())
{
const ast::node& ancestor = tree.get(path);
const ast::node* distant_ancestor = nullptr;
if(path.size() >= 3)
{
auto distant_path = path; distant_path.pop_back(); distant_path.pop_back();
distant_ancestor = &tree.get(distant_path);
}
if(std::holds_alternative<ast::function_definition>(ancestor.payload))
{
const std::string& function_name = std::get<ast::function_definition>(ancestor.payload).func_name;
const function_t* found_func = this->try_find_function(function_name.c_str());
if(found_func == nullptr)
std::string function_name = std::get<ast::function_definition>(ancestor.payload).func_name;
bool is_method = distant_ancestor != nullptr && std::holds_alternative<ast::struct_definition>(distant_ancestor->payload);
if(is_method)
{
found_func = this->try_find_function(semal::mangle_method_name(function_name));
function_name = semal::mangle_method_name(function_name);
}
const function_t* found_func = this->try_find_function(function_name.c_str());
if(found_func == nullptr)
{
diag::ice("at: {}: internal compiler error: found a parent function of an AST node (named \"{}\"), but could not then retrieve the function data from semantic analysis state.", ancestor.meta.to_string(), function_name);
Expand Down
7 changes: 7 additions & 0 deletions samples/scratchpad.psy
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ puts :: (str : i8& const) -> u0 := extern;
main :: () -> i64
{
puts("hello world!");
print();

mydata : data := data{.id := 0};
mydata.print();
Expand All @@ -19,6 +20,7 @@ main :: () -> i64

ptr.increment();
ptr.print();
print();

return 0;
}
Expand All @@ -41,6 +43,11 @@ data :: struct
}
}

print :: () -> u0
{
puts("free-function print!");
}

== default : build ==
{
set_linkage_type(executable);
Expand Down

0 comments on commit bcb5c1c

Please sign in to comment.