polserver/pol-core/bscript/compiler/ast/Function.cpp
Kevin Eady e3512d001b Add scope handling for functions and variables (#690)
* Add Report.debug

* Implement function call scoping

* Implement variable scoping
- Rename `Identifier::scope` to `calling_scope`, and concatenate the identifier scope into `name` if necessary.
- Track current scope in SemanticAnalyzer, similar to UserFunctionVisitor.
- Use current scope in SemanticAnalyzer when visiting identifiers.

* Update grammar for `::identifier` global scoping

* Introduce ScopableName for function resolution

* Address review comments
- Check for display_debugs missing

* Add ScopableName for identifier resolution

* Some cleanup
- Remove `Identifier::calling_scope`, as it is tracked in the semantic
  analyzer
- Refactor `ScopeName::exists` to `global` for better clarification of
  its use
- Removed `X::maybe_scoped_string/name`

* Address self-review comments

* Rename `Function::module_name` to `scope`
2024-10-10 18:06:04 +02:00

69 lines
No EOL
1.9 KiB
C++

#include "Function.h"
#include "bscript/compiler/ast/FunctionBody.h"
#include "bscript/compiler/ast/FunctionParameterDeclaration.h"
#include "bscript/compiler/ast/FunctionParameterList.h"
namespace Pol::Bscript::Compiler
{
Function::Function( const SourceLocation& source_location, std::string scope, std::string name,
std::unique_ptr<FunctionParameterList> parameter_list,
std::unique_ptr<FunctionBody> body )
: Node( source_location ), scope( std::move( scope ) ), name( std::move( name ) )
{
children.reserve( 2 );
children.push_back( std::move( parameter_list ) );
children.push_back( std::move( body ) );
}
Function::Function( const SourceLocation& source_location, std::string scope, std::string name,
std::unique_ptr<FunctionParameterList> parameter_list )
: Node( source_location, std::move( parameter_list ) ),
scope( std::move( scope ) ),
name( std::move( name ) )
{
}
unsigned Function::parameter_count() const
{
return static_cast<unsigned>( children.at( 0 )->children.size() );
}
bool Function::is_variadic() const
{
// The variadic argument, if present, is the last one
if ( parameter_count() > 0 )
{
const auto& parameter_list = children.at( 0 );
auto parameter =
static_cast<FunctionParameterDeclaration*>( parameter_list->children.back().get() );
return parameter->rest;
}
return false;
}
std::string Function::scoped_name() const
{
if ( scope.empty() )
{
return name;
}
return fmt::format( "{}::{}", scope, name );
}
std::vector<std::reference_wrapper<FunctionParameterDeclaration>> Function::parameters()
{
std::vector<std::reference_wrapper<FunctionParameterDeclaration>> params;
auto& param_list = child<FunctionParameterList>( 0 );
for ( auto& param : param_list.children )
{
params.emplace_back( *static_cast<FunctionParameterDeclaration*>( param.get() ) );
}
return params;
}
} // namespace Pol::Bscript::Compiler