Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 108 additions & 10 deletions src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,45 @@ export function parseInt(val: string, radix = 10) {
return strtol(val, null, radix);
}

// The number at the start of the text, after white space, as JavaScript reads it: NaN where there is none
// (`parseFloat("abc")`; strtod gave 0), "Infinity" spelled so only, and no hexadecimal ("0x10" is 0, strtod
// read 16)
export function parseFloat(val: string): number {
if (val == null) {
return Number.NaN;
}

let p = 0;
while (p < val.length) {
const space = val.charCodeAt(p);
if (space != 32 && (space < 9 || space > 13)) {
break;
}

p++;
}

const sign = p < val.length ? val.charCodeAt(p) : 0;
const q = sign == 43 /* + */ || sign == 45 /* - */ ? p + 1 : p;
const c = q < val.length ? val.charCodeAt(q) : 0;
const d = q + 1 < val.length ? val.charCodeAt(q + 1) : 0;
if (c == 73 /* I */) {
if (val.substring(q, q + 8) != "Infinity") {
return Number.NaN;
}

return sign == 45 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
}

const startsDigit = c >= 48 && c <= 57;
if (!startsDigit && !(c == 46 /* . */ && d >= 48 && d <= 57)) {
return Number.NaN;
}

if (c == 48 && (d == 120 /* x */ || d == 88 /* X */)) {
return sign == 45 ? -0.0 : 0.0;
}

return strtod(val, null);
}

Expand Down Expand Up @@ -1905,7 +1943,11 @@ export static class Math {
* @param x The value to be rounded to the nearest integer.
*/
public round(x: number): number {
return round(x);
// a half goes up, as JavaScript rounds it (Math.round(-2.5) is -2); C's round takes it away from zero (-3).
// Between -0.5 and 0 the result is -0. NaN and the infinities are themselves (x - r is NaN).
const r = floor(x);
const rounded = x - r >= 0.5 ? r + 1 : r;
return rounded == 0 && x < 0 ? -0.0 : rounded;
}

/**
Expand Down Expand Up @@ -3521,21 +3563,77 @@ export static class console {
}

private printData(fileNo: int, data: string[]): void {
switch (data.length) {
case 0:
break;
default:
this.print(fileNo, data[0]);
for (let i = 1; i < data.length; i++) {
this.print(fileNo, " ");
this.print(fileNo, data[i]);
}
// the arguments the first one's placeholders take (`console.log("%s: %d", name, n)`)
let next = 1;
if (data.length > 1 && data[0] != null && data[0].indexOf("%") >= 0) {
next = this.printFormat(fileNo, data);
} else if (data.length > 0) {
this.print(fileNo, data[0]);
}

for (let i = next; i < data.length; i++) {
this.print(fileNo, " ");
this.print(fileNo, data[i]);
}

this.print(fileNo, "\n");
}

// The first argument with its placeholders replaced by the arguments after it, as Node's
// util.format: %s %d %i %f %j %o %O %c each take the next argument (%c is CSS, and prints nothing),
// %% is "%". The arguments are strings already: %i is the integer part, the others the text
// itself. A placeholder with no argument left stays as it is. Returns the first argument not taken.
private printFormat(fileNo: int, data: string[]): int {
const format = data[0];
let next = 1;
let run = 0;
let i = 0;
while (i < format.length - 1) {
if (format.charCodeAt(i) != 37 /* % */) {
i++;
continue;
}

const c = format.charCodeAt(i + 1);
if (c == 37) {
this.print(fileNo, format.substring(run, i + 1));
i += 2;
run = i;
continue;
}

const takes = c == 115 /* s */ || c == 100 /* d */ || c == 105 /* i */ || c == 102 /* f */
|| c == 106 /* j */ || c == 111 /* o */ || c == 79 /* O */ || c == 99 /* c */;
if (!takes || next >= data.length) {
i++;
continue;
}

this.print(fileNo, format.substring(run, i));
const value = data[next++];
if (c == 105) {
const dot = value == null ? -1 : value.indexOf(".");
this.print(fileNo, dot >= 0 ? value.substring(0, dot) : value);
} else if (c != 99) {
this.print(fileNo, value);
}

i += 2;
run = i;
}

this.print(fileNo, format.substring(run));
return next;
}

private print(fileNo: int, data: string): void {
// a null string (`console.log(s)` of a `let s: string = null` without strict null checks) is "null"; it was
// read through
if (data == null) {
stdio_write(fileNo, "null", 4);
return;
}

// stdio_write, not write: going through stdio keeps this in the same buffer
// as print()/assert(), which lower to puts(). See src/wrappers/io.cpp.
stdio_write(fileNo, data, data.length);
Expand Down
51 changes: 51 additions & 0 deletions tests/node_output_forms.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// @strict-null false
// What a comparison of programs' output with Node's found (2026-11-30):
// - Math.round rounded a half away from zero (C's round): Math.round(-2.5) was -3, JavaScript's is -2
// - parseFloat gave 0 where the text has no number ("abc"; JavaScript's is NaN), and read hexadecimal
// - console.log of a null string read through it (a crash); "%s" and the other placeholders were printed as they are
// - console.log printed a value as String() makes it: a string[] as `a,b`, a tuple as `{ 1, 'a' }`

function check(condition: boolean, message: string) {
if (!condition) {
console.log("fail:", message);
assert(false, message);
}
}

function testRound() {
check(Math.round(-2.5) == -2, "Math.round(-2.5) is -2");
check(Math.round(2.5) == 3, "Math.round(2.5) is 3");
check(Math.round(-3.7) == -4, "Math.round(-3.7) is -4");
check(Math.round(0.49999999999999994) == 0, "the largest double below 0.5 rounds to 0");
const negativeZero = Math.round(-0.4);
check(negativeZero == 0 && 1 / negativeZero < 0, "Math.round(-0.4) is -0");
check(isNaN(Math.round(Number.NaN)), "NaN is NaN");
check(Math.round(Number.POSITIVE_INFINITY) == Number.POSITIVE_INFINITY, "Infinity is Infinity");
}

function testParseFloat() {
check(isNaN(parseFloat("abc")), "no number is NaN");
check(isNaN(parseFloat("")), "an empty text is NaN");
check(parseFloat("12px") == 12, "the number at the start");
check(parseFloat(" -2.5e1x") == -25, "after white space, with an exponent");
check(parseFloat(".5") == 0.5, "a fraction");
check(parseFloat("0x10") == 0, "no hexadecimal");
check(parseFloat("-Infinity") == Number.NEGATIVE_INFINITY, "-Infinity");
check(isNaN(parseFloat("inf")), "only Infinity spelled so");
}

function testConsole() {
// printed, not checked here: these crashed or printed the placeholders
let nothing: string = null;
console.log(nothing, "after a null string");
console.log("%s has %d items (%i%%)", "the list", 3, 42.9, "and more");
const names: string[] = [];
names.push("x");
console.log(names, [1, "a"], { a: 1, b: [2, 3] });
}

testRound();
testParseFloat();
testConsole();

console.log("ALL DONE");
Loading