From 3bf5657cf37ed083650fce08129fb2df15de22ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Garcia?= Date: Sun, 4 Mar 2018 09:34:57 -0300 Subject: [PATCH] Improve builtin `packToken::str_custom()` implementation Before this commit the packToken::str() function when working on a MAP would check if the map had a "__str__" attribute, and if yes it would use it to stringify the MAP. However, there was no way to do a simillar specialization for other types such as user defined types. Now if you add a type specific function for a user defined type named "__str__" packToken::str() will use it to stringify any instances of this type. --- builtin-features/functions.h | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/builtin-features/functions.h b/builtin-features/functions.h index 6ce03ec..575f340 100644 --- a/builtin-features/functions.h +++ b/builtin-features/functions.h @@ -202,16 +202,27 @@ packToken default_extend(TokenMap scope) { // Example of replacement function for packToken::str(): std::string packToken_str(const TokenBase* base, uint32_t nest) { + const Function* func; + + // Find the TokenMap with the type specific functions + // for the type of the base token: + const TokenMap* typeFuncs; if (base->type == MAP) { - const TokenMap* map = static_cast(base); - // Check if this class has a custom stringify function: - const packToken* p_func = map->find("__str__"); - if (p_func && (*p_func)->type == FUNC) { - const Function* func = p_func->asFunc(); - TokenList args; - args.push(static_cast(nest)); - return Function::call(*map, func, &args, TokenMap()).asString(); - } + typeFuncs = static_cast(base); + } else { + typeFuncs = &calculator::type_attribute_map()[base->type]; + } + + // Check if this type has a custom stringify function: + const packToken* p_func = typeFuncs->find("__str__"); + if (p_func && (*p_func)->type == FUNC) { + // Return the result of this function passing the + // nesting level as first (and only) argument: + func = p_func->asFunc(); + packToken _this = packToken(base->clone()); + TokenList args; + args.push(static_cast(nest)); + return Function::call(_this, func, &args, TokenMap()).asString(); } // Return "" to ask for the normal `packToken::str()`