diff --git a/compiler/builtins.js b/compiler/builtins.js index c77f8e76..3cbb83fd 100644 --- a/compiler/builtins.js +++ b/compiler/builtins.js @@ -1473,36 +1473,6 @@ export const BuiltinFuncs = () => { return out; }); - comptime('__Math_max', TYPES.number, (scope, decl, { generate }) => { - const out = [ - number(-Infinity) - ]; - - for (let i = 0; i < decl.arguments.length; i++) { - out.push( - ...generate(scope, decl.arguments[i]), - [ Opcodes.f64_max ] - ); - } - - return out; - }, 2); - - comptime('__Math_min', TYPES.number, (scope, decl, { generate }) => { - const out = [ - number(Infinity) - ]; - - for (let i = 0; i < decl.arguments.length; i++) { - out.push( - ...generate(scope, decl.arguments[i]), - [ Opcodes.f64_min ] - ); - } - - return out; - }, 2); - comptime('__Porffor_printStatic', TYPES.undefined, (scope, decl, { printStaticStr }) => { const str = decl.arguments[0].value; const out = printStaticStr(scope, str); diff --git a/compiler/builtins/math.ts b/compiler/builtins/math.ts index eec36217..9a054676 100644 --- a/compiler/builtins/math.ts +++ b/compiler/builtins/math.ts @@ -582,4 +582,56 @@ export const __Math_sumPrecise = (values: any[]): number => { // todo: free large and small return sum; +}; + +export const __Math_max = (...args: any[]): number => { + let max: number = -Infinity; + let sawNaN: boolean = false; + const len: i32 = args.length; + + for (let i: i32 = 0; i < len; i++) { + const n: number = __ecma262_ToNumber(args[i]); + if (Number.isNaN(n)) { + sawNaN = true; + continue; + } + + if (n > max) { + max = n; + continue; + } + + if (n == 0 && max == 0 && 1 / n > 1 / max) { + max = n; + } + } + + if (sawNaN) return NaN; + return max; +}; + +export const __Math_min = (...args: any[]): number => { + let min: number = Infinity; + let sawNaN: boolean = false; + const len: i32 = args.length; + + for (let i: i32 = 0; i < len; i++) { + const n: number = __ecma262_ToNumber(args[i]); + if (Number.isNaN(n)) { + sawNaN = true; + continue; + } + + if (n < min) { + min = n; + continue; + } + + if (n == 0 && min == 0 && 1 / n < 1 / min) { + min = n; + } + } + + if (sawNaN) return NaN; + return min; }; \ No newline at end of file