pathological.js (2260B)
1 // Let's calculate zero in some elaborate ways. 2 function testFancyZeroOffset(fancyZero, memType = 'i32') { 3 try { 4 const { mem } = wasmEvalText(`(module 5 (memory (export "mem") ${memType} 1) 6 (data (offset ${fancyZero}) "hi") 7 )`).exports; 8 const str = String.fromCharCode(...new Uint8Array(mem.buffer).slice(0, 2)); 9 assertEq(str, 'hi'); 10 } catch (e) { 11 const { getOffset } = wasmEvalText(`(module 12 (func (export "getOffset") (result ${memType}) 13 ${fancyZero} 14 ) 15 )`).exports; 16 console.log('Computed offset:', getOffset()); 17 throw e; 18 } 19 } 20 21 // Do plus one minus one a thousand times 22 testFancyZeroOffset('i32.const 0 ' + ( 23 '(i32.add (i32.const 1)) ' 24 + '(i32.sub (i32.const 1)) ' 25 ).repeat(1000)); 26 27 // Do some jank fibonacci 28 { 29 let fib = '(i32.const 1)\n' 30 let a = 1; let b = 1; let next; 31 for (let i = 0; i < 45; i++) { 32 fib += `(i32.const ${a})\n`; 33 fib += '(i32.add)\n'; 34 next = a + b; 35 a = b; 36 b = next; 37 } 38 fib += `(i32.sub (i32.const ${next}))\n`; 39 testFancyZeroOffset(fib); 40 } 41 42 // Run the collatz conjecture as long as possible 43 { 44 let val = 837799; // should reach 1 in 524 steps 45 let expr = `(i32.const ${val})\n`; 46 while (val != 1) { 47 if (val % 2 == 0) { 48 expr += `(i32.sub (i32.const ${val / 2}))\n`; // we can't divide in constant expressions lol 49 val /= 2; 50 } else { 51 expr += `(i32.mul (i32.const 3))\n`; 52 expr += `(i32.add (i32.const 1))\n`; 53 val = val * 3 + 1; 54 } 55 } 56 expr += `(i32.sub (i32.const 1))\n`; 57 testFancyZeroOffset(expr); 58 } 59 60 // The collatz conjecture would be even more fun with 64-bit numbers... 61 let val = 1899148184679; // should reach 1 in 1411 steps 62 let expr = `(i64.const ${val})\n`; 63 while (val != 1) { 64 if (val % 2 == 0) { 65 expr += `(i64.sub (i64.const ${val / 2}))\n`; // we can't divide in constant expressions lol 66 val /= 2; 67 } else { 68 expr += `(i64.mul (i64.const 3))\n`; 69 expr += `(i64.add (i64.const 1))\n`; 70 val = val * 3 + 1; 71 } 72 } 73 expr += `(i64.sub (i64.const 1))\n`; 74 testFancyZeroOffset(expr, 'i64');