update claude.md
This commit is contained in:
parent
c848ee0216
commit
eaebe10c42
216
CLAUDE.md
216
CLAUDE.md
|
|
@ -1,119 +1,149 @@
|
||||||
---
|
# CLAUDE.md
|
||||||
description: Use Bun instead of Node.js, npm, pnpm, or vite.
|
|
||||||
globs: "*.ts, *.tsx, *.html, *.css, *.js, *.jsx, package.json"
|
|
||||||
alwaysApply: false
|
|
||||||
---
|
|
||||||
|
|
||||||
## Overview
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
This is a stack based VM for a simple dyanmic language called Shrimp.
|
## Project Overview
|
||||||
|
|
||||||
Please read README.md, SPEC.md, src/vm.ts, and the examples/ to understand the VM.
|
ReefVM is a stack-based bytecode virtual machine for the Shrimp programming language. It implements a complete VM with closures, tail call optimization, exception handling, variadic functions, named parameters, and Ruby-style iterators with break/continue.
|
||||||
|
|
||||||
## Bun
|
**Essential reading**: Before making changes, read README.md, SPEC.md, and GUIDE.md to understand the VM architecture, instruction set, and compiler patterns.
|
||||||
|
|
||||||
Default to using Bun instead of Node.js.
|
## Development Commands
|
||||||
|
|
||||||
- Use `bun <file>` instead of `node <file>` or `ts-node <file>`
|
### Running Files
|
||||||
- Use `bun test` instead of `jest` or `vitest`
|
```bash
|
||||||
- Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
|
bun <file.ts> # Run TypeScript files directly
|
||||||
- Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
|
bun examples/native.ts # Run example
|
||||||
- Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
|
|
||||||
- Bun automatically loads .env, so don't use dotenv.
|
|
||||||
|
|
||||||
## APIs
|
|
||||||
|
|
||||||
- `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
|
|
||||||
- `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
|
|
||||||
- `Bun.redis` for Redis. Don't use `ioredis`.
|
|
||||||
- `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
|
|
||||||
- `WebSocket` is built-in. Don't use `ws`.
|
|
||||||
- Prefer `Bun.file` over `node:fs`'s readFile/writeFile
|
|
||||||
- Bun.$`ls` instead of execa.
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
Use `bun test` to run tests.
|
|
||||||
|
|
||||||
```ts#index.test.ts
|
|
||||||
import { test, expect } from "bun:test";
|
|
||||||
|
|
||||||
test("hello world", () => {
|
|
||||||
expect(1).toBe(1);
|
|
||||||
});
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Frontend
|
### Testing
|
||||||
|
```bash
|
||||||
|
bun test # Run all tests
|
||||||
|
bun test <file> # Run specific test file
|
||||||
|
bun test --watch # Watch mode
|
||||||
|
```
|
||||||
|
|
||||||
Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
|
### Building
|
||||||
|
No build step required - Bun runs TypeScript directly.
|
||||||
|
|
||||||
Server:
|
## Architecture
|
||||||
|
|
||||||
```ts#index.ts
|
### Core Components
|
||||||
import index from "./index.html"
|
|
||||||
|
|
||||||
Bun.serve({
|
**VM Execution Model** (src/vm.ts):
|
||||||
routes: {
|
- Stack-based execution with program counter (PC)
|
||||||
"/": index,
|
- Call stack for function frames
|
||||||
"/api/users/:id": {
|
- Exception handler stack for try/catch/finally
|
||||||
GET: (req) => {
|
- Lexical scope chain with parent references
|
||||||
return new Response(JSON.stringify({ id: req.params.id }));
|
- Native function registry for TypeScript interop
|
||||||
},
|
|
||||||
},
|
**Key subsystems**:
|
||||||
},
|
- **bytecode.ts**: Parser that converts human-readable bytecode strings to executable bytecode. Handles label resolution, constant pool management, and function definition parsing.
|
||||||
// optional websocket support
|
- **value.ts**: Tagged union Value type system with type coercion functions (toNumber, toString, isTrue, isEqual)
|
||||||
websocket: {
|
- **scope.ts**: Linked scope chain for variable resolution with lexical scoping
|
||||||
open: (ws) => {
|
- **frame.ts**: Call frame tracking for function calls and break targets
|
||||||
ws.send("Hello, world!");
|
- **exception.ts**: Exception handler records for try/catch/finally blocks
|
||||||
},
|
- **validator.ts**: Bytecode validation to catch common errors before execution
|
||||||
message: (ws, message) => {
|
- **opcode.ts**: OpCode enum defining all VM instructions
|
||||||
ws.send(message);
|
|
||||||
},
|
### Critical Design Decisions
|
||||||
close: (ws) => {
|
|
||||||
// handle close
|
**Relative jumps**: All JUMP instructions use PC-relative offsets (not absolute addresses), making bytecode position-independent. PUSH_TRY/PUSH_FINALLY use absolute addresses.
|
||||||
}
|
|
||||||
},
|
**Truthiness semantics**: Only `null` and `false` are falsy. Unlike JavaScript, `0`, `""`, empty arrays, and empty dicts are truthy.
|
||||||
development: {
|
|
||||||
hmr: true,
|
**No AND/OR opcodes**: Short-circuit logical operations are implemented at the compiler level using JUMP patterns with DUP.
|
||||||
console: true,
|
|
||||||
}
|
**Tail call optimization**: TAIL_CALL reuses the current call frame instead of pushing a new one, enabling unbounded recursion.
|
||||||
|
|
||||||
|
**Break semantics**: CALL marks frames as break targets. BREAK unwinds the call stack to the most recent break target, enabling Ruby-style iterator patterns.
|
||||||
|
|
||||||
|
**Exception handling**: THROW jumps to finally (if present) or catch. The VM does NOT auto-jump to finally on successful try completion - compilers must explicitly generate JUMPs to finally blocks.
|
||||||
|
|
||||||
|
**Parameter binding priority**: Named args bind to fixed params first. Unmatched named args go to `@named` dict parameter. Fixed params bind in order: named arg > positional arg > default > null.
|
||||||
|
|
||||||
|
**Native function calling**: CALL_NATIVE consumes the entire stack as arguments (different from CALL which pops specific argument counts).
|
||||||
|
|
||||||
|
## Testing Strategy
|
||||||
|
|
||||||
|
Tests are organized by feature area:
|
||||||
|
- **basic.test.ts**: Stack ops, arithmetic, comparisons, variables, control flow
|
||||||
|
- **functions.test.ts**: Function creation, calls, closures, defaults, variadic, named args
|
||||||
|
- **tail-call.test.ts**: Tail call optimization and unbounded recursion
|
||||||
|
- **exceptions.test.ts**: Try/catch/finally, exception unwinding, nested handlers
|
||||||
|
- **native.test.ts**: Native function interop (sync and async)
|
||||||
|
- **bytecode.test.ts**: Bytecode parser, label resolution, constants
|
||||||
|
- **validator.test.ts**: Bytecode validation rules
|
||||||
|
- **examples.test.ts**: Integration tests for example programs
|
||||||
|
|
||||||
|
When adding features:
|
||||||
|
1. Add unit tests for the specific opcode/feature
|
||||||
|
2. Add integration tests showing real-world usage
|
||||||
|
3. Update SPEC.md with formal specification
|
||||||
|
4. Update GUIDE.md with compiler patterns
|
||||||
|
5. Consider adding an example to examples/
|
||||||
|
|
||||||
|
## Common Patterns
|
||||||
|
|
||||||
|
### Writing Bytecode Tests
|
||||||
|
```typescript
|
||||||
|
import { toBytecode, run } from "#reef"
|
||||||
|
|
||||||
|
const bytecode = toBytecode(`
|
||||||
|
PUSH 42
|
||||||
|
STORE x
|
||||||
|
LOAD x
|
||||||
|
HALT
|
||||||
|
`)
|
||||||
|
|
||||||
|
const result = await run(bytecode)
|
||||||
|
// result is { type: 'number', value: 42 }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Native Function Registration
|
||||||
|
```typescript
|
||||||
|
const vm = new VM(bytecode)
|
||||||
|
vm.registerFunction('functionName', (...args: Value[]): Value => {
|
||||||
|
// Implementation
|
||||||
|
return toValue(result)
|
||||||
})
|
})
|
||||||
|
await vm.run()
|
||||||
```
|
```
|
||||||
|
|
||||||
HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
|
### Label Usage (Preferred)
|
||||||
|
Use labels instead of numeric offsets for readability:
|
||||||
```html#index.html
|
```
|
||||||
<html>
|
JUMP .skip
|
||||||
<body>
|
PUSH 42
|
||||||
<h1>Hello, world!</h1>
|
HALT
|
||||||
<script type="module" src="./frontend.tsx"></script>
|
.skip:
|
||||||
</body>
|
PUSH 99
|
||||||
</html>
|
HALT
|
||||||
```
|
```
|
||||||
|
|
||||||
With the following `frontend.tsx`:
|
## TypeScript Configuration
|
||||||
|
|
||||||
```tsx#frontend.tsx
|
- Import alias: `#reef` maps to `./src/index.ts`
|
||||||
import React from "react";
|
- Module system: ES modules (`"type": "module"` in package.json)
|
||||||
|
- Bun automatically handles TypeScript compilation
|
||||||
|
|
||||||
// import .css files directly and it works
|
## Bun-Specific Notes
|
||||||
import './index.css';
|
|
||||||
|
|
||||||
import { createRoot } from "react-dom/client";
|
- Use `bun` instead of `node`, `npm`, `pnpm`, or `vite`
|
||||||
|
- No need for dotenv - Bun loads .env automatically
|
||||||
|
- Prefer Bun APIs over Node.js equivalents when available
|
||||||
|
- See .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc for detailed Bun usage
|
||||||
|
|
||||||
const root = createRoot(document.body);
|
## Common Gotchas
|
||||||
|
|
||||||
export default function Frontend() {
|
**Jump offsets**: JUMP/JUMP_IF_FALSE/JUMP_IF_TRUE use relative offsets from the next instruction (PC + 1). PUSH_TRY/PUSH_FINALLY use absolute instruction indices.
|
||||||
return <h1>Hello, world!</h1>;
|
|
||||||
}
|
|
||||||
|
|
||||||
root.render(<Frontend />);
|
**Stack operations**: Most binary operations pop in reverse order (second operand is popped first, then first operand).
|
||||||
```
|
|
||||||
|
|
||||||
Then, run index.ts
|
**MAKE_ARRAY operand**: Specifies count, not a stack index. `MAKE_ARRAY #3` pops 3 items.
|
||||||
|
|
||||||
```sh
|
**CALL_NATIVE stack behavior**: Unlike CALL, it consumes all stack values as arguments and clears the stack.
|
||||||
bun --hot ./index.ts
|
|
||||||
```
|
|
||||||
|
|
||||||
For more information, read the Bun API docs in `node_modules/bun-types/docs/**.md`.
|
**Finally blocks**: The compiler must generate explicit JUMPs to finally blocks for successful try/catch completion. The VM only auto-jumps to finally on THROW.
|
||||||
|
|
||||||
|
**Variable scoping**: STORE updates existing variables in parent scopes or creates in current scope. It does NOT shadow by default.
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user