Skip to content

Commit

Permalink
Moved hypot to native function to guarantee correct implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
rben01 committed Dec 3, 2024
1 parent eb722e7 commit 05859b9
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 11 deletions.
3 changes: 2 additions & 1 deletion core/desugarer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ struct BuiltinDecl {
std::vector<UString> params;
};

static unsigned long max_builtin = 39;
static unsigned long max_builtin = 40;
BuiltinDecl jsonnet_builtin_decl(unsigned long builtin)
{
switch (builtin) {
Expand Down Expand Up @@ -80,6 +80,7 @@ BuiltinDecl jsonnet_builtin_decl(unsigned long builtin)
case 37: return {U"encodeUTF8", {U"str"}};
case 38: return {U"decodeUTF8", {U"arr"}};
case 39: return {U"atan2", {U"y", U"x"}};
case 40: return {U"hypot", {U"a", U"b"}};
default:
std::cerr << "INTERNAL ERROR: Unrecognized builtin function: " << builtin << std::endl;
std::abort();
Expand Down
8 changes: 8 additions & 0 deletions core/vm.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -938,6 +938,7 @@ class Interpreter {
builtins["encodeUTF8"] = &Interpreter::builtinEncodeUTF8;
builtins["decodeUTF8"] = &Interpreter::builtinDecodeUTF8;
builtins["atan2"] = &Interpreter::builtinAtan2;
builtins["hypot"] = &Interpreter::builtinHypot;

DesugaredObject *stdlib = makeStdlibAST(alloc, "__internal__");
jsonnet_static_analysis(stdlib);
Expand Down Expand Up @@ -1107,6 +1108,13 @@ class Interpreter {
return nullptr;
}

const AST *builtinHypot(const LocationRange &loc, const std::vector<Value> &args)
{
validateBuiltinArgs(loc, "atan2", args, {Value::NUMBER, Value::NUMBER});
scratch = makeNumberCheck(loc, std::hypot(args[0].v.d, args[1].v.d));
return nullptr;
}

const AST *builtinType(const LocationRange &, const std::vector<Value> &args)
{
switch (args[0].t) {
Expand Down
10 changes: 0 additions & 10 deletions stdlib/std.jsonnet
Original file line number Diff line number Diff line change
Expand Up @@ -267,16 +267,6 @@ limitations under the License.
deg2rad(x):: x * std.pi / 180,
rad2deg(x):: x * 180 / std.pi,

hypot(a, b)::
// copied from
// https://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/
local a_abs = std.abs(a);
local b_abs = std.abs(b);
local max = std.max(a_abs, b_abs);
local min = std.min(a_abs, b_abs);
local r = min / max;
max * std.sqrt(1 + r * r),

log2(x):: std.log(x) / std.log(2),
log10(x):: std.log(x) / std.log(10),

Expand Down

0 comments on commit 05859b9

Please sign in to comment.