Skip to content

feat: add global functions parseInt, parseFloat, isNaN, isFinite, Number, String, Boolean - #57

Open
jtippett wants to merge 1 commit into
TheUncharted:masterfrom
jtippett:feat/global-builtins
Open

jtippett wants to merge 1 commit into
TheUncharted:masterfrom
jtippett:feat/global-builtins

Conversation

@jtippett

@jtippett jtippett commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Summary

Agent-generated code constantly reaches for parseInt/parseFloat/isNaN/isFinite and the Number/String/Boolean conversion functions; today a bare call compiles to LoadGlobal → undefined → "x is not a function". All seven are pure computation with no sandbox surface.

Changes

  • The seven names are recognized at compile time (shadowable by a local of the same name — the same mechanism as external functions).
  • New CallBuiltin instruction dispatching to builtins::call_global_function.
  • Tests in tests/builtins.rs.

Test plan

  • Unit tests pass (cargo test)
  • make lint clean
  • Test262: built-ins/parseInt 0% → 73%, parseFloat 0% → 76%
  • CI passes

Related issues

None open. We run this patch in production via ex_zapcode.

…ber, String, Boolean

Bare calls to these compiled to LoadGlobal -> undefined -> "not a
function". They are now recognized at compile time (shadowable by a
local of the same name, like external functions) and dispatched via a
new CallBuiltin instruction to builtins::call_global_function.
Test262: built-ins/parseInt 0% -> 73%, parseFloat 0% -> 76%.
@jtippett
jtippett requested a review from TheUncharted as a code owner July 9, 2026 09:29
@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@jtippett, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 59 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 550820e4-4dae-424a-8795-65537fccda58

📥 Commits

Reviewing files that changed from the base of the PR and between ebc06fd and bc6044d.

📒 Files selected for processing (5)
  • crates/zapcode-core/src/compiler/instruction.rs
  • crates/zapcode-core/src/compiler/mod.rs
  • crates/zapcode-core/src/vm/builtins.rs
  • crates/zapcode-core/src/vm/mod.rs
  • crates/zapcode-core/tests/builtins.rs
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@perezd

perezd commented Aug 3, 2026

Copy link
Copy Markdown

Hi @TheUncharted! I'd love to see this and many of the other fantastic fixes by @jtippett merged into this project, unless you have any strong objections.

Thank you both for the contributions; this is a great project!

@TheUncharted TheUncharted left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The basic builtin tests pass (72/72), and I found no malicious code or direct host-capability escape. I am requesting changes for four focused issues documented inline: lexical/first-class name resolution, serialized instruction ordering, JavaScript conversion semantics, and resource bounds for long parsing operations. The name-resolution and coercion reproductions were executed against this exact PR head; the snapshot and resource findings are grounded in the serialization/allocation code paths.


fn parse_int(args: &[Value]) -> Value {
let s = args.first().map(|v| v.to_js_string()).unwrap_or_default();
let chars: Vec<char> = s.trim_start().chars().collect();

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This parser clones the full input string and then materializes Vec<char>, but neither temporary allocation is charged to ResourceTracker. The subsequent scan runs inside one opcode, while the VM checks elapsed time only between opcodes. A sufficiently large guest- or host-provided string can therefore amplify memory and occupy the worker beyond configured limits before control returns to the VM.

I deliberately did not run an unbounded stress payload during review. This finding is based on the allocation and control-flow path here.

Please avoid materializing Vec<char> by parsing with an iterator/byte indices, impose an input-size/resource preflight, and periodically check the execution deadline during long scans. parseFloat needs equivalent bounds. Add a bounded test with low memory/time limits that returns a controlled limit error.

Return,
CallExternal(String, usize),
/// Call a global builtin function by name (e.g. parseInt, isNaN, Number).
CallBuiltin(String, usize),

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instruction derives serde serialization and the complete CompiledProgram is stored in postcard snapshots. Inserting CallBuiltin here shifts the enum tags for every following opcode (Jump onward), so a snapshot created by Zapcode 1.5.3 may decode old instructions as different instructions after an upgrade.

Example scenario:

const response = await externalTool();
response ? 1 : 2;

The persisted snapshot contains the post-suspension jump bytecode. After this insertion, those old enum tags no longer identify the same opcodes.

Please append CallBuiltin at the end of the enum to preserve existing tags. Longer term, snapshots should use an explicit format version and legacy fixture tests, but preserving enum order is the minimal fix required in this PR.

if self.resolve_local(name).is_none() && is_global_builtin_fn(name) {
for arg in args {
self.compile_expr(arg)?;
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This compile-time rewrite bypasses normal lexical/global resolution. resolve_local() sees only this function's local slots, not a binding captured from an enclosing scope. The builtin also is not registered as a first-class global value.

Both cases were verified at this PR head:

const Number = value => value + 1;
const call = () => Number(41);
call();

Expected: 42; actual: 41.

const parse = parseInt;
parse("42");

Expected: 42; actual: TypeError("undefined is not a function").

Please register these as normal builtin function Values and invoke them through ordinary lexical/global call resolution. That lets captured/local bindings shadow them and allows assignment, callbacks, and object properties. Please add both cases as regression tests.

Some(v) => Value::String(Arc::from(v.to_js_string().as_str())),
None => Value::String(Arc::from("")),
},
"Number" => match args.first() {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These conversions use the current generic to_number()/Rust parsing behavior rather than ECMAScript coercion. I verified:

[Number(""), Number(" 42 "), Number("0x10")]

Expected: [0, 42, 16]; actual: [NaN, NaN, NaN].

I also verified:

parseInt("10", 4294967298)

Expected: 2 because JavaScript applies ToInt32 to the radix; actual: NaN.

Please implement shared ECMAScript-style ToNumber/ToString helpers and use ToInt32 for the radix. At minimum, cover empty/trimmed strings, numeric prefixes, signed zero, Infinity, and radix conversion in regression tests. If exact ECMAScript behavior is intentionally out of scope, these functions need explicit documented subset semantics rather than presenting them as standard globals.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants