Skip to content
Open
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
79 changes: 79 additions & 0 deletions script/corpus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#!/usr/bin/env bun

// What a typical program costs, by phase: the programs of a corpus directory (rust/bench/corpus: short snippets of the
// kind a model writes) against a host whose tools answer at once with canned data.
// Usage: bun run script/corpus.ts <corpus dir> [--runs N]
// Per program, the median microseconds of: compiling it, running it compiled (a fresh run's setup, the program, its
// host calls), and both from source. The last program, `return 1`, is the setup alone.

import { readdirSync, readFileSync } from "node:fs"
import { Host, Runtime } from "../src/index.js"

const text = (lines: number) =>
Array.from({ length: lines }, (_, i) =>
i % 4 === 0
? `fn item_${i}(value: usize) -> usize { value + ${i} }\n`
: i % 4 === 1
? `warn line ${i} of the log: something happened\n`
: i % 4 === 2
? ` let mut total_${i} = ${i} * 2; // version = "0.${i}.1"\n`
: `dep_${i} = "1.${i}"\n`,
).join("")
const texts = { 16: text(16), 24: text(24), 240: text(240) }
const json = `[${Array.from({ length: 9 }, (_, i) => `{"slug":"case-${i}","median_ms":${i * 3}.25,"median_instructions":${1_000_000 * (i + 1)}}`).join(",")}]`
const list = Array.from({ length: 24 }, (_, i) => `file_${i}.rs\n`).join("")
const search = Array.from({ length: 6 }, (_, i) => ({ url: `https://example.com/${i}`, title: `Result ${i}`, content: texts[16] }))

const fn = (f: (input: Record<string, unknown>) => unknown) => Host.fn(([input]) => f((input ?? {}) as Record<string, unknown>), { type: "async" })
const tools = {
shell: fn((input) => {
const command = String(input.command ?? "")
return { output: command.includes("--json") ? json : command.startsWith("ls") ? list : texts[24], exitCode: 0 }
}),
read: fn(() => ({ type: "text", content: texts[240] })),
websearch: fn(() => search),
write: fn(() => "ok"),
edit: fn(() => "ok"),
}
const runtime = Runtime.make({ globals: () => ({ tools }) })

const dir = process.argv[2]
if (dir === undefined) throw new Error("usage: bun run script/corpus.ts <corpus dir> [--runs N]")
const at = process.argv.indexOf("--runs")
const runs = at === -1 ? 301 : Number(process.argv[at + 1])
const median = (values: Array<number>) => values.sort((a, b) => a - b)[Math.floor(values.length / 2)]!
const measure = async (f: () => unknown) => {
for (let i = 0; i < 50; i++) await f()
const times: Array<number> = []
for (let i = 0; i < runs; i++) {
const start = performance.now()
await f()
times.push((performance.now() - start) * 1000)
}
return median(times)
}

const rows: Array<[string, number, number, number, number]> = []
for (const name of readdirSync(dir).filter((n) => n.endsWith(".js")).sort()) {
const code = readFileSync(`${dir}/${name}`, "utf8")
const first = await runtime.execute(code)
if (!first.ok) throw new Error(`${name} failed: ${JSON.stringify(first.error)}`)
const made = runtime.compile(code)
if (!made.ok) throw new Error(`${name} does not compile`)
const compile = await measure(() => runtime.compile(code))
const run = await measure(() => runtime.program(made.compiled).run())
const both = await measure(() => runtime.execute(code))
rows.push([name.replace(/\.js$/, ""), code.length, compile, run, both])
}
const setup = rows.at(-1)![3]
const pad = (v: number) => v.toFixed(0).padStart(9)
console.log(`${"program".padEnd(22)} ${"bytes".padStart(6)} ${"compile".padStart(9)} ${"setup".padStart(9)} ${"program".padStart(9)} ${"total".padStart(9)} (median µs)`)
const sum = [0, 0, 0, 0]
for (const [name, bytes, compile, run, both] of rows) {
const program = Math.max(0, run - setup)
console.log(`${name.padEnd(22)} ${String(bytes).padStart(6)} ${pad(compile)} ${pad(setup)} ${pad(program)} ${pad(both)}`)
;[compile, setup, program, both].forEach((v, i) => (sum[i]! += v))
}
console.log(`${"sum".padEnd(22)} ${"".padStart(6)} ${sum.map(pad).join(" ")}`)
const parts = sum[0]! + sum[1]! + sum[2]!
console.log(`${"share".padEnd(22)} ${"".padStart(6)} ${[sum[0]!, sum[1]!, sum[2]!].map((v) => `${((100 * v) / parts).toFixed(0)}%`.padStart(9)).join(" ")}`)
17 changes: 12 additions & 5 deletions src/prelude/prelude.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Interpreter } from "../runtime/interpreter.js"
import { define, Fn, get, hidden, Obj, type Value } from "../runtime/objects.js"
import type { Code } from "../code.js"
import { builtinCodes } from "./bytecode.js"
import { helpers } from "./helpers.js"
import { code } from "./source.js"
Expand All @@ -20,6 +21,11 @@ let compiled: ReturnType<typeof builtinCodes> | undefined
*/
export const compiledPrelude = () => (compiled ??= builtinCodes("@prelude", code))

let installs: ReadonlyArray<readonly [name: string, made: Code, path: ReadonlyArray<string>]> | undefined

/** The prelude's functions with their names split into where each is installed, once for the process. */
const preludeInstalls = () => (installs ??= [...compiledPrelude().byName].map(([name, made]) => [name, made, name.split("$")] as const))

/** One runtime's prelude: what its functions' free names see, and its functions and helpers, by name. */
export class Prelude {
readonly scope = new Map<string, Value>()
Expand All @@ -37,16 +43,17 @@ export class Prelude {
define(this.helpers, name, value, hidden)
this.scope.set(name, value)
}
for (const [name, made] of compiledPrelude().byName) {
const path = name.split("$")
const fn = new Fn(builtins.Function, made, [], path.at(-1))
for (const [name, made, path] of preludeInstalls()) {
const last = path[path.length - 1]!
const fn = new Fn(builtins.Function, made, [], last)
// The prelude's generators are iterator helpers.
if (fn.generator) define(fn, "prototype", builtins.IteratorHelper, hidden)
this.scope.set(name, fn)
define(this.functions, name, fn, hidden)
if (path.length === 1) continue
const owner = path.slice(1, -1).reduce((value, key) => get(value as Obj, key), this.scope.get(path[0]!))
define(owner as Obj, path.at(-1)!, fn, hidden)
let owner = this.scope.get(path[0]!)
for (let i = 1; i < path.length - 1; i++) owner = get(owner as Obj, path[i]!)
define(owner as Obj, last, fn, hidden)
}
}

Expand Down
6 changes: 4 additions & 2 deletions src/runtime/objects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,10 @@ export abstract class Callable extends Opaque {
readonly length: number,
) {
super(proto)
define(this, "length", length, readonly)
define(this, "name", name, readonly)
// As `define` would, without its checks: a function just made is no array, is not an intrinsic yet and has no
// guard. A run makes several hundred built-in functions before its program starts.
this.props.set("length", { value: length, writable: false, enumerable: false, configurable: true })
this.props.set("name", { value: name, writable: false, enumerable: false, configurable: true })
}
override get describe() {
return "a function"
Expand Down
7 changes: 7 additions & 0 deletions src/stdlib/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,13 @@ export const stringGlobal = <R>(ctx: Interpreter<R>) => {
if (thisValue === null || thisValue === undefined) {
throw typeError(`String.prototype.${name} called on null or undefined.`)
}
// A string receiver with nothing to convert among the arguments, which is nearly every call: no conversion
// list to build. The same call makes the same choice when it runs again, so later conversions keep their order.
if (typeof thisValue === "string") {
let plain = true
for (let i = 0; i < hints.length && plain; i++) plain = !(args[i] instanceof Obj)
if (plain) return op(thisValue, args)
}
return withPrimitives(
["string", ...hints],
[thisValue, ...args.slice(0, hints.length)],
Expand Down