Skip to content

Commit 05859b9

Browse files
committed
Moved hypot to native function to guarantee correct implementation
1 parent eb722e7 commit 05859b9

File tree

3 files changed

+10
-11
lines changed

3 files changed

+10
-11
lines changed

core/desugarer.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ struct BuiltinDecl {
3636
std::vector<UString> params;
3737
};
3838

39-
static unsigned long max_builtin = 39;
39+
static unsigned long max_builtin = 40;
4040
BuiltinDecl jsonnet_builtin_decl(unsigned long builtin)
4141
{
4242
switch (builtin) {
@@ -80,6 +80,7 @@ BuiltinDecl jsonnet_builtin_decl(unsigned long builtin)
8080
case 37: return {U"encodeUTF8", {U"str"}};
8181
case 38: return {U"decodeUTF8", {U"arr"}};
8282
case 39: return {U"atan2", {U"y", U"x"}};
83+
case 40: return {U"hypot", {U"a", U"b"}};
8384
default:
8485
std::cerr << "INTERNAL ERROR: Unrecognized builtin function: " << builtin << std::endl;
8586
std::abort();

core/vm.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -938,6 +938,7 @@ class Interpreter {
938938
builtins["encodeUTF8"] = &Interpreter::builtinEncodeUTF8;
939939
builtins["decodeUTF8"] = &Interpreter::builtinDecodeUTF8;
940940
builtins["atan2"] = &Interpreter::builtinAtan2;
941+
builtins["hypot"] = &Interpreter::builtinHypot;
941942

942943
DesugaredObject *stdlib = makeStdlibAST(alloc, "__internal__");
943944
jsonnet_static_analysis(stdlib);
@@ -1107,6 +1108,13 @@ class Interpreter {
11071108
return nullptr;
11081109
}
11091110

1111+
const AST *builtinHypot(const LocationRange &loc, const std::vector<Value> &args)
1112+
{
1113+
validateBuiltinArgs(loc, "atan2", args, {Value::NUMBER, Value::NUMBER});
1114+
scratch = makeNumberCheck(loc, std::hypot(args[0].v.d, args[1].v.d));
1115+
return nullptr;
1116+
}
1117+
11101118
const AST *builtinType(const LocationRange &, const std::vector<Value> &args)
11111119
{
11121120
switch (args[0].t) {

stdlib/std.jsonnet

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -267,16 +267,6 @@ limitations under the License.
267267
deg2rad(x):: x * std.pi / 180,
268268
rad2deg(x):: x * 180 / std.pi,
269269

270-
hypot(a, b)::
271-
// copied from
272-
// https://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/
273-
local a_abs = std.abs(a);
274-
local b_abs = std.abs(b);
275-
local max = std.max(a_abs, b_abs);
276-
local min = std.min(a_abs, b_abs);
277-
local r = min / max;
278-
max * std.sqrt(1 + r * r),
279-
280270
log2(x):: std.log(x) / std.log(2),
281271
log10(x):: std.log(x) / std.log(10),
282272

0 commit comments

Comments
 (0)