Skip to content

Commit

Permalink
feat: add built-in 'getattr' function
Browse files Browse the repository at this point in the history
  • Loading branch information
jacopodl committed Sep 21, 2023
1 parent 6f5caef commit 236164c
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions argon/vm/mod/builtins.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,41 @@ ARGON_FUNCTION(builtins_eval, eval,
return (ArObject *) result;
}

ARGON_FUNCTION(builtins_getattr, getattr,
"Access object attributes dynamically by providing the object and the attribute name as arguments.\n"
"\n"
"- Parameters:\n"
" - obj: The object from which to retrieve the attribute.\n"
" - name: A string representing the name of the attribute you want to access.\n"
"- KWParameters:\n"
" - default: A default value to return if the attribute does not exist.\n"
"- Returns: If the attribute exists within the object, its value is returned, "
"otherwise the default value if defined is returned.\n",
": obj, s: name", false, true) {
bool _static = false;

if (AR_GET_TYPE(*args) == type_type_)
_static = true;

auto *res = AttributeLoad(*args, args[1], _static);
if (res == nullptr) {
ArObject *def = nullptr;

if (kwargs != nullptr) {
def = DictLookup((Dict *) kwargs, "default");
if (def == nullptr && argon::vm::IsPanicking())
return nullptr;
}

if (def != nullptr)
argon::vm::DiscardLastPanic();

return def;
}

return res;
}

ARGON_FUNCTION(builtins_iscallable, iscallable,
"Return true if argument appears callable, false otherwise.\n"
"\n"
Expand Down Expand Up @@ -279,6 +314,7 @@ const ModuleEntry builtins_entries[] = {
MODULE_EXPORT_FUNCTION(builtins_bind),
MODULE_EXPORT_FUNCTION(builtins_exit),
MODULE_EXPORT_FUNCTION(builtins_eval),
MODULE_EXPORT_FUNCTION(builtins_getattr),
MODULE_EXPORT_FUNCTION(builtins_iscallable),
MODULE_EXPORT_FUNCTION(builtins_implements),
MODULE_EXPORT_FUNCTION(builtins_len),
Expand Down

0 comments on commit 236164c

Please sign in to comment.