diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/print.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/print.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..09681aef5774f516d1fefbf4847ff867f16704e2 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/print.test.ts @@ -0,0 +1,92 @@ +import { beforeEach, describe, expect, test, vi } from 'vitest'; +import { getParentStackId } from './get-parent-stack-id.ts'; +import type { GraphNode } from './graph-node.ts'; +import type { GraphPointer } from './graph-pointer.ts'; +import { Pointers } from './pointers.ts'; +import { printGraphNode, printGraphPointer } from './print.ts'; +import { RuleRef } from './rule-ref.ts'; +import { type PrintOpts, RuleChar, type UnresolvedRule } from './types.ts'; + +vi.mock('./get-parent-stack-id.ts', () => ({ getParentStackId: vi.fn() })); + +const mockGetParentStackId = vi.mocked(getParentStackId); + +beforeEach(() => { + mockGetParentStackId.mockReset(); +}); + +const COLORS: Record = { + '\x1b[34m': 'BLUE', + '\x1b[36m': 'CYAN', + '\x1b[32m': 'GREEN', + '\x1b[31m': 'RED', + '\x1b[90m': 'GRAY', + '\x1b[33m': 'YELLOW', +}; + +const mockColorize = (text: string | number, color: string): string => { + if (!(color in COLORS)) { + throw new Error(`Invalid color: ${color}`); + } + return `[${COLORS[color]}]:${text}`; +}; + +interface MockNode { + id: number; + rule: UnresolvedRule; + next: GraphNode | undefined; + print: (opts: PrintOpts) => string; +} + +const createMockNode = (id: number, rule: UnresolvedRule, next?: GraphNode): MockNode => ({ + id, + rule, + next, + print: (_opts) => `Node(${id})`, +}); + +const createMockGraphPointer = (node: MockNode) => ({ + node, + parent: undefined, + print: (_opts: PrintOpts) => `Pointer to ${node.id}`, +}); + +describe('print', () => { + describe('printGraphPointer', () => { + test('it prints graph pointer details correctly', () => { + const mockNode = createMockNode(1, new RuleRef(100)); + const mockPointer = createMockGraphPointer(mockNode); + mockGetParentStackId.mockReturnValue('foo'); + const result = printGraphPointer(mockPointer as unknown as GraphPointer)({ + colorize: mockColorize, + pointers: new Pointers(), + showPosition: false, + }); + expect(result).toEqual('[RED]:*foo'); + }); + }); + + describe('printGraphNode', () => { + test('it prints graph node with a character rule', () => { + const ruleChar = new RuleChar([65]); + const mockNode = createMockNode(1, ruleChar); + const result = printGraphNode(mockNode as unknown as GraphNode)({ + colorize: mockColorize, + showPosition: false, + pointers: new Pointers(), + }); + expect(result).toEqual('[GRAY]:[[YELLOW]:A[GRAY]:]'); + }); + + test('it prints graph node with a rule reference', () => { + const ruleRef = new RuleRef(200); + const mockNode = createMockNode(1, ruleRef); + const result = printGraphNode(mockNode as unknown as GraphNode)({ + colorize: mockColorize, + showPosition: true, + pointers: new Pointers(), + }); + expect(result).toEqual('[BLUE]:{[GRAY]:1[BLUE]:}[GRAY]:Ref([GREEN]:200[GRAY]:)'); + }); + }); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/print.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/print.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c69027e527f46085d60b7e49614dc4aa7da5d9d --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/print.ts @@ -0,0 +1,68 @@ +import { Color } from './colorize.ts'; +import { getParentStackId } from './get-parent-stack-id.ts'; +import type { GraphNode } from './graph-node.ts'; +import type { GraphPointer } from './graph-pointer.ts'; +import { isRange, isRuleChar, isRuleRef } from './type-guards.ts'; +import type { PrintOpts } from './types.ts'; + +export const printGraphPointer = + (pointer: GraphPointer) => + (opts: PrintOpts): string => { + const col = opts.colorize; + return col(`*${getParentStackId(pointer, col)}`, Color.RED); + }; + +export const printGraphNode = + (node: GraphNode) => + (opts: PrintOpts): string => { + const pointers: Iterable = opts.pointers ?? []; + const col = opts.colorize; + const showPosition = opts.showPosition ?? false; + const rule = node.rule; + + const parts: string[] = []; + if (showPosition) { + parts.push(col('{', Color.BLUE), col(node.id, Color.GRAY), col('}', Color.BLUE)); + } + + if (isRuleChar(rule)) { + parts.push( + col('[', Color.GRAY), + col( + rule.value + .map((v) => (isRange(v) ? v.map((val) => col(getChar(val), Color.YELLOW)).join('') : getChar(v))) + .join(''), + Color.YELLOW, + ), + col(']', Color.GRAY), + ); + } else if (isRuleRef(rule)) { + parts.push(col('Ref(', Color.GRAY), col(rule.value, Color.GREEN), col(')', Color.GRAY)); + } else { + parts.push(col(rule.type, Color.YELLOW)); + } + + for (const pointer of pointers) { + const pointerParts: string[] = []; + if (pointer.node === node) { + pointerParts.push(pointer.print(opts)); + } + if (pointerParts.length > 0) { + parts.push(col('[', Color.GRAY), col(pointerParts.join(''), Color.YELLOW), col(']', Color.GRAY)); + } + } + + const partsToReturn = [parts.join('')]; + if (node.next) { + partsToReturn.push(node.next.print(opts)); + } + return partsToReturn.join(col('-> ', Color.GRAY)); + }; + +const getChar = (charCode: number): string => { + const char = String.fromCodePoint(charCode); + if (char === '\n') { + return '\\n'; + } + return char; +}; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/rule-ref.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/rule-ref.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..eac9e85494a37a48c62b1e13b643673b1e5fd09b --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/rule-ref.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, test } from 'vitest'; +import type { GraphNode } from './graph-node.ts'; +import { RuleRef } from './rule-ref.ts'; + +describe('RuleRef', () => { + test('initializes with a given value', () => { + const ruleRef = new RuleRef(123); + expect(ruleRef.value).toEqual(123); + }); + + test('allows setting and getting nodes', () => { + const mockNodes = new Set([1]) as unknown as Set; + const ruleRef = new RuleRef(123); + ruleRef.nodes = mockNodes; + expect(ruleRef.nodes).toEqual(mockNodes); + }); + + test('throws an error if trying to get nodes before setting', () => { + const ruleRef = new RuleRef(123); + expect(() => ruleRef.nodes).toThrow(new Error('Nodes are not set')); + }); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/rule-ref.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/rule-ref.ts new file mode 100644 index 0000000000000000000000000000000000000000..49377d28b962ea243a33e8c726b6dfd1c127b57d --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/rule-ref.ts @@ -0,0 +1,21 @@ +import type { GraphNode } from './graph-node.ts'; + +export class RuleRef { + value: number; + #nodes?: Set; + + constructor(value: number) { + this.value = value; + } + + get nodes(): Set { + if (this.#nodes === undefined) { + throw new Error('Nodes are not set'); + } + return this.#nodes; + } + + set nodes(nodes: Set) { + this.#nodes = nodes; + } +} diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/type-guards.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/type-guards.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c1ec8604bf00858a7121dc4875cf3b56efd8cbb --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/type-guards.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, test } from 'vitest'; +import { GraphNode } from './graph-node.ts'; +import { GraphPointer } from './graph-pointer.ts'; +import { RuleRef } from './rule-ref.ts'; +import { + isGraphPointerRuleChar, + isGraphPointerRuleCharExclude, + isGraphPointerRuleEnd, + isGraphPointerRuleRef, + isRange, + isRule, + isRuleChar, + isRuleCharExclude, + isRuleEnd, + isRuleRef, +} from './type-guards.ts'; +import { RuleChar, RuleCharExclude, RuleEnd } from './types.ts'; + +describe('rule type guards', () => { + describe('isGraphPointerRuleRef', () => { + test('it returns true', () => { + const node = new GraphNode(new RuleRef(1), { stackId: 1, pathId: 2, stepId: 3 }); + const pointer = new GraphPointer(node); + expect(isGraphPointerRuleRef(pointer)).toBe(true); + }); + + test('it returns false', () => { + const node = new GraphNode(new RuleEnd(), { stackId: 1, pathId: 2, stepId: 3 }); + const pointer = new GraphPointer(node); + expect(isGraphPointerRuleRef(pointer)).toBe(false); + }); + }); + + describe('isGraphPointerRuleEnd', () => { + test('it returns false', () => { + const node = new GraphNode(new RuleRef(1), { stackId: 1, pathId: 2, stepId: 3 }); + const pointer = new GraphPointer(node); + expect(isGraphPointerRuleEnd(pointer)).toBe(false); + }); + + test('it returns true', () => { + const node = new GraphNode(new RuleEnd(), { stackId: 1, pathId: 2, stepId: 3 }); + const pointer = new GraphPointer(node); + expect(isGraphPointerRuleEnd(pointer)).toBe(true); + }); + }); + + describe('isGraphPointerRuleChar', () => { + test('it returns true', () => { + const node = new GraphNode(new RuleChar([97]), { stackId: 1, pathId: 2, stepId: 3 }); + const pointer = new GraphPointer(node); + expect(isGraphPointerRuleChar(pointer)).toBe(true); + }); + + test('it returns false', () => { + const node = new GraphNode(new RuleEnd(), { stackId: 1, pathId: 2, stepId: 3 }); + const pointer = new GraphPointer(node); + expect(isGraphPointerRuleChar(pointer)).toBe(false); + }); + }); + + describe('isGraphPointerRuleCharExclude', () => { + test('it returns true', () => { + const node = new GraphNode(new RuleCharExclude([97]), { stackId: 1, pathId: 2, stepId: 3 }); + const pointer = new GraphPointer(node); + expect(isGraphPointerRuleCharExclude(pointer)).toBe(true); + }); + + test('it returns false', () => { + const node = new GraphNode(new RuleChar([97]), { stackId: 1, pathId: 2, stepId: 3 }); + const pointer = new GraphPointer(node); + expect(isGraphPointerRuleCharExclude(pointer)).toBe(false); + }); + }); + + describe('isRule', () => { + test('it returns false for null', () => { + expect(isRule(undefined)).toBe(false); + expect(isRule(null)).toBe(false); + }); + + test('it returns false for a non rule', () => { + expect(isRule({ type: 'invalid', value: [] })).toBe(false); + }); + + test('it returns true for valid rule objects', () => { + const ruleChar = new RuleChar([65, [66, 67]]); + expect(isRule(ruleChar)).toBe(true); + }); + }); + + describe('isRuleRef', () => { + test('it returns true for valid rule refs', () => { + const ruleRef = new RuleRef(1); + expect(isRuleRef(ruleRef)).toBe(true); + }); + + test('it returns false for invalid rule refs', () => { + expect(isRuleRef(new RuleChar([65]))).toBe(false); + }); + }); + + describe('isRuleEnd', () => { + test('it returns true for valid rule ends', () => { + expect(isRuleEnd(new RuleEnd())).toBe(true); + }); + + test('it returns false for invalid rule ends', () => { + expect(isRuleEnd(new RuleChar([65]))).toBe(false); + }); + }); + + describe('isRuleChar', () => { + test('it returns true for valid rule chars', () => { + expect(isRuleChar(new RuleChar([65]))).toBe(true); + }); + + test('it returns false for invalid rule chars', () => { + expect(isRuleChar(new RuleCharExclude([65]))).toBe(false); + }); + }); + + describe('isRuleCharExclude', () => { + test('it returns true for valid rule chars', () => { + expect(isRuleCharExclude(new RuleCharExclude([65]))).toBe(true); + }); + + test('it returns false for invalid rule chars', () => { + expect(isRuleCharExclude(new RuleChar([65]))).toBe(false); + }); + }); + + describe('isRange', () => { + test('it returns true for valid ranges', () => { + expect(isRange([1, 10])).toBe(true); + }); + + test.each<[unknown]>([[[1, '10']], [[1]], [5]])('it returns false for invalid ranges %j', (value) => { + expect(isRange(value)).toBe(false); + }); + }); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/type-guards.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/type-guards.ts new file mode 100644 index 0000000000000000000000000000000000000000..52dbe98d3e61c4c091c3dd8b694ec6050230dafd --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/type-guards.ts @@ -0,0 +1,29 @@ +import type { GraphPointer } from './graph-pointer.ts'; +import { RuleRef } from './rule-ref.ts'; +import { type Range, RuleChar, RuleCharExclude, RuleEnd, type UnresolvedRule } from './types.ts'; + +export const isRule = (rule?: unknown): rule is UnresolvedRule => + rule instanceof RuleChar || rule instanceof RuleCharExclude || rule instanceof RuleEnd || rule instanceof RuleRef; + +export const isRuleRef = (rule?: unknown): rule is RuleRef => rule instanceof RuleRef; + +export const isRuleEnd = (rule?: unknown): rule is RuleEnd => rule instanceof RuleEnd; + +export const isRuleChar = (rule?: unknown): rule is RuleChar => rule instanceof RuleChar; + +export const isRuleCharExclude = (rule?: unknown): rule is RuleCharExclude => rule instanceof RuleCharExclude; + +export const isRange = (inpt?: unknown): inpt is Range => + Array.isArray(inpt) && inpt.length === 2 && inpt.every((n) => Number.isInteger(n)); + +export const isGraphPointerRuleRef = (pointer: GraphPointer): pointer is GraphPointer => + isRuleRef(pointer.rule); + +export const isGraphPointerRuleEnd = (pointer: GraphPointer): pointer is GraphPointer => + isRuleEnd(pointer.rule); + +export const isGraphPointerRuleChar = (pointer: GraphPointer): pointer is GraphPointer => + isRuleChar(pointer.rule); + +export const isGraphPointerRuleCharExclude = (pointer: GraphPointer): pointer is GraphPointer => + isRuleCharExclude(pointer.rule); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/types.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..d5d29b9e064b13b0167442e9008485746936ac54 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-graph/types.ts @@ -0,0 +1,80 @@ +import type { GraphPointer } from './graph-pointer.ts'; +import type { Pointers } from './pointers.ts'; +import { RuleRef } from './rule-ref.ts'; + +export { RuleRef }; + +export interface PrintOpts { + pointers?: Pointers; + colorize: (text: string | number, color: string) => string; + showPosition?: boolean; +} + +export type Range = [number, number]; + +export const RuleType = { + CHAR: 'char', + CHAR_EXCLUDE: 'char_exclude', + END: 'end', +} as const; +export type RuleType = (typeof RuleType)[keyof typeof RuleType]; + +// Rules carry their type as a plain property, so that two rules of the same type and value are +// structurally equal (e.g. with `toEqual`) and serialize to `{ type, value }`. +export class Rule { + readonly type: RuleType; + + protected constructor(type: RuleType) { + this.type = type; + } +} + +export class RuleWithValue extends Rule { + value: T; + + protected constructor(type: RuleType, value: T) { + super(type); + this.value = value; + } +} + +export class RuleWithListOfIntsOrRanges extends RuleWithValue<(number | Range)[]> { + protected constructor(type: RuleType, value: (number | Range)[] = []) { + super(type, value.slice()); + } +} + +export class RuleChar extends RuleWithListOfIntsOrRanges { + declare readonly type: typeof RuleType.CHAR; + + constructor(value?: (number | Range)[]) { + super(RuleType.CHAR, value); + } +} + +export class RuleCharExclude extends RuleWithListOfIntsOrRanges { + declare readonly type: typeof RuleType.CHAR_EXCLUDE; + + constructor(value?: (number | Range)[]) { + super(RuleType.CHAR_EXCLUDE, value); + } +} + +export class RuleEnd extends Rule { + declare readonly type: typeof RuleType.END; + + constructor() { + super(RuleType.END); + } +} + +export type UnresolvedRule = RuleChar | RuleCharExclude | RuleRef | RuleEnd; + +// ValidInput can either be a string, or a number indicating a code point. +// It CANNOT be a number representing a number; a number intended as input (like "8") +// should be passed in as a string. +export type ValidInput = string | number | number[]; + +// RuleRefs should never be exposed to the end user. +export type ResolvedRule = RuleCharExclude | RuleChar | RuleEnd; +export type ResolvedGraphPointer = GraphPointer; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-parser/build-rule-stack.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-parser/build-rule-stack.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8f8fbfc3840b1a3d13d24bb3292c538e7a1af02 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-parser/build-rule-stack.test.ts @@ -0,0 +1,283 @@ +import { describe, expect, test } from 'vitest'; +import { RuleRef } from '../grammar-graph/rule-ref.ts'; +import { type Range, RuleChar, RuleCharExclude, RuleEnd, type UnresolvedRule } from '../grammar-graph/types.ts'; +import { + type InternalRuleDef, + InternalRuleDefAlt, + InternalRuleDefChar, + InternalRuleDefCharAlt, + InternalRuleDefCharNot, + InternalRuleDefCharRngUpper, + InternalRuleDefEnd, + InternalRuleDefReference, +} from '../rules-builder/types.ts'; +import { buildRuleStack } from './build-rule-stack.ts'; + +const ord = (char: string): number => char.codePointAt(0) as number; + +const ichar = (value: number[]): InternalRuleDefChar => new InternalRuleDefChar(value); + +const icharAlt = (value: number): InternalRuleDefCharAlt => new InternalRuleDefCharAlt(value); + +const icharRngUpper = (value: number): InternalRuleDefCharRngUpper => new InternalRuleDefCharRngUpper(value); + +const icharNot = (value: number[]): InternalRuleDefCharNot => new InternalRuleDefCharNot(value); + +const ialt = (): InternalRuleDefAlt => new InternalRuleDefAlt(); + +const iend = (): InternalRuleDefEnd => new InternalRuleDefEnd(); + +const iref = (value: number): InternalRuleDefReference => new InternalRuleDefReference(value); + +const makeRange = (lower: number | string, upper: number | string): Range => [ + typeof lower === 'number' ? lower : ord(lower), + typeof upper === 'number' ? upper : ord(upper), +]; + +describe('buildRuleStack', () => { + test('it builds rule stack for a single path', () => { + expect(buildRuleStack([ichar([120])])).toEqual([[new RuleChar([120]), new RuleEnd()]]); + }); + + test('it builds rule stack for two alternate paths', () => { + const result = buildRuleStack([ichar([ord('x')]), ialt(), ichar([ord('y')])]); + expect(result).toEqual([[new RuleChar([ord('x')]), new RuleEnd()], [new RuleChar([ord('y')]), new RuleEnd()]]); + }); + + test('it builds rule stack for three alternate paths', () => { + expect(buildRuleStack([ichar([ord('x')]), ialt(), ichar([ord('y')]), ialt(), ichar([ord('z')])])).toEqual([ + [new RuleChar([ord('x')]), new RuleEnd()], + [new RuleChar([ord('y')]), new RuleEnd()], + [new RuleChar([ord('z')]), new RuleEnd()], + ]); + }); + + test('it builds rule stack for char not', () => { + expect( + buildRuleStack([icharNot([ord('x')]), ialt(), icharNot([ord('y')]), ialt(), icharNot([ord('z')])]), + ).toEqual([ + [new RuleCharExclude([ord('x')]), new RuleEnd()], + [new RuleCharExclude([ord('y')]), new RuleEnd()], + [new RuleCharExclude([ord('z')]), new RuleEnd()], + ]); + }); + + test('it builds rule stack for mixed char and char not', () => { + expect(buildRuleStack([icharNot([ord('x')]), ialt(), ichar([ord('y')]), ialt(), icharNot([ord('z')])])).toEqual([ + [new RuleCharExclude([ord('x')]), new RuleEnd()], + [new RuleChar([ord('y')]), new RuleEnd()], + [new RuleCharExclude([ord('z')]), new RuleEnd()], + ]); + }); + + test('it builds rule stack for char not with two characters and a range', () => { + const result = buildRuleStack([icharNot([ord('x')]), icharAlt(ord('y')), icharAlt(ord('z')), icharRngUpper(130)]); + expect(result).toEqual([[new RuleCharExclude([120, 121, makeRange(122, 130)]), new RuleEnd()]]); + }); + + describe('ranges', () => { + test.each<[string, InternalRuleDef[], UnresolvedRule[][]]>([ + [ + '[a-z]', + [ichar([ord('a')]), icharRngUpper(ord('z')), iend()], + [[new RuleChar([makeRange('a', 'z')]), new RuleEnd()]], + ], + [ + '[a-zA-Z]', + [ichar([ord('a')]), icharRngUpper(ord('z')), icharAlt(ord('A')), icharRngUpper(ord('Z')), iend()], + [[new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z')]), new RuleEnd()]], + ], + [ + '[a-zA-Z0-9]', + [ + ichar([ord('a')]), + icharRngUpper(ord('z')), + icharAlt(ord('A')), + icharRngUpper(ord('Z')), + icharAlt(ord('0')), + icharRngUpper(ord('9')), + iend(), + ], + [[new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z'), makeRange('0', '9')]), new RuleEnd()]], + ], + ])('it builds rule stack for a char with no modifiers: %s', (grammar, input, expected) => { + const result = buildRuleStack(input); + expect(result).toEqual(expected); + }); + }); + + test.each<[string, InternalRuleDef[], UnresolvedRule[][]]>([ + [ + '[a-z]?', + [ichar([ord('a')]), icharRngUpper(ord('z')), ialt(), iend()], + [[new RuleChar([makeRange('a', 'z')]), new RuleEnd()], [new RuleEnd()]], + ], + [ + '[a-zA-Z]?', + [ichar([ord('a')]), icharRngUpper(ord('z')), icharAlt(ord('A')), icharRngUpper(ord('Z')), ialt(), iend()], + [[new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z')]), new RuleEnd()], [new RuleEnd()]], + ], + [ + '[a-zA-Z0-9]?', + [ + ichar([ord('a')]), + icharRngUpper(ord('z')), + icharAlt(ord('A')), + icharRngUpper(ord('Z')), + icharAlt(ord('0')), + icharRngUpper(ord('9')), + ialt(), + iend(), + ], + [[new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z'), makeRange('0', '9')]), new RuleEnd()], [new RuleEnd()]], + ], + ])('it builds rule stack for a char with question mark modifier: %s', (grammar, input, expected) => { + expect(buildRuleStack(input)).toEqual(expected); + }); + + test.each<[string, InternalRuleDef[], UnresolvedRule[][]]>([ + [ + '[a-z]+', + [ichar([ord('a')]), icharRngUpper(ord('z')), iref(1), ialt(), ichar([ord('a')]), icharRngUpper(ord('z')), iend()], + [ + [new RuleChar([makeRange('a', 'z')]), new RuleRef(1), new RuleEnd()], + [new RuleChar([makeRange('a', 'z')]), new RuleEnd()], + ], + ], + [ + '[a-zA-Z]+', + [ + ichar([ord('a')]), + icharRngUpper(ord('z')), + icharAlt(ord('A')), + icharRngUpper(ord('Z')), + iref(1), + ialt(), + ichar([ord('a')]), + icharRngUpper(ord('z')), + icharAlt(ord('A')), + icharRngUpper(ord('Z')), + iend(), + ], + [ + [new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z')]), new RuleRef(1), new RuleEnd()], + [new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z')]), new RuleEnd()], + ], + ], + [ + '[a-zA-Z0-9]+', + [ + ichar([ord('a')]), + icharRngUpper(ord('z')), + icharAlt(ord('A')), + icharRngUpper(ord('Z')), + icharAlt(ord('0')), + icharRngUpper(ord('9')), + iref(1), + ialt(), + ichar([ord('a')]), + icharRngUpper(ord('z')), + icharAlt(ord('A')), + icharRngUpper(ord('Z')), + icharAlt(ord('0')), + icharRngUpper(ord('9')), + iend(), + ], + [ + [new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z'), makeRange('0', '9')]), new RuleRef(1), new RuleEnd()], + [new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z'), makeRange('0', '9')]), new RuleEnd()], + ], + ], + ])('it builds rule stack for a char with plus modifier: %s', (grammar, input, expected) => { + const result = buildRuleStack(input); + expect(result).toEqual(expected); + }); + + test.each<[string, InternalRuleDef[], UnresolvedRule[][]]>([ + [ + '[a-z]*', + [ichar([ord('a')]), icharRngUpper(ord('z')), iref(1), ialt(), iend()], + [[new RuleChar([makeRange('a', 'z')]), new RuleRef(1), new RuleEnd()], [new RuleEnd()]], + ], + [ + '[a-zA-Z]*', + [ + ichar([ord('a')]), + icharRngUpper(ord('z')), + icharAlt(ord('A')), + icharRngUpper(ord('Z')), + iref(1), + ialt(), + iend(), + ], + [[new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z')]), new RuleRef(1), new RuleEnd()], [new RuleEnd()]], + ], + [ + '[a-zA-Z0-9]*', + [ + ichar([ord('a')]), + icharRngUpper(ord('z')), + icharAlt(ord('A')), + icharRngUpper(ord('Z')), + icharAlt(ord('0')), + icharRngUpper(ord('9')), + iref(1), + ialt(), + iend(), + ], + [ + [new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z'), makeRange('0', '9')]), new RuleRef(1), new RuleEnd()], + [new RuleEnd()], + ], + ], + ])('it builds rule stack for a char with asterisk modifier: %s', (grammar, input, expected) => { + const result = buildRuleStack(input); + expect(result).toEqual(expected); + }); + + test('char with range', () => { + const input: InternalRuleDef[] = [ + ichar([ord('a')]), + icharRngUpper(ord('z')), + icharAlt(ord('A')), + icharRngUpper(ord('Z')), + icharAlt(ord('_')), + iend(), + ]; + + expect(buildRuleStack(input)).toEqual([ + [new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z'), ord('_')]), new RuleEnd()], + ]); + }); + + test('it builds rule stack for situation root ws plus newline ws star', () => { + const input: InternalRuleDef[] = [ichar([32]), icharAlt(92), icharAlt(110), iref(4), ialt(), iend()]; + + const expected = [[new RuleChar([32, 92, 110]), new RuleRef(4), new RuleEnd()], [new RuleEnd()]]; + + expect(buildRuleStack(input)).toEqual(expected); + }); + + test('it builds rule stack for situation root char plus char range', () => { + const input: InternalRuleDef[] = [ + ichar([ord('a')]), + icharRngUpper(ord('z')), + icharAlt(ord('A')), + icharRngUpper(ord('Z')), + iref(1), + ialt(), + ichar([ord('a')]), + icharRngUpper(ord('z')), + icharAlt(ord('A')), + icharRngUpper(ord('Z')), + iend(), + ]; + + const expected = [ + [new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z')]), new RuleRef(1), new RuleEnd()], + [new RuleChar([makeRange('a', 'z'), makeRange('A', 'Z')]), new RuleEnd()], + ]; + + expect(buildRuleStack(input)).toEqual(expected); + }); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-parser/build-rule-stack.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-parser/build-rule-stack.ts new file mode 100644 index 0000000000000000000000000000000000000000..9255428cfdec7355a59822eb5d83e77a0dac180f --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/grammar-parser/build-rule-stack.ts @@ -0,0 +1,89 @@ +import { isRange, isRuleEnd } from '../grammar-graph/type-guards.ts'; +import { RuleChar, RuleCharExclude, RuleEnd, RuleRef, type UnresolvedRule } from '../grammar-graph/types.ts'; +import { + type InternalRuleDef, + type InternalRuleDefChar, + type InternalRuleDefCharNot, + isRuleDefAlt, + isRuleDefChar, + isRuleDefCharAlt, + isRuleDefCharNot, + isRuleDefCharRngUpper, + isRuleDefEnd, + isRuleDefRef, +} from '../rules-builder/types.ts'; + +export const makeCharRule = (ruleDef: InternalRuleDefChar | InternalRuleDefCharNot): RuleChar | RuleCharExclude => { + const value = ruleDef.value; + if (isRuleDefCharNot(ruleDef)) { + return new RuleCharExclude(value); + } + if (isRuleDefChar(ruleDef)) { + return new RuleChar(value); + } + throw new Error(`Unsupported rule type for make_char_rule: ${JSON.stringify(ruleDef)}`); +}; + +export const buildRuleStack = (linearRules: InternalRuleDef[]): UnresolvedRule[][] => { + let paths: UnresolvedRule[] = []; + const stack: UnresolvedRule[][] = []; + let idx = 0; + + while (idx < linearRules.length) { + const ruleDef = linearRules[idx]; + if (isRuleDefChar(ruleDef) || isRuleDefCharNot(ruleDef)) { + // this could be a single char, or a range, or a sequence of alts; we don't know until we step through it. + const charRule = makeCharRule(ruleDef); + idx += 1; + let rule = idx < linearRules.length ? linearRules[idx] : undefined; + while (idx < linearRules.length && (isRuleDefCharRngUpper(rule) || isRuleDefCharAlt(rule))) { + if (isRuleDefCharRngUpper(rule)) { + // previous rule value should be a number + const prevValue = charRule.value.pop(); + if (isRange(prevValue)) { + throw new Error(`Unexpected range, expected a number but got an array: [${prevValue.join(', ')}]`); + } + if (prevValue === undefined) { + throw new Error('Unexpected undefined value'); + } + charRule.value.push([prevValue, rule.value]); + } + if (isRuleDefCharAlt(rule)) { + charRule.value.push(rule.value); + } + idx += 1; + rule = idx < linearRules.length ? linearRules[idx] : undefined; + } + paths.push(charRule); + } else { + if (isRuleDefAlt(ruleDef)) { + if (paths.length === 0) { + throw new Error('Encountered alt without anything before it'); + } + paths.push(new RuleEnd()); + stack.push(paths); + paths = []; + } else if (isRuleDefEnd(ruleDef)) { + paths.push(new RuleEnd()); + } else if (isRuleDefRef(ruleDef)) { + paths.push(new RuleRef(ruleDef.value)); + } else if (isRuleDefCharAlt(ruleDef)) { + throw new Error(`Encountered char alt, should be handled by above block: ${JSON.stringify(ruleDef)}`); + } else { + throw new Error(`Unsupported rule type: ${JSON.stringify(ruleDef)}`); + } + idx += 1; + } + } + + // the reference reads the last element of the path unconditionally, and so fails on an empty path + if (paths.length === 0) { + throw new RangeError('list index out of range'); + } + if (!isRuleEnd(paths[paths.length - 1])) { + paths.push(new RuleEnd()); + } + stack.push(paths); + + return stack; +}; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/index.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..54b45273d8a6dfdedfaed39954d72592ea27a1ed --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/index.ts @@ -0,0 +1,8 @@ +import { GBNF } from './gbnf.ts'; + +export { GBNF }; +export default GBNF; +export { ParseState } from './grammar-graph/parse-state.ts'; +export { RuleChar, RuleCharExclude, RuleEnd, RuleType } from './grammar-graph/types.ts'; +export type { Range, ResolvedRule } from './grammar-graph/types.ts'; +export { GrammarParseError, InputParseError } from './utils/errors/index.ts'; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/index.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..003b61791ef70ecadfdfb0a50a08e689d22a6456 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/index.ts @@ -0,0 +1,2 @@ +export { GrammarParseError, InputParseError } from '../utils/errors/index.ts'; +export { RulesBuilder } from './rules-builder.ts'; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/is-space.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/is-space.ts new file mode 100644 index 0000000000000000000000000000000000000000..879a8a2fc24dac2c5ee28d979c18da3004b66098 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/is-space.ts @@ -0,0 +1,4 @@ +// The characters that Python's str.isspace() considers to be whitespace. +const WHITESPACE = /^[\t-\r\x1c-\x20\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]$/; + +export const isSpace = (c: string): boolean => WHITESPACE.test(c); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/is-word-char.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/is-word-char.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f9eedb98548bc2558966730b95dd956e2f4a5cd --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/is-word-char.test.ts @@ -0,0 +1,25 @@ +import { expect, test } from 'vitest'; +import { isWordChar } from './is-word-char.ts'; + +test('should return true for lowercase letters', () => { + expect(isWordChar('a')).toBe(true); + expect(isWordChar('z')).toBe(true); +}); + +test('should return true for uppercase letters', () => { + expect(isWordChar('A')).toBe(true); + expect(isWordChar('Z')).toBe(true); +}); + +test('should return false for digits', () => { + expect(isWordChar('0')).toBe(false); + expect(isWordChar('9')).toBe(false); +}); + +test('should return false for non word characters', () => { + expect(isWordChar('-')).toBe(false); + expect(isWordChar('@')).toBe(false); + expect(isWordChar('_')).toBe(false); + expect(isWordChar('?')).toBe(false); + expect(isWordChar(' ')).toBe(false); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/is-word-char.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/is-word-char.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d999efb2183c75f684dd310b19ba0f88c224318 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/is-word-char.ts @@ -0,0 +1 @@ +export const isWordChar = (c: string): boolean => /[a-zA-Z]/.test(c); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-char.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-char.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1090ba6116af987bb5c48350a0f46256c63c72eb --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-char.test.ts @@ -0,0 +1,37 @@ +import { expect, test } from 'vitest'; +import { GrammarParseError } from '../utils/errors/index.ts'; +import { parseChar } from './parse-char.ts'; + +const ord = (char: string): number => char.codePointAt(0) as number; + +test.each<[string, string, number]>([ + ['escaped 8-bit unicode char', 'a', ord('a')], + ['escaped 8-bit unicode char', '9', ord('9')], +])('parse char simple (%j, %j)', (_description, char, codePoint) => { + const grammar = `root ::= "${char}" "foo"`; + expect(parseChar(grammar, 'root ::= "'.length)).toEqual([codePoint, 1]); +}); + +test.each<[string, string, number, number]>([ + ['escaped 8-bit unicode char', '\\x2A', ord('\x2A'), 4], + ['escaped 16-bit unicode char', '\\u006F', ord('\u006F'), 6], + ['escaped 32-bit unicode char', '\\U0001F4A9', 128169, 10], + ['escaped tab char', '\\t', ord('\t'), 2], + ['escaped new line char', '\\n', ord('\n'), 2], + ['escaped \r char', '\\r', ord('\r'), 2], + ['escaped quote char', '\\"', ord('"'), 2], + ['escaped [ char', '\\[', ord('['), 2], + ['escaped ] char', '\\]', ord(']'), 2], + ['escaped \\ char', '\\\\', ord('\\'), 2], +])('parse char complex (%j, %j)', (_description, escapedChar, codePoint, incPos) => { + const grammar = `root ::= "${escapedChar}" "foo"`; + expect(parseChar(grammar, 'root ::= "'.length)).toEqual([codePoint, incPos]); +}); + +test.each<[string, number]>([ + ['', 0], + ['a', 1], + ['a', 2], +])('parse char raises (%j, %i)', (input, pos) => { + expect(() => parseChar(input, pos)).toThrow(GrammarParseError); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-char.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-char.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfb1cd14cd94ee00d9bb13200f917353a4bf84af --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-char.ts @@ -0,0 +1,105 @@ +import { getChars } from '../utils/code-points.ts'; +import { GrammarParseError } from '../utils/errors/index.ts'; + +const ESCAPED_CONTROL_CHARS: Record = { t: '\t', r: '\r', n: '\n' }; + +const NON_ASCII_WHITESPACE = /[\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/; +const DECIMAL_DIGIT = /^\p{Nd}$/u; +const NON_PRINTABLE = /^[\p{C}\p{Z}]$/u; +const HEX_LITERAL = /^[ \t-\r]*([+-]?)(?:0[xX]_?)?([0-9a-fA-F]+(?:_[0-9a-fA-F]+)*)[ \t-\r]*$/; + +// Unicode encodes decimal digits in contiguous runs of ten, in ascending order. +const getDecimalDigit = (char: string): number | undefined => { + if (!DECIMAL_DIGIT.test(char)) { + return undefined; + } + const codePoint = char.codePointAt(0) as number; + let start = codePoint; + while (DECIMAL_DIGIT.test(String.fromCodePoint(start - 1))) { + start -= 1; + } + return (codePoint - start) % 10; +}; + +const escapeCodePoint = (codePoint: number): string => { + const hex = codePoint.toString(16); + if (codePoint <= 0xff) { + return `\\x${hex.padStart(2, '0')}`; + } + if (codePoint <= 0xffff) { + return `\\u${hex.padStart(4, '0')}`; + } + return `\\U${hex.padStart(8, '0')}`; +}; + +// Quotes a string the way Python's repr() does, which is how the reference reports a malformed escape. +const repr = (text: string): string => { + const quote = text.includes("'") && !text.includes('"') ? '"' : "'"; + let quoted = quote; + for (const char of text) { + if (char === quote || char === '\\') { + quoted += `\\${char}`; + } else if (char === '\t') { + quoted += '\\t'; + } else if (char === '\n') { + quoted += '\\n'; + } else if (char === '\r') { + quoted += '\\r'; + } else if (char !== ' ' && NON_PRINTABLE.test(char)) { + quoted += escapeCodePoint(char.codePointAt(0) as number); + } else { + quoted += char; + } + } + return quoted + quote; +}; + +// Escapes are read the way the Python reference reads them, with int(text, 16). On top of plain hex digits, +// that accepts surrounding whitespace, a sign, a 0x prefix, single underscores between digits, and any +// Unicode decimal digit. +export const parseHex = (text: string): number => { + let normalized = ''; + for (const char of text) { + if ((char.codePointAt(0) as number) < 127) { + normalized += char; + } else if (NON_ASCII_WHITESPACE.test(char)) { + normalized += ' '; + } else { + normalized += getDecimalDigit(char) ?? '?'; + } + } + + const match = HEX_LITERAL.exec(normalized); + if (match === null) { + throw new Error(`invalid literal for int() with base 16: ${repr(text)}`); + } + const value = Number.parseInt(match[2].replaceAll('_', ''), 16); + return match[1] === '-' && value !== 0 ? -value : value; +}; + +export const parseChar = (src: string, pos: number): [number, number] => { + const chars = getChars(src); + if (pos >= chars.length) { + throw new GrammarParseError(src, pos, 'Unexpected end of grammar input, failed to complete parse'); + } + if (chars[pos] === '\\') { + const escaped = chars[pos + 1]; + if (escaped === 'x') { + return [parseHex(chars.slice(pos + 2, pos + 4).join('')), 4]; + } + if (escaped === 'u') { + return [parseHex(chars.slice(pos + 2, pos + 6).join('')), 6]; + } + if (escaped === 'U') { + return [parseHex(chars.slice(pos + 2, pos + 10).join('')), 10]; + } + if (escaped === 't' || escaped === 'r' || escaped === 'n') { + return [ESCAPED_CONTROL_CHARS[escaped].codePointAt(0) as number, 2]; + } + if (escaped === '"' || escaped === '[' || escaped === ']' || escaped === '\\') { + return [escaped.codePointAt(0) as number, 2]; + } + throw new GrammarParseError(src, pos, `Unknown escape at ${chars[pos]}`); + } + return [chars[pos].codePointAt(0) as number, 1]; +}; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-name.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-name.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b248730379f65febb3819ddf429f7e2cd3c08fc --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-name.test.ts @@ -0,0 +1,22 @@ +import { expect, test } from 'vitest'; +import { GrammarParseError } from '../utils/errors/index.ts'; +import { PARSE_NAME_ERROR, parseName } from './parse-name.ts'; + +test('should return correct name when encountering a valid name', () => { + const src = 'validName'; + const name = parseName(src, 0); + expect(name).toEqual(src); +}); + +test('should return correct name when encountering a valid name starting at a non zero position', () => { + const src = '123validName'; + const name = parseName(src, 3); + expect(name).toEqual('validName'); +}); + +test('should throw error when encountering an invalid name', () => { + const src = '123'; + const act = () => parseName(src, 0); + expect(act).toThrow(GrammarParseError); + expect(act).toThrow(new GrammarParseError(src, 0, PARSE_NAME_ERROR)); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-name.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-name.ts new file mode 100644 index 0000000000000000000000000000000000000000..e57d08c5e99105ac69c0b5db15945687a284f126 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-name.ts @@ -0,0 +1,21 @@ +import { getChars } from '../utils/code-points.ts'; +import { GrammarParseError } from '../utils/errors/index.ts'; +import { isWordChar } from './is-word-char.ts'; + +export const PARSE_NAME_ERROR = 'Failed to find a valid name'; +const VALID_NAME_SEPARATORS = ['-', '_']; + +export const parseName = (grammar: string, pos: number): string => { + const chars = getChars(grammar); + let name = ''; + + while (pos < chars.length && (isWordChar(chars[pos]) || VALID_NAME_SEPARATORS.includes(chars[pos]))) { + name += chars[pos]; + pos += 1; + } + + if (!name) { + throw new GrammarParseError(grammar, pos, PARSE_NAME_ERROR); + } + return name; +}; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-space.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-space.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..458e73b3ef45548778b9dd15b1c7920e4c1b2c76 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-space.test.ts @@ -0,0 +1,64 @@ +import { expect, test } from 'vitest'; +import { parseSpace } from './parse-space.ts'; + +test('return input string when no whitespace or comments', () => { + const inputStr = 'abcdefghijk'; + const pos = parseSpace(inputStr, 0, true); + expect(inputStr.slice(pos)).toEqual(inputStr); +}); + +test('skip leading spaces and tabs', () => { + const inputStr = ' \t abcdefghijk'; + const expected = 'abcdefghijk'; + const pos = parseSpace(inputStr, 0, true); + expect(inputStr.slice(pos)).toEqual(expected); +}); + +test('skip leading newline characters when newline ok true', () => { + const inputStr = '\n\n\r\n\r\nabcdefghijk'; + const expected = 'abcdefghijk'; + const pos = parseSpace(inputStr, 0, true); + expect(inputStr.slice(pos)).toEqual(expected); +}); + +test('not skip leading newline characters when newline ok false', () => { + const inputStr = '\n\n\r\n\r\nabcdefghijk'; + const expected = '\n\n\r\n\r\nabcdefghijk'; + const pos = parseSpace(inputStr, 0, false); + expect(inputStr.slice(pos)).toEqual(expected); +}); + +test('skip comments and leading spaces', () => { + const inputStr = ' # This is a comment\n\t abcdefghijk'; + const expected = 'abcdefghijk'; + const pos = parseSpace(inputStr, 0, true); + expect(inputStr.slice(pos)).toEqual(expected); +}); + +test('skip comments and leading newline characters when newline ok true', () => { + const inputStr = '\n\n # This is a comment\n\r\n\r\nabcdefghijk'; + const expected = 'abcdefghijk'; + const pos = parseSpace(inputStr, 0, true); + expect(inputStr.slice(pos)).toEqual(expected); +}); + +test('skip comments and leading newline characters when newline ok false', () => { + const inputStr = '\n\n # This is a comment\n\r\n\r\nabcdefghijk'; + const expected = '\n\n # This is a comment\n\r\n\r\nabcdefghijk'; + const pos = parseSpace(inputStr, 0, false); + expect(inputStr.slice(pos)).toEqual(expected); +}); + +test('return empty string if input all whitespace and comments', () => { + const inputStr = ' \t# Comment\n# Another comment\n\n'; + const expected = ''; + const pos = parseSpace(inputStr, 0, true); + expect(inputStr.slice(pos)).toEqual(expected); +}); + +test('return empty string for empty input string', () => { + const inputStr = ''; + const expected = ''; + const pos = parseSpace(inputStr, 0, true); + expect(inputStr.slice(pos)).toEqual(expected); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-space.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-space.ts new file mode 100644 index 0000000000000000000000000000000000000000..f712e5dd5b5df9834e00cbd8bcfcc3f568e708e6 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/parse-space.ts @@ -0,0 +1,21 @@ +import { getChars } from '../utils/code-points.ts'; + +export const parseSpace = (src: string, pos: number, newlineOk: boolean): number => { + const chars = getChars(src); + while ( + pos < chars.length && + (chars[pos] === ' ' || + chars[pos] === '\t' || + chars[pos] === '#' || + (newlineOk && (chars[pos] === '\r' || chars[pos] === '\n'))) + ) { + if (chars[pos] === '#') { + while (pos < chars.length && chars[pos] !== '\r' && chars[pos] !== '\n') { + pos += 1; + } + } else { + pos += 1; + } + } + return pos; +}; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/rules-builder.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/rules-builder.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ef4174987c727013f148616100142c91edbf00f --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/rules-builder.test.ts @@ -0,0 +1,1254 @@ +import { expect, test } from 'vitest'; +import { RulesBuilder } from './rules-builder.ts'; +import { + type InternalRuleDef, + InternalRuleDefAlt, + InternalRuleDefChar, + InternalRuleDefCharAlt, + InternalRuleDefCharNot, + InternalRuleDefCharRngUpper, + InternalRuleDefEnd, + InternalRuleDefReference, +} from './types.ts'; + +const ord = (char: string): number => char.codePointAt(0) as number; + +type TestCase = [string, string, [[string, number][], InternalRuleDef[][]]]; + +const testCases: TestCase[] = [ + [ + 'single-string', + 'root ::= "foo"', + [ + [['root', 0]], + [ + [ + new InternalRuleDefChar([ord('f')]), + new InternalRuleDefChar([ord('o')]), + new InternalRuleDefChar([ord('o')]), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'quote character', + 'root ::= "\\""', + [[['root', 0]], [[new InternalRuleDefChar([ord('"')]), new InternalRuleDefEnd()]]], + ], + [ + 'two-lines-referencing-expression', + `root ::= foo + foo ::= "bar"`, + [ + [['root', 0], ['foo', 1]], + [ + [new InternalRuleDefReference(1), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([ord('b')]), + new InternalRuleDefChar([ord('a')]), + new InternalRuleDefChar([ord('r')]), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'expression with dash', + `root ::= foo-bar + foo-bar ::= "bar"`, + [ + [['root', 0], ['foo-bar', 1]], + [ + [new InternalRuleDefReference(1), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([ord('b')]), + new InternalRuleDefChar([ord('a')]), + new InternalRuleDefChar([ord('r')]), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'simple-grammar', + ` + root ::= (expr "=" term " +")+ + expr ::= term ([-+*/] term)* + term ::= [0-9]+ + `, + [ + [ + ['root', 0], + ['root_1', 1], + ['expr', 2], + ['term', 3], + ['root_4', 4], + ['expr_5', 5], + ['expr_6', 6], + ['term_7', 7], + ], + [ + [new InternalRuleDefReference(4), new InternalRuleDefEnd()], + [ + new InternalRuleDefReference(2), + new InternalRuleDefChar([61]), + new InternalRuleDefReference(3), + new InternalRuleDefChar([10]), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(3), new InternalRuleDefReference(6), new InternalRuleDefEnd()], + [new InternalRuleDefReference(7), new InternalRuleDefEnd()], + [ + new InternalRuleDefReference(1), + new InternalRuleDefReference(4), + new InternalRuleDefAlt(), + new InternalRuleDefReference(1), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([45]), + new InternalRuleDefCharAlt(43), + new InternalRuleDefCharAlt(42), + new InternalRuleDefCharAlt(47), + new InternalRuleDefReference(3), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(5), + new InternalRuleDefReference(6), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefReference(7), + new InternalRuleDefAlt(), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'longer-grammar', + '\n root ::= (expr "=" ws term "\n")+\n expr ::= term ([-+*/] term)*\n term ::= ident | num | "(" ws expr ")" ws\n ident ::= [a-z] [a-z0-9_]* ws\n num ::= [0-9]+ ws\n ws ::= [ \t\n]*\n ', + [ + [ + ['root', 0], + ['root_1', 1], + ['expr', 2], + ['ws', 3], + ['term', 4], + ['root_5', 5], + ['expr_6', 6], + ['expr_7', 7], + ['ident', 8], + ['num', 9], + ['ident_10', 10], + ['num_11', 11], + ['ws_12', 12], + ], + [ + [new InternalRuleDefReference(5), new InternalRuleDefEnd()], + [ + new InternalRuleDefReference(2), + new InternalRuleDefChar([61]), + new InternalRuleDefReference(3), + new InternalRuleDefReference(4), + new InternalRuleDefChar([10]), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(4), new InternalRuleDefReference(7), new InternalRuleDefEnd()], + [new InternalRuleDefReference(12), new InternalRuleDefEnd()], + [ + new InternalRuleDefReference(8), + new InternalRuleDefAlt(), + new InternalRuleDefReference(9), + new InternalRuleDefAlt(), + new InternalRuleDefChar([40]), + new InternalRuleDefReference(3), + new InternalRuleDefReference(2), + new InternalRuleDefChar([41]), + new InternalRuleDefReference(3), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(1), + new InternalRuleDefReference(5), + new InternalRuleDefAlt(), + new InternalRuleDefReference(1), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([45]), + new InternalRuleDefCharAlt(43), + new InternalRuleDefCharAlt(42), + new InternalRuleDefCharAlt(47), + new InternalRuleDefReference(4), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(6), + new InternalRuleDefReference(7), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([97]), + new InternalRuleDefCharRngUpper(122), + new InternalRuleDefReference(10), + new InternalRuleDefReference(3), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(11), new InternalRuleDefReference(3), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([97]), + new InternalRuleDefCharRngUpper(122), + new InternalRuleDefCharAlt(48), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(95), + new InternalRuleDefReference(10), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefReference(11), + new InternalRuleDefAlt(), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([32]), + new InternalRuleDefCharAlt(9), + new InternalRuleDefCharAlt(10), + new InternalRuleDefReference(12), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'character unicode grammar', + 'root ::= [ぁ-ゟ]', + [ + [['root', 0]], + [[new InternalRuleDefChar([ord('ぁ')]), new InternalRuleDefCharRngUpper(ord('ゟ')), new InternalRuleDefEnd()]], + ], + ], + [ + 'character alts grammar', + 'root ::= [az]', + [ + [['root', 0]], + [[new InternalRuleDefChar([ord('a')]), new InternalRuleDefCharAlt(ord('z')), new InternalRuleDefEnd()]], + ], + ], + [ + 'character range grammar', + 'root ::= [a-zA-Z0-9]', + [ + [['root', 0]], + [ + [ + new InternalRuleDefChar([ord('a')]), + new InternalRuleDefCharRngUpper(ord('z')), + new InternalRuleDefCharAlt(ord('A')), + new InternalRuleDefCharRngUpper(ord('Z')), + new InternalRuleDefCharAlt(ord('0')), + new InternalRuleDefCharRngUpper(ord('9')), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'character range grammar with dash at end', + 'root ::= [a-z-]', + [ + [['root', 0]], + [ + [ + new InternalRuleDefChar([ord('a')]), + new InternalRuleDefCharRngUpper(ord('z')), + new InternalRuleDefCharAlt(ord('-')), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'grouping', + 'root ::= "f" ("b" | "a")', + [ + [['root', 0], ['root_1', 1]], + [ + [new InternalRuleDefChar([ord('f')]), new InternalRuleDefReference(1), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([ord('b')]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([ord('a')]), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'optional', + 'root ::= "f"?', + [ + [['root', 0], ['root_1', 1]], + [ + [new InternalRuleDefReference(1), new InternalRuleDefEnd()], + [new InternalRuleDefChar([ord('f')]), new InternalRuleDefAlt(), new InternalRuleDefEnd()], + ], + ], + ], + [ + 'repeating', + 'root ::= "f"*', + [ + [['root', 0], ['root_1', 1]], + [ + [new InternalRuleDefReference(1), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([ord('f')]), + new InternalRuleDefReference(1), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'repeating-at-least-once', + 'root ::= "f"+', + [ + [['root', 0], ['root_1', 1]], + [ + [new InternalRuleDefReference(1), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([ord('f')]), + new InternalRuleDefReference(1), + new InternalRuleDefAlt(), + new InternalRuleDefChar([ord('f')]), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'character range with optional repeating', + 'root ::= [a-zA-Z0-9]*', + [ + [['root', 0], ['root_1', 1]], + [ + [new InternalRuleDefReference(1), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([ord('a')]), + new InternalRuleDefCharRngUpper(ord('z')), + new InternalRuleDefCharAlt(ord('A')), + new InternalRuleDefCharRngUpper(ord('Z')), + new InternalRuleDefCharAlt(ord('0')), + new InternalRuleDefCharRngUpper(ord('9')), + new InternalRuleDefReference(1), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'grouping-repeating', + 'root ::= "f" ("b" | "a")*', + [ + [['root', 0], ['root_1', 1], ['root_2', 2]], + [ + [new InternalRuleDefChar([ord('f')]), new InternalRuleDefReference(2), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([ord('b')]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([ord('a')]), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(1), + new InternalRuleDefReference(2), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'negation', + 'root ::= [^\\n]', + [[['root', 0]], [[new InternalRuleDefCharNot([ord('\n')]), new InternalRuleDefEnd()]]], + ], + [ + 'negation of range', + 'root ::= [^0-9]', + [ + [['root', 0]], + [[new InternalRuleDefCharNot([ord('0')]), new InternalRuleDefCharRngUpper(ord('9')), new InternalRuleDefEnd()]], + ], + ], + [ + 'negation with after', + 'root ::= [^\\n]+ "\\n"', + [ + [['root', 0], ['root_1', 1]], + [ + [new InternalRuleDefReference(1), new InternalRuleDefChar([ord('\n')]), new InternalRuleDefEnd()], + [ + new InternalRuleDefCharNot([ord('\n')]), + new InternalRuleDefReference(1), + new InternalRuleDefAlt(), + new InternalRuleDefCharNot([ord('\n')]), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'longer negation', + 'root ::= "\\"" ( [^"abcdefgh])* ', + [ + [['root', 0], ['root_1', 1], ['root_2', 2]], + [ + [new InternalRuleDefChar([34]), new InternalRuleDefReference(2), new InternalRuleDefEnd()], + [ + new InternalRuleDefCharNot([34]), + new InternalRuleDefCharAlt(97), + new InternalRuleDefCharAlt(98), + new InternalRuleDefCharAlt(99), + new InternalRuleDefCharAlt(100), + new InternalRuleDefCharAlt(101), + new InternalRuleDefCharAlt(102), + new InternalRuleDefCharAlt(103), + new InternalRuleDefCharAlt(104), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(1), + new InternalRuleDefReference(2), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'longer negation with a range', + 'root ::= "\\"" ( [^"abcdefghA-Z])* ', + [ + [['root', 0], ['root_1', 1], ['root_2', 2]], + [ + [new InternalRuleDefChar([34]), new InternalRuleDefReference(2), new InternalRuleDefEnd()], + [ + new InternalRuleDefCharNot([34]), + new InternalRuleDefCharAlt(97), + new InternalRuleDefCharAlt(98), + new InternalRuleDefCharAlt(99), + new InternalRuleDefCharAlt(100), + new InternalRuleDefCharAlt(101), + new InternalRuleDefCharAlt(102), + new InternalRuleDefCharAlt(103), + new InternalRuleDefCharAlt(104), + new InternalRuleDefCharAlt(65), + new InternalRuleDefCharRngUpper(ord('Z')), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(1), + new InternalRuleDefReference(2), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + ], + ], + ], + ...( + [ + ['escaped 8-bit unicode char', '\\x2A', ord('*')], + ['escaped 16-bit unicode char', '\\u006F', ord('o')], + ['escaped 32-bit unicode char', '\\U0001F4A9', 128169], + ['escaped tab char', '\\t', ord('\t')], + ['escaped new line char', '\\n', ord('\n')], + ['escaped \r char', '\\r', ord('\r')], + ['escaped quote char', '\\"', ord('"')], + ['escaped [ char', '\\[', ord('[')], + ['escaped ] char', '\\]', ord(']')], + ['escaped \\ char', '\\\\', ord('\\')], + ] as [string, string, number][] + ).map(([key, escapedChar, actualChar]): TestCase => [ + key, + `root ::= "${escapedChar}"`, + [[['root', 0]], [[new InternalRuleDefChar([actualChar]), new InternalRuleDefEnd()]]], + ]), + [ + 'simple arithmetic', + ` + root ::= (expr "=" term "\\n")+ + expr ::= term ([-+*/] term)* + term ::= [0-9]+ + `, + [ + [ + ['root', 0], + ['root_1', 1], + ['expr', 2], + ['term', 3], + ['root_4', 4], + ['expr_5', 5], + ['expr_6', 6], + ['term_7', 7], + ], + [ + [new InternalRuleDefReference(4), new InternalRuleDefEnd()], + [ + new InternalRuleDefReference(2), + new InternalRuleDefChar([61]), + new InternalRuleDefReference(3), + new InternalRuleDefChar([10]), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(3), new InternalRuleDefReference(6), new InternalRuleDefEnd()], + [new InternalRuleDefReference(7), new InternalRuleDefEnd()], + [ + new InternalRuleDefReference(1), + new InternalRuleDefReference(4), + new InternalRuleDefAlt(), + new InternalRuleDefReference(1), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([45]), + new InternalRuleDefCharAlt(43), + new InternalRuleDefCharAlt(42), + new InternalRuleDefCharAlt(47), + new InternalRuleDefReference(3), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(5), + new InternalRuleDefReference(6), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefReference(7), + new InternalRuleDefAlt(), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'ranges with chars', + ` + root ::= [a-z0-9_]* + `, + [ + [['root', 0], ['root_1', 1]], + [ + [new InternalRuleDefReference(1), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([97]), + new InternalRuleDefCharRngUpper(122), + new InternalRuleDefCharAlt(48), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(95), + new InternalRuleDefReference(1), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'nested ranges with chars', + ` + root ::= [a-z] [a-z0-9_]* + `, + [ + [['root', 0], ['root_1', 1]], + [ + [ + new InternalRuleDefChar([97]), + new InternalRuleDefCharRngUpper(122), + new InternalRuleDefReference(1), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([97]), + new InternalRuleDefCharRngUpper(122), + new InternalRuleDefCharAlt(48), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(95), + new InternalRuleDefReference(1), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'expression with nested range with chars', + ` + root ::= ident + ident ::= [a-z] [a-z0-9_]* ws + ws ::= [ \\t\\n]* + `, + [ + [['root', 0], ['ident', 1], ['ident_2', 2], ['ws', 3], ['ws_4', 4]], + [ + [new InternalRuleDefReference(1), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([97]), + new InternalRuleDefCharRngUpper(122), + new InternalRuleDefReference(2), + new InternalRuleDefReference(3), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([97]), + new InternalRuleDefCharRngUpper(122), + new InternalRuleDefCharAlt(48), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(95), + new InternalRuleDefReference(2), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(4), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([32]), + new InternalRuleDefCharAlt(9), + new InternalRuleDefCharAlt(10), + new InternalRuleDefReference(4), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'lots of escapes', + 'root ::= "\\x2A" "\\u006F" "\\U0001F4A9" "\\t" "\\n" "\\r" "\\"" "\\[" "\\]" "\\\\"', + [ + [['root', 0]], + [ + [ + new InternalRuleDefChar([42]), + new InternalRuleDefChar([111]), + new InternalRuleDefChar([128169]), + new InternalRuleDefChar([9]), + new InternalRuleDefChar([10]), + new InternalRuleDefChar([13]), + new InternalRuleDefChar([34]), + new InternalRuleDefChar([91]), + new InternalRuleDefChar([93]), + new InternalRuleDefChar([92]), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'lots of escape and alternate escapes', + `root ::= "\\x2A" "\\u006F" "\\U0001F4A9" "\\t" "\\n" "\\r" "\\"" "\\[" "\\]" "\\\\" ( + "\\x2A" | "\\u006F" | "\\U0001F4A9" | "\\t" | "\\n" | "\\r" | "\\"" | "\\[" | "\\]" | "\\\\" )`, + [ + [['root', 0], ['root_1', 1]], + [ + [ + new InternalRuleDefChar([42]), + new InternalRuleDefChar([111]), + new InternalRuleDefChar([128169]), + new InternalRuleDefChar([9]), + new InternalRuleDefChar([10]), + new InternalRuleDefChar([13]), + new InternalRuleDefChar([34]), + new InternalRuleDefChar([91]), + new InternalRuleDefChar([93]), + new InternalRuleDefChar([92]), + new InternalRuleDefReference(1), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([42]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([111]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([128169]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([9]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([10]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([13]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([34]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([91]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([93]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([92]), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'arithmetic', + ` + root ::= (expr "=" ws term "\\n")+ + expr ::= term ([-+*/] term)* + term ::= ident | num | "(" ws expr ")" ws + ident ::= [a-z] [a-z0-9_]* ws + num ::= [0-9]+ ws + ws ::= [ \\t\\n]* + `, + [ + [ + ['root', 0], + ['root_1', 1], + ['expr', 2], + ['ws', 3], + ['term', 4], + ['root_5', 5], + ['expr_6', 6], + ['expr_7', 7], + ['ident', 8], + ['num', 9], + ['ident_10', 10], + ['num_11', 11], + ['ws_12', 12], + ], + [ + [new InternalRuleDefReference(5), new InternalRuleDefEnd()], + [ + new InternalRuleDefReference(2), + new InternalRuleDefChar([61]), + new InternalRuleDefReference(3), + new InternalRuleDefReference(4), + new InternalRuleDefChar([10]), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(4), new InternalRuleDefReference(7), new InternalRuleDefEnd()], + [new InternalRuleDefReference(12), new InternalRuleDefEnd()], + [ + new InternalRuleDefReference(8), + new InternalRuleDefAlt(), + new InternalRuleDefReference(9), + new InternalRuleDefAlt(), + new InternalRuleDefChar([40]), + new InternalRuleDefReference(3), + new InternalRuleDefReference(2), + new InternalRuleDefChar([41]), + new InternalRuleDefReference(3), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(1), + new InternalRuleDefReference(5), + new InternalRuleDefAlt(), + new InternalRuleDefReference(1), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([45]), + new InternalRuleDefCharAlt(43), + new InternalRuleDefCharAlt(42), + new InternalRuleDefCharAlt(47), + new InternalRuleDefReference(4), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(6), + new InternalRuleDefReference(7), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([97]), + new InternalRuleDefCharRngUpper(122), + new InternalRuleDefReference(10), + new InternalRuleDefReference(3), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(11), new InternalRuleDefReference(3), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([97]), + new InternalRuleDefCharRngUpper(122), + new InternalRuleDefCharAlt(48), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(95), + new InternalRuleDefReference(10), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefReference(11), + new InternalRuleDefAlt(), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([32]), + new InternalRuleDefCharAlt(9), + new InternalRuleDefCharAlt(10), + new InternalRuleDefReference(12), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'json.gbnf (string)', + ` + root ::= + "\\"" ( + [^"\\\\\\x7F\\x00-\\x1F] | + "\\\\" (["\\\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes + )* "\\"" + `, + [ + [['root', 0], ['root_1', 1], ['root_2', 2], ['root_3', 3]], + [ + [ + new InternalRuleDefChar([34]), + new InternalRuleDefReference(3), + new InternalRuleDefChar([34]), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefCharNot([34]), + new InternalRuleDefCharAlt(92), + new InternalRuleDefCharAlt(127), + new InternalRuleDefCharAlt(0), + new InternalRuleDefCharRngUpper(31), + new InternalRuleDefAlt(), + new InternalRuleDefChar([92]), + new InternalRuleDefReference(2), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([34]), + new InternalRuleDefCharAlt(92), + new InternalRuleDefCharAlt(47), + new InternalRuleDefCharAlt(98), + new InternalRuleDefCharAlt(102), + new InternalRuleDefCharAlt(110), + new InternalRuleDefCharAlt(114), + new InternalRuleDefCharAlt(116), + new InternalRuleDefAlt(), + new InternalRuleDefChar([117]), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(97), + new InternalRuleDefCharRngUpper(102), + new InternalRuleDefCharAlt(65), + new InternalRuleDefCharRngUpper(70), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(97), + new InternalRuleDefCharRngUpper(102), + new InternalRuleDefCharAlt(65), + new InternalRuleDefCharRngUpper(70), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(97), + new InternalRuleDefCharRngUpper(102), + new InternalRuleDefCharAlt(65), + new InternalRuleDefCharRngUpper(70), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(97), + new InternalRuleDefCharRngUpper(102), + new InternalRuleDefCharAlt(65), + new InternalRuleDefCharRngUpper(70), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(1), + new InternalRuleDefReference(3), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + ], + ], + ], + [ + 'json.gbnf (full)', + ` + root ::= object + value ::= object | array | string | number | ("true" | "false" | "null") ws + object ::= + "{" ws ( + string ":" ws value + ("," ws string ":" ws value)* + )? "}" ws + array ::= + "[" ws ( + value + ("," ws value)* + )? "]" ws + string ::= + "\\"" ( + [^"\\\\\\x7F\\x00-\\x1F] | + "\\\\" (["\\\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes + )* "\\"" ws + number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws + # Optional space: by convention, applied in this grammar after literal chars when allowed + ws ::= ([ \\t\\n] ws)? + `, + [ + [ + ['root', 0], + ['object', 1], + ['value', 2], + ['array', 3], + ['string', 4], + ['number', 5], + ['value_6', 6], + ['ws', 7], + ['object_8', 8], + ['object_9', 9], + ['object_10', 10], + ['object_11', 11], + ['array_12', 12], + ['array_13', 13], + ['array_14', 14], + ['array_15', 15], + ['string_16', 16], + ['string_17', 17], + ['string_18', 18], + ['number_19', 19], + ['number_20', 20], + ['number_21', 21], + ['number_22', 22], + ['number_23', 23], + ['number_24', 24], + ['number_25', 25], + ['number_26', 26], + ['number_27', 27], + ['number_28', 28], + ['number_29', 29], + ['ws_30', 30], + ['ws_31', 31], + ], + [ + [new InternalRuleDefReference(1), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([123]), + new InternalRuleDefReference(7), + new InternalRuleDefReference(11), + new InternalRuleDefChar([125]), + new InternalRuleDefReference(7), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(1), + new InternalRuleDefAlt(), + new InternalRuleDefReference(3), + new InternalRuleDefAlt(), + new InternalRuleDefReference(4), + new InternalRuleDefAlt(), + new InternalRuleDefReference(5), + new InternalRuleDefAlt(), + new InternalRuleDefReference(6), + new InternalRuleDefReference(7), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([91]), + new InternalRuleDefReference(7), + new InternalRuleDefReference(15), + new InternalRuleDefChar([93]), + new InternalRuleDefReference(7), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([34]), + new InternalRuleDefReference(18), + new InternalRuleDefChar([34]), + new InternalRuleDefReference(7), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(19), + new InternalRuleDefReference(25), + new InternalRuleDefReference(29), + new InternalRuleDefReference(7), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([116]), + new InternalRuleDefChar([114]), + new InternalRuleDefChar([117]), + new InternalRuleDefChar([101]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([102]), + new InternalRuleDefChar([97]), + new InternalRuleDefChar([108]), + new InternalRuleDefChar([115]), + new InternalRuleDefChar([101]), + new InternalRuleDefAlt(), + new InternalRuleDefChar([110]), + new InternalRuleDefChar([117]), + new InternalRuleDefChar([108]), + new InternalRuleDefChar([108]), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(31), new InternalRuleDefEnd()], + [ + new InternalRuleDefReference(4), + new InternalRuleDefChar([58]), + new InternalRuleDefReference(7), + new InternalRuleDefReference(2), + new InternalRuleDefReference(10), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([44]), + new InternalRuleDefReference(7), + new InternalRuleDefReference(4), + new InternalRuleDefChar([58]), + new InternalRuleDefReference(7), + new InternalRuleDefReference(2), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(9), + new InternalRuleDefReference(10), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(8), new InternalRuleDefAlt(), new InternalRuleDefEnd()], + [new InternalRuleDefReference(2), new InternalRuleDefReference(14), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([44]), + new InternalRuleDefReference(7), + new InternalRuleDefReference(2), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(13), + new InternalRuleDefReference(14), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(12), new InternalRuleDefAlt(), new InternalRuleDefEnd()], + [ + new InternalRuleDefCharNot([34]), + new InternalRuleDefCharAlt(92), + new InternalRuleDefCharAlt(127), + new InternalRuleDefCharAlt(0), + new InternalRuleDefCharRngUpper(31), + new InternalRuleDefAlt(), + new InternalRuleDefChar([92]), + new InternalRuleDefReference(17), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([34]), + new InternalRuleDefCharAlt(92), + new InternalRuleDefCharAlt(47), + new InternalRuleDefCharAlt(98), + new InternalRuleDefCharAlt(102), + new InternalRuleDefCharAlt(110), + new InternalRuleDefCharAlt(114), + new InternalRuleDefCharAlt(116), + new InternalRuleDefAlt(), + new InternalRuleDefChar([117]), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(97), + new InternalRuleDefCharRngUpper(102), + new InternalRuleDefCharAlt(65), + new InternalRuleDefCharRngUpper(70), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(97), + new InternalRuleDefCharRngUpper(102), + new InternalRuleDefCharAlt(65), + new InternalRuleDefCharRngUpper(70), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(97), + new InternalRuleDefCharRngUpper(102), + new InternalRuleDefCharAlt(65), + new InternalRuleDefCharRngUpper(70), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefCharAlt(97), + new InternalRuleDefCharRngUpper(102), + new InternalRuleDefCharAlt(65), + new InternalRuleDefCharRngUpper(70), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(16), + new InternalRuleDefReference(18), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(20), new InternalRuleDefReference(21), new InternalRuleDefEnd()], + [new InternalRuleDefChar([45]), new InternalRuleDefAlt(), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefAlt(), + new InternalRuleDefChar([49]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefReference(22), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefReference(22), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefChar([46]), new InternalRuleDefReference(24), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefReference(24), + new InternalRuleDefAlt(), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(23), new InternalRuleDefAlt(), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([101]), + new InternalRuleDefCharAlt(69), + new InternalRuleDefReference(27), + new InternalRuleDefReference(28), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([45]), + new InternalRuleDefCharAlt(43), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefReference(28), + new InternalRuleDefAlt(), + new InternalRuleDefChar([48]), + new InternalRuleDefCharRngUpper(57), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(26), new InternalRuleDefAlt(), new InternalRuleDefEnd()], + [ + new InternalRuleDefChar([32]), + new InternalRuleDefCharAlt(9), + new InternalRuleDefCharAlt(10), + new InternalRuleDefReference(7), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefReference(30), new InternalRuleDefAlt(), new InternalRuleDefEnd()], + ], + ], + ], + [ + 'japanese', + ` + # A probably incorrect grammar for Japanese + root ::= jp-char+ ([ \\t\\n] jp-char+)* + jp-char ::= hiragana | katakana | punctuation | cjk + hiragana ::= [ぁ-ゟ] + katakana ::= [ァ-ヿ] + punctuation ::= [、-〾] + cjk ::= [一-鿿] + `, + [ + [ + ['root', 0], + ['jp-char', 1], + ['root_2', 2], + ['root_3', 3], + ['root_4', 4], + ['root_5', 5], + ['hiragana', 6], + ['katakana', 7], + ['punctuation', 8], + ['cjk', 9], + ], + [ + [new InternalRuleDefReference(2), new InternalRuleDefReference(5), new InternalRuleDefEnd()], + [ + new InternalRuleDefReference(6), + new InternalRuleDefAlt(), + new InternalRuleDefReference(7), + new InternalRuleDefAlt(), + new InternalRuleDefReference(8), + new InternalRuleDefAlt(), + new InternalRuleDefReference(9), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(1), + new InternalRuleDefReference(2), + new InternalRuleDefAlt(), + new InternalRuleDefReference(1), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefChar([32]), + new InternalRuleDefCharAlt(9), + new InternalRuleDefCharAlt(10), + new InternalRuleDefReference(4), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(1), + new InternalRuleDefReference(4), + new InternalRuleDefAlt(), + new InternalRuleDefReference(1), + new InternalRuleDefEnd(), + ], + [ + new InternalRuleDefReference(3), + new InternalRuleDefReference(5), + new InternalRuleDefAlt(), + new InternalRuleDefEnd(), + ], + [new InternalRuleDefChar([12353]), new InternalRuleDefCharRngUpper(12447), new InternalRuleDefEnd()], + [new InternalRuleDefChar([12449]), new InternalRuleDefCharRngUpper(12543), new InternalRuleDefEnd()], + [new InternalRuleDefChar([12289]), new InternalRuleDefCharRngUpper(12350), new InternalRuleDefEnd()], + [new InternalRuleDefChar([19968]), new InternalRuleDefCharRngUpper(40959), new InternalRuleDefEnd()], + ], + ], + ], +]; + +test.each(testCases)('grammar parser: %s', (_key, grammar, expected) => { + const [symbolIdsExpected, rulesExpected] = expected; + const parsedGrammar = new RulesBuilder(grammar.replaceAll('\\n', '\n')); + expect(parsedGrammar.rules).toEqual(rulesExpected); + expect([...parsedGrammar.symbolIds.items()]).toEqual(symbolIdsExpected); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/rules-builder.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/rules-builder.ts new file mode 100644 index 0000000000000000000000000000000000000000..c485187fd211f1318ef7912e6ac7da48805a33d6 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/rules-builder.ts @@ -0,0 +1,263 @@ +import { getChars } from '../utils/code-points.ts'; +import { GrammarParseError } from '../utils/errors/index.ts'; +import { isSpace } from './is-space.ts'; +import { isWordChar } from './is-word-char.ts'; +import { parseChar } from './parse-char.ts'; +import { parseName } from './parse-name.ts'; +import { parseSpace } from './parse-space.ts'; +import { SymbolIds } from './symbol-ids.ts'; +import { + type InternalRuleDef, + InternalRuleDefAlt, + InternalRuleDefChar, + InternalRuleDefCharAlt, + InternalRuleDefCharNot, + InternalRuleDefCharRngUpper, + InternalRuleDefEnd, + InternalRuleDefReference, +} from './types.ts'; + +type InternalRuleDefClass = new (...args: never[]) => InternalRuleDef; + +// declared locally so that type-checking depends on neither the DOM nor the node typings +declare const performance: { now(): number }; + +const perfCounter = (): number => performance.now() / 1000; + +export const getOutElements = (typeOfRule: InternalRuleDefClass, startcharValue: number): InternalRuleDef => { + if (typeOfRule === InternalRuleDefChar) { + return new InternalRuleDefChar([startcharValue]); + } + if (typeOfRule === InternalRuleDefCharNot) { + return new InternalRuleDefCharNot([startcharValue]); + } + if (typeOfRule === InternalRuleDefCharRngUpper) { + return new InternalRuleDefCharRngUpper(startcharValue); + } + if (typeOfRule === InternalRuleDefAlt) { + return new InternalRuleDefAlt(); + } + if (typeOfRule === InternalRuleDefEnd) { + return new InternalRuleDefEnd(); + } + if (typeOfRule === InternalRuleDefCharAlt) { + return new InternalRuleDefCharAlt(startcharValue); + } + throw new Error(`Invalid type: ${typeof typeOfRule === 'function' ? typeOfRule.name : typeOfRule}`); +}; + +export class RulesBuilder { + pos: number; + symbolIds: SymbolIds; + rules: InternalRuleDef[][]; + src: string; + start: number; + timeLimit: number; + + // the time limit is measured in seconds + constructor(src: string, limit = 1000) { + this.pos = 0; + this.symbolIds = new SymbolIds(); + this.rules = []; + this.src = src; + this.start = perfCounter(); + this.timeLimit = limit; + this.parse(src); + } + + parse(src: string): void { + const chars = getChars(src); + this.pos = parseSpace(src, 0, true); + while (this.pos < chars.length) { + this.parseRule(src); + } + + // Validate the state to ensure that all rules are defined + for (const rule of this.rules) { + for (const elem of rule) { + if (elem instanceof InternalRuleDefReference) { + const ruleExists = elem.value < this.rules.length && this.rules[elem.value].length > 0; + if (!ruleExists) { + const missingRuleName = this.symbolIds.reverseGet(elem.value); + let missingRulePos = this.symbolIds.getPos(missingRuleName); + + // Skip over the ::= and any whitespace + while ( + missingRulePos < chars.length && + (chars[missingRulePos] === ':' || chars[missingRulePos] === '=' || isSpace(chars[missingRulePos])) + ) { + missingRulePos += 1; + } + + throw new GrammarParseError(src, missingRulePos, `Undefined rule identifier "${missingRuleName}"`); + } + } + } + } + } + + parseRule(src: string): void { + const chars = getChars(src); + const name = parseName(src, this.pos); + this.pos = parseSpace(src, this.pos + name.length, false); + const ruleId = this.getSymbolId(name, name.length); + + this.pos = parseSpace(src, this.pos, true); + if ( + !( + this.pos + 2 < chars.length && // Ensure the position + 2 is within bounds + chars[this.pos] === ':' && + chars[this.pos + 1] === ':' && + chars[this.pos + 2] === '=' + ) + ) { + throw new GrammarParseError(src, this.pos, `Expecting ::= at ${this.pos}`); + } + this.pos += 3; + this.pos = parseSpace(src, this.pos, true); + + this.parseAlternates(name, ruleId); + + // Check if this.pos is within the bounds of src before checking for a carriage return + if (this.pos < chars.length && chars[this.pos] === '\r') { + // the reference reads the character after the carriage return without checking that there is + // one, and so fails on a grammar that ends in a carriage return + if (this.pos + 1 >= chars.length) { + throw new RangeError('string index out of range'); + } + this.pos += chars[this.pos + 1] === '\n' ? 2 : 1; + } else if (this.pos < chars.length && chars[this.pos] === '\n') { + this.pos += 1; + } else if (this.pos < chars.length && chars[this.pos]) { + throw new GrammarParseError(src, this.pos, `Expecting newline or end at ${this.pos}`); + } + this.pos = parseSpace(src, this.pos, true); + } + + getSymbolId(src: string, length: number): number { + const nextId = this.symbolIds.size; + const key = Array.from(src).slice(0, length).join(''); + if (!this.symbolIds.has(key)) { + this.symbolIds.set(key, nextId, this.pos); + } + return this.symbolIds.get(key) as number; + } + + generateSymbolId(baseName: string): number { + const nextId = this.symbolIds.size; + this.symbolIds.set(`${baseName}_${nextId}`, nextId, this.pos); + return nextId; + } + + addRule(ruleId: number, rule: InternalRuleDef[]): void { + while (this.rules.length <= ruleId) { + this.rules.push([]); + } + this.rules[ruleId] = rule; + } + + checkDuration(): void { + if (perfCounter() - this.start > this.timeLimit) { + throw new GrammarParseError(this.src, this.pos, `Duration of ${this.timeLimit} exceeded`); + } + } + + parseSequence(ruleName: string, outElements: InternalRuleDef[], depth = 0): void { + const isNested = depth !== 0; + const src = this.src; + const chars = getChars(src); + let lastSymStart = outElements.length; + + while (this.pos < chars.length) { + if (chars[this.pos] === '"') { + this.pos += 1; + lastSymStart = outElements.length; + while (chars[this.pos] !== '"') { + this.checkDuration(); + const [value, incPos] = parseChar(src, this.pos); + outElements.push(new InternalRuleDefChar([value])); + this.pos += incPos; + } + this.pos = parseSpace(src, this.pos + 1, isNested); + } else if (chars[this.pos] === '[') { + this.pos += 1; + let startType: InternalRuleDefClass = InternalRuleDefChar; + if (chars[this.pos] === '^') { + this.pos += 1; + startType = InternalRuleDefCharNot; + } + lastSymStart = outElements.length; + while (chars[this.pos] !== ']') { + this.checkDuration(); + const type: InternalRuleDefClass = lastSymStart < outElements.length ? InternalRuleDefCharAlt : startType; + const [startcharValue, incPos] = parseChar(src, this.pos); + this.pos += incPos; + outElements.push(getOutElements(type, startcharValue)); + + if (chars[this.pos] === '-' && chars[this.pos + 1] !== ']') { + this.pos += 1; + const [endcharValue, endcharIncPos] = parseChar(src, this.pos); + outElements.push(new InternalRuleDefCharRngUpper(endcharValue)); + this.pos += endcharIncPos; + } + } + this.pos = parseSpace(src, this.pos + 1, isNested); + } else if (isWordChar(chars[this.pos])) { + const name = parseName(src, this.pos); + const refRuleId = this.getSymbolId(name, name.length); + this.pos += name.length; + this.pos = parseSpace(src, this.pos, isNested); + + lastSymStart = outElements.length; + outElements.push(new InternalRuleDefReference(refRuleId)); + } else if (chars[this.pos] === '(') { + this.pos = parseSpace(src, this.pos + 1, true); + const subRuleId = this.generateSymbolId(ruleName); + this.parseAlternates(ruleName, subRuleId, depth + 1); + lastSymStart = outElements.length; + outElements.push(new InternalRuleDefReference(subRuleId)); + if (chars[this.pos] !== ')') { + throw new GrammarParseError(src, this.pos, `Expecting ')' at ${this.pos}`); + } + this.pos = parseSpace(src, this.pos + 1, isNested); + } else if ('*+?'.includes(chars[this.pos])) { + if (lastSymStart === outElements.length) { + throw new GrammarParseError(src, this.pos, `Expecting preceding item to */+/? at ${this.pos}`); + } + const subRuleId = this.generateSymbolId(ruleName); + const subRule = outElements.slice(lastSymStart); + if ('*+'.includes(chars[this.pos])) { + subRule.push(new InternalRuleDefReference(subRuleId)); + } + subRule.push(new InternalRuleDefAlt()); + if (chars[this.pos] === '+') { + for (const elem of outElements.slice(lastSymStart)) { + subRule.push(elem); + } + } + subRule.push(new InternalRuleDefEnd()); + this.addRule(subRuleId, subRule); + outElements.splice(lastSymStart, outElements.length - lastSymStart, new InternalRuleDefReference(subRuleId)); + this.pos = parseSpace(src, this.pos + 1, isNested); + } else { + break; + } + } + } + + parseAlternates(ruleName: string, ruleId: number, depth = 0): void { + const src = this.src; + const chars = getChars(src); + const rule: InternalRuleDef[] = []; + this.parseSequence(ruleName, rule, depth); + // Ensure that this.pos is within bounds before checking chars[this.pos] + while (this.pos < chars.length && chars[this.pos] === '|') { + this.checkDuration(); + rule.push(new InternalRuleDefAlt()); + this.pos = parseSpace(src, this.pos + 1, true); + this.parseSequence(ruleName, rule, depth); + } + rule.push(new InternalRuleDefEnd()); + this.addRule(ruleId, rule); + } +} diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/symbol-ids.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/symbol-ids.ts new file mode 100644 index 0000000000000000000000000000000000000000..a1b9eeec570a09c92cf0120ad63c6eaaeaaefd0f --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/symbol-ids.ts @@ -0,0 +1,47 @@ +export class SymbolIds implements Iterable<[string, number]> { + #map = new Map(); + #pos = new Map(); + #reverseMap = new Map(); + + items(): IterableIterator<[string, number]> { + return this.#map.entries(); + } + + [Symbol.iterator](): IterableIterator<[string, number]> { + return this.#map.entries(); + } + + get size(): number { + return this.#map.size; + } + + get(key: string): number | undefined { + return this.#map.get(key); + } + + set(key: string, value: number, pos: number): void { + this.#map.set(key, value); + this.#reverseMap.set(value, key); + this.#pos.set(key, pos); + } + + has(key: string): boolean { + return this.#map.has(key); + } + + reverseGet(key: number): string { + const val = this.#reverseMap.get(key); + if (val === undefined) { + throw new Error(`SymbolIds does not contain value: ${key}`); + } + return val; + } + + getPos(key: string): number { + const val = this.#pos.get(key); + if (val === undefined) { + throw new Error(`SymbolIds does not contain key: ${key}`); + } + return val; + } +} diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/types.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..760dda6c3a327311bb91c87b41163f7789df9fc7 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/rules-builder/types.ts @@ -0,0 +1,99 @@ +export const InternalRuleType = { + CHAR: 'CHAR', + CHAR_RNG_UPPER: 'CHAR_RNG_UPPER', + RULE_REF: 'RULE_REF', + ALT: 'ALT', + END: 'END', + CHAR_NOT: 'CHAR_NOT', + CHAR_ALT: 'CHAR_ALT', +} as const; +export type InternalRuleType = (typeof InternalRuleType)[keyof typeof InternalRuleType]; + +export class InternalRuleDefWithNumericValue { + value: number; + + constructor(value: number) { + this.value = value; + } +} + +export class InternalBase {} + +export class InternalBaseWithValue { + value: T; + + constructor(value: T) { + this.value = value; + } +} + +export class InternalBaseWithInt extends InternalBaseWithValue {} + +export class InternalBaseWithListOfInts extends InternalBaseWithValue { + constructor(value: number[] = []) { + super(value.slice()); + } +} + +// Each rule definition carries its type as a plain property, so that definitions of different +// classes are never structurally equal (e.g. with `toEqual`), even when their values match. +export class InternalRuleDefChar extends InternalBaseWithListOfInts { + readonly type = InternalRuleType.CHAR; +} + +export class InternalRuleDefCharAlt extends InternalBaseWithInt { + readonly type = InternalRuleType.CHAR_ALT; +} + +export class InternalRuleDefAlt extends InternalBase { + readonly type = InternalRuleType.ALT; +} + +export class InternalRuleDefCharNot extends InternalBaseWithListOfInts { + readonly type = InternalRuleType.CHAR_NOT; +} + +export class InternalRuleDefCharRngUpper extends InternalBaseWithInt { + readonly type = InternalRuleType.CHAR_RNG_UPPER; +} + +export class InternalRuleDefReference extends InternalBaseWithInt { + readonly type = InternalRuleType.RULE_REF; +} + +export class InternalRuleDefEnd extends InternalBase { + readonly type = InternalRuleType.END; +} + +export class InternalRuleDefWithoutValue extends InternalBase {} + +export type InternalRuleDef = + | InternalRuleDefChar + | InternalRuleDefEnd + | InternalRuleDefReference + | InternalRuleDefCharNot + | InternalRuleDefWithNumericValue + | InternalRuleDefWithoutValue + | InternalRuleDefAlt + | InternalRuleDefCharRngUpper + | InternalRuleDefCharAlt; + +export type InternalRuleDefCharOrAltChar = InternalRuleDefChar | InternalRuleDefCharAlt; + +export const isRuleDefAlt = (rule?: unknown): rule is InternalRuleDefAlt => rule instanceof InternalRuleDefAlt; + +export const isRuleDefRef = (rule?: unknown): rule is InternalRuleDefReference => + rule instanceof InternalRuleDefReference; + +export const isRuleDefEnd = (rule?: unknown): rule is InternalRuleDefEnd => rule instanceof InternalRuleDefEnd; + +export const isRuleDefChar = (rule?: unknown): rule is InternalRuleDefChar => rule instanceof InternalRuleDefChar; + +export const isRuleDefCharNot = (rule?: unknown): rule is InternalRuleDefCharNot => + rule instanceof InternalRuleDefCharNot; + +export const isRuleDefCharAlt = (rule?: unknown): rule is InternalRuleDefCharAlt => + rule instanceof InternalRuleDefCharAlt; + +export const isRuleDefCharRngUpper = (rule?: unknown): rule is InternalRuleDefCharRngUpper => + rule instanceof InternalRuleDefCharRngUpper; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/code-points.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/code-points.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f6d23e133677f5152f4e1ff95fc970e223be4b6 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/code-points.ts @@ -0,0 +1,23 @@ +// Python strings are sequences of code points, whereas JavaScript strings are sequences of +// UTF-16 code units. Positions and lengths in this library are measured in code points, so +// strings are split with the helpers below before they are indexed. + +let cachedSrc: string | undefined; +let cachedChars: readonly string[] = []; + +// The most recently split string is cached, as the grammar parser repeatedly indexes into the same source. +export const getChars = (src: string): readonly string[] => { + if (src !== cachedSrc) { + cachedChars = Array.from(src); + cachedSrc = src; + } + return cachedChars; +}; + +export const getLength = (src: string): number => { + let length = 0; + for (const _ of src) { + length += 1; + } + return length; +}; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/build-error-position.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/build-error-position.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..40db3ea08589ae61f23b221c3a59146c7d4fdc0d --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/build-error-position.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it, test } from 'vitest'; +import { buildErrorPosition } from './build-error-position.ts'; + +describe('buildErrorPosition', () => { + it.each<[string, number, [string, string]]>([ + ['root ::= "foo"', 1, ['root ::= "foo"', ' ^']], + ['root ::= "foo"', 5, ['root ::= "foo"', ' ^']], + // multi line grammars with pos on first line + ['aa\\nbb', 1, ['aa', ' ^']], + // multi line grammars with pos on second line, first character + ['aa\\nbb', 2, ['aa\\nbb', '^']], + // multi line grammars with pos on second line, second character + ['aa\\nbb', 2 + 1, ['aa\\nbb', ' ^']], + // multi line grammars beyond error with pos on second line + ['aa\\nbb\\ncc', 2 + 1, ['aa\\nbb', ' ^']], + // multi line grammars beyond error with pos on third line, first char + ['aa\\nbb\\ncc', 2 + 2 + 0, ['aa\\nbb\\ncc', '^']], + // multi line grammars beyond error with pos on third line, second char + ['aa\\nbb\\ncc', 2 + 2 + 1, ['aa\\nbb\\ncc', ' ^']], + // multi line grammars beyond error with pos on fourth line, first char + ['aa\\nbb\\ncc\\ndd', 2 + 2 + 2 + 0, ['bb\\ncc\\ndd', '^']], + // multi line grammars beyond error with pos on fifth line, second char + ['aa\\nbb\\ncc\\ndd\\nee', 2 + 2 + 2 + 2 + 1, ['cc\\ndd\\nee', ' ^']], + ])('correctly shows position for single line grammars (%j, %i)', (grammar, pos, expected) => { + const [grammarOut, posOut] = expected; + const result = buildErrorPosition(grammar.split('\\n').join('\n'), pos); + expect(result).toEqual([...grammarOut.split('\\n'), posOut]); + }); + + test('it renders a message for empty input', () => { + expect(buildErrorPosition('', 0)).toEqual(['No input provided']); + }); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/build-error-position.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/build-error-position.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e8a70435259685e26c84d0a135d9c4a17f9ad56 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/build-error-position.ts @@ -0,0 +1,31 @@ +import { getLength } from '../code-points.ts'; + +export const MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW = 3; + +export const buildErrorPosition = (src: string, pos: number): string[] => { + if (src === '') { + return ['No input provided']; + } + const lines = src.split('\n'); + const srcLength = getLength(src); + + const getLine = (idx: number): string => { + if (idx >= lines.length) { + throw new RangeError('list index out of range'); + } + return lines[idx]; + }; + + let lineIdx = 0; + while (getLine(lineIdx) && pos > getLength(lines[lineIdx]) - 1 && pos < srcLength) { + pos -= getLength(lines[lineIdx]); + lineIdx += 1; + } + + const linesToShow: string[] = []; + for (let i = Math.max(0, lineIdx - (MAXIMUM_NUMBER_OF_ERROR_LINES_TO_SHOW - 1)); i <= lineIdx; i++) { + linesToShow.push(lines[i]); + } + + return [...linesToShow, ' '.repeat(Math.max(0, pos)) + '^']; +}; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/get-input-as-string.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/get-input-as-string.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd59b85bf7454ec496502eb2660641c8a1bf9fb2 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/get-input-as-string.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest'; +import { getInputAsString } from './get-input-as-string.ts'; +import type { ValidInput } from './types.ts'; + +describe('getInputAsString', () => { + it.each<[ValidInput, string]>([ + ['hello', 'hello'], + [[104, 101, 108, 108, 111], 'hello'], + [104, 'h'], + [0x1f600, '\u{1F600}'], + [[0x1f600, 0x1f601], '\u{1F600}\u{1F601}'], + ])('correctly converts strings to strings (%j)', (input, expected) => { + expect(getInputAsString(input)).toEqual(expected); + }); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/get-input-as-string.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/get-input-as-string.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b465409b156b8c26f2dcc2212a052dae6726527 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/get-input-as-string.ts @@ -0,0 +1,11 @@ +import type { ValidInput } from './types.ts'; + +export const getInputAsString = (src: ValidInput): string => { + if (typeof src === 'string') { + return src; + } + if (typeof src === 'number') { + return String.fromCodePoint(src); + } + return src.map((cp) => String.fromCodePoint(cp)).join(''); +}; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/grammar-parse-error.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/grammar-parse-error.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4dbc56fe23240b15891757709fb941c51dd66a6a --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/grammar-parse-error.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, test } from 'vitest'; +import { GRAMMAR_PARSER_ERROR_HEADER_MESSAGE, GrammarParseError } from './grammar-parse-error.ts'; + +describe('GrammarParseError', () => { + test('it renders a message', () => { + const grammar = 'aa\\nbb\\ncc\\ndd\\nee'; + const pos = 5; + const reason = 'reason'; + const err = new GrammarParseError(grammar.split('\\n').join('\n'), pos, reason); + expect(err.message).toEqual([GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(reason), '', 'aa', 'bb', 'cc', ' ^'].join('\n')); + }); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/grammar-parse-error.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/grammar-parse-error.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0ff9cbdc21936c5ae2911c1ab3fcbed74fb8220 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/grammar-parse-error.ts @@ -0,0 +1,17 @@ +import { buildErrorPosition } from './build-error-position.ts'; + +export const GRAMMAR_PARSER_ERROR_HEADER_MESSAGE = (reason: string): string => `Failed to parse grammar: ${reason}`; + +export class GrammarParseError extends Error { + grammar: string; + pos: number; + reason: string; + + constructor(grammar: string, pos: number, reason: string) { + super([GRAMMAR_PARSER_ERROR_HEADER_MESSAGE(reason), '', ...buildErrorPosition(grammar, pos)].join('\n')); + this.name = 'GrammarParseError'; + this.grammar = grammar; + this.pos = pos; + this.reason = reason; + } +} diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/index.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..33a4f337132416dbc9544308b682d159353f471e --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/index.ts @@ -0,0 +1,2 @@ +export { GrammarParseError } from './grammar-parse-error.ts'; +export { InputParseError } from './input-parse-error.ts'; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/input-parse-error.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/input-parse-error.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..96beb51c43caccbb7ac869bd5f2ce187db64eb1e --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/input-parse-error.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, test } from 'vitest'; +import { INPUT_PARSER_ERROR_HEADER_MESSAGE, InputParseError } from './input-parse-error.ts'; + +describe('InputParseError', () => { + test('it renders a message', () => { + const input = 'some input'; + const pos = 1; + const err = new InputParseError(input, pos); + expect(err.message).toEqual([INPUT_PARSER_ERROR_HEADER_MESSAGE, '', input, ' ^'].join('\n')); + }); + + test('it renders a message for code point', () => { + const pos = 0; + const err = new InputParseError('a', pos); + expect(err.message).toEqual([INPUT_PARSER_ERROR_HEADER_MESSAGE, '', 'a', '^'].join('\n')); + }); + + test('it renders a message for code points', () => { + const pos = 2; + const err = new InputParseError('abcd', pos); + expect(err.message).toEqual([INPUT_PARSER_ERROR_HEADER_MESSAGE, '', 'abcd', ' ^'].join('\n')); + }); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/input-parse-error.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/input-parse-error.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4648bfee65bf88b8e6758c440cb9004dd7955a7 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/input-parse-error.ts @@ -0,0 +1,41 @@ +import { getLength } from '../code-points.ts'; +import { buildErrorPosition } from './build-error-position.ts'; +import { getInputAsString } from './get-input-as-string.ts'; +import type { ValidInput } from './types.ts'; + +export const INPUT_PARSER_ERROR_HEADER_MESSAGE = 'Failed to parse input string:'; + +export class InputParseError extends Error { + mostRecentInput: ValidInput; + pos: number; + previousInput: ValidInput; + + constructor(mostRecentInput: ValidInput, pos: number, previousInput: ValidInput = '') { + super( + [ + INPUT_PARSER_ERROR_HEADER_MESSAGE, + '', + ...buildErrorPosition( + `${getInputAsString(previousInput)}${getInputAsString(mostRecentInput)}`, + pos + getLength(getInputAsString(previousInput)), + ), + ].join('\n'), + ); + this.name = 'InputParseError'; + this.mostRecentInput = mostRecentInput; + this.pos = pos; + this.previousInput = previousInput; + } + + get src(): string { + return `${getInputAsString(this.previousInput)}${getInputAsString(this.mostRecentInput)}`; + } + + get errorForMostRecentInput(): string { + return [ + INPUT_PARSER_ERROR_HEADER_MESSAGE, + '', + ...buildErrorPosition(getInputAsString(this.mostRecentInput), this.pos), + ].join('\n'); + } +} diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/types.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce9c435fb72d3fd1561d94771da384a990714740 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/errors/types.ts @@ -0,0 +1 @@ +export type ValidInput = string | number | number[]; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/is-point-in-range.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/is-point-in-range.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc6342738f348d27238c7d725b81dc184d2dabc5 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/is-point-in-range.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest'; +import type { Range } from '../grammar-graph/types.ts'; +import { isPointInRange } from './is-point-in-range.ts'; + +describe('isPointInRange', () => { + it.each<[number, Range, boolean]>([ + [96, [97, 122], false], + [97, [97, 122], true], + [98, [97, 122], true], + [122, [97, 122], true], + [123, [97, 122], false], + ])('checks if point %i is in range %j: %s', (point, range, expectation) => { + expect(isPointInRange(point, range)).toEqual(expectation); + }); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/is-point-in-range.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/is-point-in-range.ts new file mode 100644 index 0000000000000000000000000000000000000000..a44be1df561a853865cffe200f80fbd684c15ea8 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/is-point-in-range.ts @@ -0,0 +1,8 @@ +import type { Range } from '../grammar-graph/types.ts'; + +export const isPointInRange = (point: number, givenRange: Range): boolean => { + if (!Number.isInteger(point)) { + throw new Error('point must be an integer'); + } + return point >= givenRange[0] && point <= givenRange[1]; +}; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/validate-non-empty.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/validate-non-empty.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf28a1fa2d8c1e063837e3089007d2fc193581bf --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/src/utils/validate-non-empty.ts @@ -0,0 +1,6 @@ +export const validateNonEmpty = (value: number[]): number[] => { + if (!value || value.length === 0) { + throw new Error('Value cannot be empty.'); + } + return value; +}; diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/iteration/iteration-with-additional-strings.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/iteration/iteration-with-additional-strings.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a810253c596afa3103464ad0695705fe591e29e0 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/iteration/iteration-with-additional-strings.test.ts @@ -0,0 +1,662 @@ +import { describe, expect, test } from 'vitest'; +import { + GBNF, + InputParseError, + type Range, + type ResolvedRule, + RuleChar, + RuleCharExclude, + RuleEnd, +} from '../../../src/index.ts'; + +const ord = (char: string): number => char.codePointAt(0) as number; + +interface ExpectedRule { + type: string; + value?: (number | Range)[]; +} + +const byJson = (a: ResolvedRule, b: ResolvedRule): number => { + const [keyA, keyB] = [JSON.stringify(a), JSON.stringify(b)]; + if (keyA === keyB) { + return 0; + } + return keyA < keyB ? -1 : 1; +}; + +// runs the callback, and returns the error it is expected to throw +const raises = (expected: new (...args: never[]) => T, callback: () => unknown): T => { + let error: unknown; + try { + callback(); + } catch (err) { + error = err; + } + expect(error).toBeInstanceOf(expected); + return error as T; +}; + +describe('iteration', () => { + test.each<[string, string, string]>([ + // single char rule + [ + // single char rule + 'root ::= "foo"', + // single char rule + 'f', + // single char rule + '1', + ], + ['root ::= "foo"', 'f', 'b'], + ['root ::= "foo"', 'f', 'o1'], + ['root ::= "foo"', 'f', 'ooo'], + ['root ::= "foo"', 'f', 'ooooooo'], + // two char rules + [ + // two char rules + 'root ::= "foo" | "bar"', + // two char rules + 'f', + // two char rules + '1', + ], + ['root ::= "foo" | "bar"', 'b', '1'], + ['root ::= "foo" | "bar"', 'f', 'o1'], + ['root ::= "foo" | "bar"', 'b', 'a1'], + ['root ::= "foo" | "bar"', 'f', 'ooo'], + ['root ::= "foo" | "bar"', 'b', 'arrr'], + // three char rules + [ + // three char rules + 'root ::= "foo" | "bar" | "baz"', + // three char rules + 'f', + // three char rules + '1', + ], + ['root ::= "foo" | "bar" | "baz"', 'f', 'z'], + ['root ::= "foo" | "bar" | "baz"', 'b', 'b1'], + ['root ::= "foo" | "bar" | "baz"', 'f', 'o1'], + ['root ::= "foo" | "bar" | "baz"', 'b', 'al'], + ['root ::= "foo" | "bar" | "baz"', 'f', 'ooo'], + ['root ::= "foo" | "bar" | "baz"', 'b', 'azrr'], + // expressions + [ + `root ::= foo +foo ::="foo"`, + 'f', + '1', + ], + [ + `root ::= foo +foo ::="foo"`, + 'f', + 'b', + ], + [ + `root ::= foo +foo ::="foo"`, + 'f', + 'o1', + ], + [ + `root ::= foo +foo ::="foo"`, + 'f', + 'ooo', + ], + // expression and a char rule + [ + `root::=foo|"bar" +foo::="foo"`, + 'f', + '1', + ], + [ + `root::=foo|"bar" +foo::="foo"`, + 'f', + 'z', + ], + [ + `root::=foo|"bar" +foo::="foo"`, + 'b', + 'b1', + ], + [ + `root::=foo|"bar" +foo::="foo"`, + 'f', + 'o1', + ], + [ + `root::=foo|"bar" +foo::="foo"`, + 'f', + 'ooo', + ], + [ + `root::=foo|"bar" +foo::="foo"`, + 'b', + 'arr', + ], + // two expressions + [ + `root::= foo | bar + foo::="foo" + bar::="bar"`, + 'f', + '1', + ], + [ + `root::= foo | bar + foo::="foo" + bar::="bar"`, + 'f', + 'z', + ], + [ + `root::= foo | bar + foo::="foo" + bar::="bar"`, + 'b', + '1', + ], + [ + `root::= foo | bar + foo::="foo" + bar::="bar"`, + 'f', + 'o1', + ], + [ + `root::= foo | bar + foo::="foo" + bar::="bar"`, + 'f', + 'ooo', + ], + [ + `root::= foo | bar + foo::="foo" + bar::="bar"`, + 'b', + 'arr', + ], + // nested expressions + [ + `root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'f', + '1', + ], + [ + `root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'f', + 'z', + ], + [ + `root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'b', + '1', + ], + [ + `root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'f', + 'o1', + ], + [ + `root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'f', + 'ooo', + ], + [ + `root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'b', + 'arr', + ], + [ + `root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'b', + 'azr', + ], + // ranges + [ + // ranges + 'root ::= [a-z]', + // ranges + 'a', + // ranges + 'A', + ], + ['root ::= [a-z]', 'a', '0'], + ['root ::= [a-z]', 'a', 'az'], + // range with ? modifier + [ + // range with ? modifier + 'root ::= [a-z]?', + // range with ? modifier + 'a', + // range with ? modifier + 'A', + ], + ['root ::= [a-z]?', 'a', '0'], + ['root ::= [a-z]?', 'a', 'az'], + // range with + modifier + [ + // range with + modifier + 'root ::= [a-z]+', + // range with + modifier + 'a', + // range with + modifier + 'A', + ], + ['root ::= [a-z]+', 'a', '0'], + ['root ::= [a-z]+', 'a', 'z0'], + // range with * modifier + [ + // range with * modifier + 'root ::= [a-z]*', + // range with * modifier + 'a', + // range with * modifier + 'A', + ], + ['root ::= [a-z]*', 'a', '0'], + ['root ::= [a-z]*', 'a', 'z0'], + ])( + 'it raises if encountering grammar %j with starting %j and additional %j [%#]', + (grammar, starting, additional) => { + const state = GBNF(grammar, starting); + expect(() => state.add(additional)).toThrow(InputParseError); + }, + ); + + test.each<[string, string, string, ExpectedRule[]]>([ + ['root ::= "foo"', '', 'f', [{ type: 'char', value: [ord('o')] }]], + ['root ::= "foo"', 'f', 'o', [{ type: 'char', value: [ord('o')] }]], + ['root ::= "foo"', 'fo', 'o', [{ type: 'end' }]], + // two char rules + ['root ::= "foo" | "bar" ', '', 'f', [{ type: 'char', value: [ord('o')] }]], + ['root ::= "foo" | "bar" ', 'f', 'o', [{ type: 'char', value: [ord('o')] }]], + ['root ::= "foo" | "bar" ', 'fo', 'o', [{ type: 'end' }]], + ['root ::= "foo" | "bar" ', '', 'b', [{ type: 'char', value: [ord('a')] }]], + ['root ::= "foo" | "bar" ', 'b', 'a', [{ type: 'char', value: [ord('r')] }]], + ['root ::= "foo" | "bar" ', 'ba', 'r', [{ type: 'end' }]], + // three char rules + [ + 'root ::= "foo" | "bar" | "baz"', + 'b', + 'a', + [{ type: 'char', value: [ord('r')] }, { type: 'char', value: [ord('z')] }], + ], + // char not + ['root ::= [^f] "o"', 'g', 'o', [{ type: 'end' }]], + ['root ::= [^A-Z]', '', 'a', [{ type: 'end' }]], + ['root ::= [^A-Z0-9]', '', 'a', [{ type: 'end' }]], + ['root ::= [^A-Z0-9_-]', '', 'a', [{ type: 'end' }]], + // expressions + [ + `root ::= foo +foo ::= "foo"`, + '', + 'f', + [{ type: 'char', value: [ord('o')] }], + ], + [ + `root ::= foo +foo ::= "foo"`, + 'f', + 'o', + [{ type: 'char', value: [ord('o')] }], + ], + [ + `root ::= foo +foo ::= "foo"`, + 'fo', + 'o', + [{ type: 'end' }], + ], + // expression and a char rule + [ + `root ::= foo | "bar" +foo ::= "foo"`, + '', + 'f', + [{ type: 'char', value: [ord('o')] }], + ], + [ + `root ::= foo | "bar" +foo ::= "foo"`, + 'f', + 'o', + [{ type: 'char', value: [ord('o')] }], + ], + [ + `root ::= foo | "bar" +foo ::= "foo"`, + 'fo', + 'o', + [{ type: 'end' }], + ], + [ + `root ::= foo | "bar" +foo ::= "foo"`, + '', + 'b', + [{ type: 'char', value: [ord('a')] }], + ], + [ + `root ::= foo | "bar" +foo ::= "foo"`, + 'b', + 'a', + [{ type: 'char', value: [ord('r')] }], + ], + [ + `root ::= foo | "bar" +foo ::= "foo"`, + 'ba', + 'r', + [{ type: 'end' }], + ], + // two expressions + [ + `root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + '', + 'f', + [{ type: 'char', value: [ord('o')] }], + ], + [ + ` +root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + 'f', + 'o', + [{ type: 'char', value: [ord('o')] }], + ], + [ + ` +root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + 'fo', + 'o', + [{ type: 'end' }], + ], + [ + `root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + '', + 'b', + [{ type: 'char', value: [ord('a')] }], + ], + [ + `root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + 'b', + 'a', + [{ type: 'char', value: [ord('r')] }], + ], + [ + `root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + 'ba', + 'r', + [{ type: 'end' }], + ], + // nested expressions + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + '', + 'f', + [{ type: 'char', value: [ord('o')] }], + ], + [ + `root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'f', + 'o', + [{ type: 'char', value: [ord('o')] }], + ], + [ + `root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'fo', + 'o', + [{ type: 'end' }], + ], + [ + `root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + '', + 'b', + [{ type: 'char', value: [ord('a')] }], + ], + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'b', + 'a', + [{ type: 'char', value: [ord('r')] }, { type: 'char', value: [ord('z')] }], + ], + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'ba', + 'r', + [{ type: 'end' }], + ], + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'ba', + 'z', + [{ type: 'end' }], + ], + // ranges + ['root ::= [a-z]', '', 'a', [{ type: 'end' }]], + ['root ::= [a-z]', '', 'm', [{ type: 'end' }]], + ['root ::= [a-z]', '', 'z', [{ type: 'end' }]], + ['root ::= [a-zA-Z]', '', 'a', [{ type: 'end' }]], + ['root ::= [a-zA-Z]', '', 'Z', [{ type: 'end' }]], + ['root ::= [a-zA-Z0-9]', '', 'Z', [{ type: 'end' }]], + ['root ::= [a-zA-Z0-9]', '', '0', [{ type: 'end' }]], + ['root ::= [a-zA-Z0-9]', '', '9', [{ type: 'end' }]], + // range with ? modifier + ['root ::= [a-z]?', '', 'a', [{ type: 'end' }]], + ['root ::= [a-zA-Z]?', '', 'Z', [{ type: 'end' }]], + ['root ::= [a-zA-Z0-9]?', '', '0', [{ type: 'end' }]], + // range with + modifier + ['root ::= [a-z]+', '', 'a', [{ type: 'char', value: [[ord('a'), ord('z')]] }, { type: 'end' }]], + [ + 'root ::= [a-zA-Z]+', + '', + 'Z', + [{ type: 'char', value: [[ord('a'), ord('z')], [ord('A'), ord('Z')]] }, { type: 'end' }], + ], + [ + 'root ::= [a-zA-Z]+', + 'azA', + 'Z', + [{ type: 'char', value: [[ord('a'), ord('z')], [ord('A'), ord('Z')]] }, { type: 'end' }], + ], + // range with * modifier + ['root ::= [a-z]*', '', 'a', [{ type: 'char', value: [[ord('a'), ord('z')]] }, { type: 'end' }]], + [ + 'root ::= [a-zA-Z]+', + '', + 'Z', + [{ type: 'char', value: [[ord('a'), ord('z')], [ord('A'), ord('Z')]] }, { type: 'end' }], + ], + [ + 'root ::= [a-zA-Z]+', + 'acczABC', + 'Z', + [{ type: 'char', value: [[ord('a'), ord('z')], [ord('A'), ord('Z')]] }, { type: 'end' }], + ], + ['root ::= "foo" | "bar" | "baz" | "bazaar" | "barrington" ', 'baza', 'a', [{ type: 'char', value: [ord('r')] }]], + // char not with modifiers + [ + 'root ::= [^f]+ "o"', + 'aaa', + 'a', + [{ type: 'char_exclude', value: [ord('f')] }, { type: 'char', value: [ord('o')] }], + ], + ['root ::= [^A-Z]+', 'abc', 'd', [{ type: 'char_exclude', value: [[ord('A'), ord('Z')]] }, { type: 'end' }]], + [ + 'root ::= [^A-Z0-9]*', + 'abc', + 'd', + [{ type: 'char_exclude', value: [[ord('A'), ord('Z')], [ord('0'), ord('9')]] }, { type: 'end' }], + ], + [ + 'root ::= [^A-Z0-9_-]*', + 'abc', + 'd', + [ + { type: 'char_exclude', value: [[ord('A'), ord('Z')], [ord('0'), ord('9')], ord('_'), ord('-')] }, + { type: 'end' }, + ], + ], + ])( + 'it parses a grammar %j with starting %j and additional %j [%#]', + (grammar, starting, additional, expected) => { + const transformedExpectedDict = (e: ExpectedRule): ResolvedRule => { + if (e.type === 'char') { + return new RuleChar(e.value); + } else if (e.type === 'char_exclude') { + return new RuleCharExclude(e.value); + } else if (e.type === 'end') { + return new RuleEnd(); + } else { + throw new Error(`Unknown type found in expectation array: ${e.type}`); + } + }; + + let state = GBNF(grammar, starting); + state = state.add(additional); + expect([...state].sort(byJson)).toEqual(expected.map(transformedExpectedDict).sort(byJson)); + }, + ); + + test.each([false, true])( + 'it raises a particular error (error for most recent input: %s)', + (errorForMostRecentInput) => { + const grammar = 'root ::= "bar"'; + let state = GBNF(grammar); + state = state.add('b'); + state = state.add('a'); + const err = raises(InputParseError, () => state.add('z')); + const expectedError = new InputParseError('z', 0, 'ba'); + if (errorForMostRecentInput) { + expect(err.errorForMostRecentInput).toEqual(expectedError.errorForMostRecentInput); + } else { + expect(err.message).toEqual(expectedError.message); + } + }, + ); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/iteration/iteration-with-an-initial-string.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/iteration/iteration-with-an-initial-string.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8d6f3357dde76743fb543961c402cb936634484 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/iteration/iteration-with-an-initial-string.test.ts @@ -0,0 +1,517 @@ +import { describe, expect, test } from 'vitest'; +import { GBNF, type Range, type ResolvedRule, RuleChar, RuleCharExclude, RuleEnd } from '../../../src/index.ts'; + +const ord = (char: string): number => char.codePointAt(0) as number; + +interface ExpectedRule { + type: string; + value?: (number | Range)[]; +} + +const byJson = (a: ResolvedRule, b: ResolvedRule): number => { + const [keyA, keyB] = [JSON.stringify(a), JSON.stringify(b)]; + if (keyA === keyB) { + return 0; + } + return keyA < keyB ? -1 : 1; +}; + +describe('iteration', () => { + test.each<[string, string, ExpectedRule[]]>([ + // single char rule + ['root ::= "foo"', '', [{ type: 'char', value: [ord('f')] }]], + ['root ::= "foo"', 'f', [{ type: 'char', value: [ord('o')] }]], + ['root ::= "foo"', 'fo', [{ type: 'char', value: [ord('o')] }]], + ['root ::= "foo"', 'foo', [{ type: 'end' }]], + // two char rules + ['root ::= "foo" | "bar" ', '', [{ type: 'char', value: [ord('f')] }, { type: 'char', value: [ord('b')] }]], + ['root ::= "foo" | "bar" ', 'f', [{ type: 'char', value: [ord('o')] }]], + ['root ::= "foo" | "bar" ', 'fo', [{ type: 'char', value: [ord('o')] }]], + ['root ::= "foo" | "bar" ', 'foo', [{ type: 'end' }]], + ['root ::= "foo" | "bar" ', 'b', [{ type: 'char', value: [ord('a')] }]], + ['root ::= "foo" | "bar" ', 'ba', [{ type: 'char', value: [ord('r')] }]], + ['root ::= "foo" | "bar" ', 'bar', [{ type: 'end' }]], + // three char rules + [ + 'root ::= "foo" | "bar" | "baz"', + 'ba', + [{ type: 'char', value: [ord('r')] }, { type: 'char', value: [ord('z')] }], + ], + // chars that shadow built-in characters + ['root ::= "["', '[', [{ type: 'end' }]], + ['root ::= "]"', ']', [{ type: 'end' }]], + ['root ::= "[]"', '[]', [{ type: 'end' }]], + ['root ::= "{"', '{', [{ type: 'end' }]], + ['root ::= "}"', '}', [{ type: 'end' }]], + ['root ::= "{}"', '{}', [{ type: 'end' }]], + ['root ::= "[{}]"', '[{}]', [{ type: 'end' }]], + // ('root ::= "[{\"}]"', '[{"}]', [ + // { "type": 'end' }, + // ]), + // char not + ['root ::= [^f] "o"', '', [{ type: 'char_exclude', value: [ord('f')] }]], + ['root ::= [^f] "o"', 'a', [{ type: 'char', value: [ord('o')] }]], + ['root ::= [^A-Z]', '', [{ type: 'char_exclude', value: [[ord('A'), ord('Z')]] }]], + ['root ::= [^A-Z0-9]', '', [{ type: 'char_exclude', value: [[ord('A'), ord('Z')], [ord('0'), ord('9')]] }]], + [ + 'root ::= [^A-Z0-9_-]', + '', + [{ type: 'char_exclude', value: [[ord('A'), ord('Z')], [ord('0'), ord('9')], ord('_'), ord('-')] }], + ], + // expressions + [ + ` +root ::= foo +foo ::= "foo"`, + '', + [{ type: 'char', value: [ord('f')] }], + ], + [ + `root ::= foo +foo ::= "foo" +`, + 'f', + [{ type: 'char', value: [ord('o')] }], + ], + [ + ` +root ::= foo +foo ::= "foo" +`, + 'fo', + [{ type: 'char', value: [ord('o')] }], + ], + [ + `root ::= foo +foo ::= "foo"`, + 'foo', + [{ type: 'end' }], + ], + [ + `root ::= f +f ::= foo +foo ::= "foo"`, + '', + [{ type: 'char', value: [ord('f')] }], + ], + // expression and a char rule + [ + ` +root ::= foo | "bar" +foo ::= "foo" +`, + '', + [{ type: 'char', value: [ord('f')] }, { type: 'char', value: [ord('b')] }], + ], + [ + ` +root ::= foo | "bar" +foo ::= "foo"`, + 'f', + [{ type: 'char', value: [ord('o')] }], + ], + [ + `root ::= foo | "bar" +foo ::= "foo"`, + 'fo', + [{ type: 'char', value: [ord('o')] }], + ], + [ + `root ::= foo | "bar" +foo ::= "foo"`, + 'foo', + [{ type: 'end' }], + ], + [ + `root ::= foo | "bar" +foo ::= "foo"`, + 'b', + [{ type: 'char', value: [ord('a')] }], + ], + [ + `root ::= foo | "bar" +foo ::= "foo"`, + 'ba', + [{ type: 'char', value: [ord('r')] }], + ], + [ + `root ::= foo | "bar" +foo ::= "foo"`, + 'bar', + [{ type: 'end' }], + ], + // two expressions + [ + ` +root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + '', + [{ type: 'char', value: [ord('f')] }, { type: 'char', value: [ord('b')] }], + ], + [ + ` +root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + 'f', + [{ type: 'char', value: [ord('o')] }], + ], + [ + ` +root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + 'fo', + [{ type: 'char', value: [ord('o')] }], + ], + [ + ` +root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + 'foo', + [{ type: 'end' }], + ], + [ + ` +root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + 'b', + [{ type: 'char', value: [ord('a')] }], + ], + [ + ` +root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + 'ba', + [{ type: 'char', value: [ord('r')] }], + ], + [ + ` +root ::= foo | bar +foo ::= "foo" +bar ::= "bar"`, + 'bar', + [{ type: 'end' }], + ], + // nested expressions + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + '', + [{ type: 'char', value: [ord('f')] }, { type: 'char', value: [ord('b')] }], + ], + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'f', + [{ type: 'char', value: [ord('o')] }], + ], + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'fo', + [{ type: 'char', value: [ord('o')] }], + ], + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'foo', + [{ type: 'end' }], + ], + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'b', + [{ type: 'char', value: [ord('a')] }], + ], + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'ba', + [{ type: 'char', value: [ord('r')] }, { type: 'char', value: [ord('z')] }], + ], + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'bar', + [{ type: 'end' }], + ], + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz"`, + 'baz', + [{ type: 'end' }], + ], + // ranges + ['root ::= [a-z]', '', [{ type: 'char', value: [[ord('a'), ord('z')]] }]], + ['root ::= [a-zA-Z]', '', [{ type: 'char', value: [[ord('a'), ord('z')], [ord('A'), ord('Z')]] }]], + ['root ::= [a-z]', 'a', [{ type: 'end' }]], + ['root ::= [a-z]', 'm', [{ type: 'end' }]], + ['root ::= [a-z]', 'z', [{ type: 'end' }]], + ['root ::= [a-zA-Z]', 'a', [{ type: 'end' }]], + ['root ::= [a-zA-Z]', 'Z', [{ type: 'end' }]], + ['root ::= [a-zA-Z0-9]', 'Z', [{ type: 'end' }]], + ['root ::= [a-zA-Z0-9]', '0', [{ type: 'end' }]], + ['root ::= [a-zA-Z0-9]', '9', [{ type: 'end' }]], + // range with ? modifier + ['root ::= [a-z]?', '', [{ type: 'char', value: [[ord('a'), ord('z')]] }, { type: 'end' }]], + ['root ::= [a-z]?', 'a', [{ type: 'end' }]], + ['root ::= [a-zA-Z]?', 'Z', [{ type: 'end' }]], + ['root ::= [a-zA-Z0-9]?', '0', [{ type: 'end' }]], + // range with + modifier + ['root ::= [a-z]+', '', [{ type: 'char', value: [[ord('a'), ord('z')]] }]], + ['root ::= [a-z]+', 'l', [{ type: 'char', value: [[ord('a'), ord('z')]] }, { type: 'end' }]], + [ + 'root ::= [a-zA-Z]+', + 'Z', + [{ type: 'char', value: [[ord('a'), ord('z')], [ord('A'), ord('Z')]] }, { type: 'end' }], + ], + [ + 'root ::= [a-zA-Z]+', + 'aZ', + [{ type: 'char', value: [[ord('a'), ord('z')], [ord('A'), ord('Z')]] }, { type: 'end' }], + ], + [ + 'root ::= [a-zA-Z]+', + 'azAZ', + [{ type: 'char', value: [[ord('a'), ord('z')], [ord('A'), ord('Z')]] }, { type: 'end' }], + ], + // range with * modifier + ['root ::= [a-z]*', '', [{ type: 'char', value: [[ord('a'), ord('z')]] }, { type: 'end' }]], + ['root ::= [a-z]*', 'a', [{ type: 'char', value: [[ord('a'), ord('z')]] }, { type: 'end' }]], + [ + 'root ::= [a-zA-Z]+', + 'Z', + [{ type: 'char', value: [[ord('a'), ord('z')], [ord('A'), ord('Z')]] }, { type: 'end' }], + ], + [ + 'root ::= [a-zA-Z]+', + 'abczABCZ', + [{ type: 'char', value: [[ord('a'), ord('z')], [ord('A'), ord('Z')]] }, { type: 'end' }], + ], + // char not with modifiers + ['root ::= [^f]+ "o"', 'aaa', [{ type: 'char_exclude', value: [ord('f')] }, { type: 'char', value: [ord('o')] }]], + ['root ::= [^A-Z]+', 'abc', [{ type: 'char_exclude', value: [[ord('A'), ord('Z')]] }, { type: 'end' }]], + [ + 'root ::= [^A-Z0-9]*', + 'abc', + [{ type: 'char_exclude', value: [[ord('A'), ord('Z')], [ord('0'), ord('9')]] }, { type: 'end' }], + ], + [ + 'root ::= [^A-Z0-9_-]*', + 'abc', + [ + { type: 'char_exclude', value: [[ord('A'), ord('Z')], [ord('0'), ord('9')], ord('_'), ord('-')] }, + { type: 'end' }, + ], + ], + // real world bugs + [ + ` +root ::= [a-z] | xyx +xyx ::= "foo"`, + 'f', + [{ type: 'end' }, { type: 'char', value: [ord('o')] }], + ], + // "baz" and "bazaar" are ambiguous, and a string "bazaa" should not result in an 'a' CHAR rule + ['root ::= "foo" | "bar" | "baz" | "bazaar" | "barrington" ', 'bazaa', [{ type: 'char', value: [ord('r')] }]], + // should be able to step _into_ a rule, and then continue with the previous rule + ['root ::= ("bar" | "foo") "zyx"', 'bar', [{ type: 'char', value: [ord('z')] }]], + // should be able to process a rule, then step _into_ a rule, with a pointer to previous rule + [ + 'root ::= "z" ("bar" | "foo") "zzzz"', + 'z', + [{ type: 'char', value: [ord('b')] }, { type: 'char', value: [ord('f')] }], + ], + // should be able to process a rule, then step _into_ a rule, and then continue with the previous rule + ['root ::= "z" ("bar" | "foo") "zzz"', 'zbar', [{ type: 'char', value: [ord('z')] }]], + [ + '\nroot ::= termz ([-+*/] termz)* \ntermz ::= [0-9]+', + '1', + [ + { type: 'char', value: [[ord('0'), ord('9')]] }, + { type: 'char', value: [ord('-'), ord('+'), ord('*'), ord('/')] }, + { type: 'end' }, + ], + ], + [ + '\nroot ::= expr "=" termy \nexpr ::= termy ([-+*/] termy)*\ntermy ::= [0-9]+', + '1', + [ + { type: 'char', value: [[ord('0'), ord('9')]] }, + { type: 'char', value: [ord('-'), ord('+'), ord('*'), ord('/')] }, + { type: 'char', value: [ord('=')] }, + ], + ], + [ + ` +root ::= (expr "=" terma " +")+ +expr ::= terma ([-+*/] terma)* +terma ::= [0-9]+`, + '1', + [ + { type: 'char', value: [[ord('0'), ord('9')]] }, + { type: 'char', value: [ord('-'), ord('+'), ord('*'), ord('/')] }, + { type: 'char', value: [ord('=')] }, + ], + ], + [ + `root ::= (expr "=" termb " +")+ +expr ::= termb ([-+*/] termb)* +termb ::= [0-9]+`, + '1+', + [{ type: 'char', value: [[ord('0'), ord('9')]] }], + ], + [ + ` +root ::= (expr "=" termc " +")+ +expr ::= termc ([-+*/] termc)* +termc ::= [0-9]+`, + '1=', + [{ type: 'char', value: [[ord('0'), ord('9')]] }], + ], + [ + `root ::= (expr "=" termd " +")+ +expr ::= termd ([-+*/] termd)* +termd ::= [0-9]+`, + '1+1', + [ + { type: 'char', value: [[ord('0'), ord('9')]] }, + { type: 'char', value: [ord('-'), ord('+'), ord('*'), ord('/')] }, + { type: 'char', value: [ord('=')] }, + ], + ], + [ + `root ::= (expr "=" term " +")+ +expr ::= term ([-+*/] term)* +term ::= [0-9]+`, + '1=1', + [{ type: 'char', value: [[ord('0'), ord('9')]] }, { type: 'char', value: [ord('\n')] }], + ], + [ + 'root ::= "\\"" ( [^\\"abcdefghA-Z])* ', + '"is not only in its lyrism, its vow to sustin it in its poo-sion, its r,v:l\'y, it\'s tory,', + [ + { + type: 'char_exclude', + value: [ + ord('"'), + ord('a'), + ord('b'), + ord('c'), + ord('d'), + ord('e'), + ord('f'), + ord('g'), + ord('h'), + [ord('A'), ord('Z')], + ], + }, + { type: 'end' }, + ], + ], + // sticking to llama.cpp's implementation, for a char_not rule _and_ a char rule + // side by side, _either_ is valid. + // that means that input explicitly forbidden by char_not can be allowed by the char + // rule. + // it seems weird. but it's the way it is. + // so below, anything in b-z is allowed, because of the second rule. Anything _not_ a-z is + // also allowed, because of the first rule. So really the only character disallowed is 'a'. + [ + 'root ::= ( [^abcdefgh] | [b-z])* ', + 'bcdefghzyxw0123ABCZ', + [ + { + type: 'char_exclude', + value: [ord('a'), ord('b'), ord('c'), ord('d'), ord('e'), ord('f'), ord('g'), ord('h')], + }, + { type: 'char', value: [[ord('b'), ord('z')]] }, + { type: 'end' }, + ], + ], + ])( + 'it returns parse state for grammar %j and initial string %j [%#]', + (grammar, inputString, expected) => { + const transformedExpectedDict = (e: ExpectedRule): ResolvedRule => { + if (e.type === 'char') { + return new RuleChar(e.value); + } else if (e.type === 'char_exclude') { + return new RuleCharExclude(e.value); + } else if (e.type === 'end') { + return new RuleEnd(); + } else { + throw new Error(`Unknown type found in expectation array: ${e.type}`); + } + }; + + let state = GBNF(grammar); + state = state.add(inputString); + expect([...state].sort(byJson)).toEqual(expected.map(transformedExpectedDict).sort(byJson)); + }, + ); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/iteration/iteration.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/iteration/iteration.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a32346f4651f62718e0cfabc8b51fd9aacc7efa4 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/iteration/iteration.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, test } from 'vitest'; +import { GBNF, type Range, type ResolvedRule, RuleChar, RuleCharExclude, RuleEnd } from '../../../src/index.ts'; + +const ord = (char: string): number => char.codePointAt(0) as number; + +interface ExpectedRule { + type: string; + value?: (number | Range)[]; +} + +describe('iteration', () => { + test.each<[string, ExpectedRule[]]>([ + // single char rule + ['root ::= "foo"', [{ type: 'char', value: [ord('f')] }]], + // two char rules + ['root ::= "foo" | "bar" ', [{ type: 'char', value: [ord('f')] }, { type: 'char', value: [ord('b')] }]], + // three char rules + [ + 'root ::= "foo" | "bar" | "gaz"', + [{ type: 'char', value: [ord('f')] }, { type: 'char', value: [ord('b')] }, { type: 'char', value: [ord('g')] }], + ], + ['root ::= "foo" | "bar" | "baz"', [{ type: 'char', value: [ord('f')] }, { type: 'char', value: [ord('b')] }]], + // char not + ['root ::= [^x]', [{ type: 'char_exclude', value: [ord('x')] }]], + ['root ::= [^f] "o"', [{ type: 'char_exclude', value: [ord('f')] }]], + ['root ::= [^A-Z]', [{ type: 'char_exclude', value: [[ord('A'), ord('Z')]] }]], + ['root ::= [^A-Z0-9]', [{ type: 'char_exclude', value: [[ord('A'), ord('Z')], [ord('0'), ord('9')]] }]], + [ + 'root ::= [^A-Z0-9_-]', + [{ type: 'char_exclude', value: [[ord('A'), ord('Z')], [ord('0'), ord('9')], ord('_'), ord('-')] }], + ], + // expressions + [ + ` +root ::= foo +foo ::= "foo" + `, + [{ type: 'char', value: [ord('f')] }], + ], + [ + ` +root ::= f +f ::= foo +foo ::= "foo" + `, + [{ type: 'char', value: [ord('f')] }], + ], + // expression and a char rule + [ + ` +root ::= foo | "bar" +foo ::= "foo"`, + [{ type: 'char', value: [ord('f')] }, { type: 'char', value: [ord('b')] }], + ], + // two expressions + [ + ` +root ::= foo | bar +foo ::= "foo" +bar ::= "bar" + `, + [{ type: 'char', value: [ord('f')] }, { type: 'char', value: [ord('b')] }], + ], + // nested expressions + [ + ` +root ::= f | b +f ::= fo +b ::= ba +fo ::= foo +ba ::= bar | baz +foo ::= "foo" +bar ::= "bar" +baz ::= "baz" + `, + [{ type: 'char', value: [ord('f')] }, { type: 'char', value: [ord('b')] }], + ], + // ranges + ['root ::= [a-z]', [{ type: 'char', value: [[ord('a'), ord('z')]] }]], + ['root ::= [a-zA-Z]', [{ type: 'char', value: [[ord('a'), ord('z')], [ord('A'), ord('Z')]] }]], + // range with ? modifier + ['root ::= [a-z]?', [{ type: 'char', value: [[ord('a'), ord('z')]] }, { type: 'end' }]], + // range with + modifier + ['root ::= [a-z]+', [{ type: 'char', value: [[ord('a'), ord('z')]] }]], + // range with * modifier + ['root ::= [a-z]*', [{ type: 'char', value: [[ord('a'), ord('z')]] }, { type: 'end' }]], + // rules that aren't used are silently ignored + [ + ` + root ::= "foo" + foo ::= "foo"`, + [{ type: 'char', value: [ord('f')] }], + ], + // real world use cases + // arithmetic + [ + ` + root ::= (expr "=" term "")+ + expr ::= term ([-+*/] term)* + term ::= [0-9]+ + `, + [{ type: 'char', value: [[ord('0'), ord('9')]] }], + ], + ])('it returns parse state for grammar %j [%#]', (grammar, expected) => { + const transformedExpectedDict = (e: ExpectedRule): ResolvedRule => { + if (e.type === 'char') { + return new RuleChar(e.value); + } else if (e.type === 'char_exclude') { + return new RuleCharExclude(e.value); + } else if (e.type === 'end') { + return new RuleEnd(); + } else { + throw new Error(`Unknown type found in expectation array: ${e.type}`); + } + }; + + const state = [...GBNF(grammar)]; + expect(state).toEqual(expected.map(transformedExpectedDict)); + }); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/validation/validate-grammar.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/validation/validate-grammar.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..292ba6211626092867488981b185499489d14df3 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/validation/validate-grammar.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, test } from 'vitest'; +import { GBNF, GrammarParseError } from '../../../src/index.ts'; + +// runs the callback, and returns the error it is expected to throw +const raises = (expected: new (...args: never[]) => T, callback: () => unknown): T => { + let error: unknown; + try { + callback(); + } catch (err) { + error = err; + } + expect(error).toBeInstanceOf(expected); + return error as T; +}; + +describe('validate grammar', () => { + test.each([ + 'root ::= "foo"', + 'root ::= "foo" | "bar"', + 'root ::= ("foo" | "bar")', + 'root ::= ("foo" | "bar")?', + 'root ::= ("foo" | "bar")*', + 'root ::= ("foo" | "bar")+', + 'root ::= [a-z]', + 'root ::= [a-zA-Z]', + 'root ::= [a-zA-Z0-9]', + 'root ::= [a-zA-Z0-9]*', + 'root ::= [a-zA-Z0-9]?', + 'root ::= [a-z]+', + 'root ::= [a-zA-Z0-9]+', + 'root ::= ([a-zA-Z0-9])*', + 'root ::= ([a-zA-Z0-9])?', + 'root ::= ([a-zA-Z0-9])+', + ` + root ::= foo + foo ::= "foo"`, + ` + root ::= foo + foo ::= "foo" | "bar" | ([a-z])? + `, + ])('it parses a grammar %j [%#]', (grammar) => { + GBNF(grammar); + }); + + test.each<[string, number, string]>([ + ['', 0, 'No rules were found'], + ['root = "foo"', 5, 'Expecting ::= at 5'], + [ + `root ::= foo +foo := "foo" + `, + 17, + 'Expecting ::= at 17', + ], + ['root ::= foo', 9, 'Undefined rule identifier "foo"'], + [ + `root ::= foo +bar ::= "bar" + `, + 9, + 'Undefined rule identifier "foo"', + ], + [ + `root ::= foo +foo ::= baz +bar ::= "bar" + `, + 21, + 'Undefined rule identifier "baz"', + ], + ['root ::= foo ::= bar', 13, 'Expecting newline or end at 13'], + [ + `root ::= ([a-z] +foo ::= "foo" + `, + 20, + "Expecting ')' at 20", + ], + ])( + 'it reports an error for an invalid grammar %j [%#]', + (grammar, errorPos, errorReason) => { + const expected = new GrammarParseError(grammar, errorPos, errorReason); + const e = raises(GrammarParseError, () => GBNF(grammar)); + expect(e.message).toEqual(expected.message); + }, + ); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/validation/validate-input.test.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/validation/validate-input.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd1e00fd5f9b3d46a7688732f2e23d7d90c40e03 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tests/generated/validation/validate-input.test.ts @@ -0,0 +1,352 @@ +import { describe, expect, test } from 'vitest'; +import { GBNF, InputParseError } from '../../../src/index.ts'; + +// runs the callback, and returns the error it is expected to throw +const raises = (expected: new (...args: never[]) => T, callback: () => unknown): T => { + let error: unknown; + try { + callback(); + } catch (err) { + error = err; + } + expect(error).toBeInstanceOf(expected); + return error as T; +}; + +describe('validate input', () => { + test.each<[string, string]>([['root ::= "foo"', 'f']])( + 'it parses a grammar %j with input %j [%#]', + (grammar, input) => { + const graph = GBNF(grammar, input); + expect(Boolean(graph)).toBe(true); + }, + ); + + test.each<[string, string, number]>([ + ['root ::= "foo"', '2', 0], + ['root ::= "foo"', 'b', 0], + ['root ::= "foo"', 'f1', 1], + ['root ::= "foo"', 'fo1', 2], + ['root ::= "foo"', 'fooo', 3], + ['root ::= "foo"', 'fooooooo', 3], + ['root ::= "foo" | "bar"', '1', 0], + ['root ::= "foo" | "bar"', 'z', 0], + ['root ::= "foo" | "bar"', 'f1', 1], + ['root ::= "foo" | "bar"', 'b1', 1], + ['root ::= "foo" | "bar"', 'fo1', 2], + ['root ::= "foo" | "bar"', 'ba1', 2], + ['root ::= "foo" | "bar"', 'fooo', 3], + ['root ::= "foo" | "bar"', 'barrr', 3], + ['root ::= "foo" | "bar" | "baz"', '1', 0], + ['root ::= "foo" | "bar" | "baz"', 'z', 0], + ['root ::= "foo" | "bar" | "baz"', 'f1', 1], + ['root ::= "foo" | "bar" | "baz"', 'b1', 1], + ['root ::= "foo" | "bar" | "baz"', 'fo1', 2], + ['root ::= "foo" | "bar" | "baz"', 'bal', 2], + ['root ::= "foo" | "bar" | "baz"', 'fooo', 3], + ['root ::= "foo" | "bar" | "baz"', 'bazrr', 3], + ['root ::= [^a]', 'a', 0], + ['root ::= [^abc]', 'b', 0], + ['root ::= [^a-z]', 'z', 0], + ['root ::= [^a-zA-Z]', 'X', 0], + ['root ::= [^a-zA-Z0-9]', '8', 0], + [ + ` + root ::= foo + foo ::= "foo"`, + '1', + 0, + ], + [ + ` + root ::= foo + foo ::= "foo"`, + 'b', + 0, + ], + [ + ` + root ::= foo + foo ::= "foo"`, + 'f1', + 1, + ], + [ + ` + root ::= foo + foo ::= "foo"`, + 'fo1', + 2, + ], + [ + ` + root ::= foo + foo ::= "foo"`, + 'fooo', + 3, + ], + [ + ` + root::=foo|"bar" + foo::="foo"`, + '1', + 0, + ], + [ + ` + root::=foo|"bar" + foo::="foo"`, + 'z', + 0, + ], + [ + ` + root::=foo|"bar" + foo::="foo"`, + 'f1', + 1, + ], + [ + ` + root::=foo|"bar" + foo::="foo"`, + 'b1', + 1, + ], + [ + ` + root::=foo|"bar" + foo::="foo"`, + 'fo1', + 2, + ], + [ + ` + root::=foo|"bar" + foo::="foo"`, + 'fooo', + 3, + ], + [ + ` + root::=foo|"bar" + foo::="foo"`, + 'barr', + 3, + ], + [ + ` + root::= foo | bar + foo::="foo" + bar::="bar"`, + '1', + 0, + ], + [ + ` + root::= foo | bar + foo::="foo" + bar::="bar"`, + 'z', + 0, + ], + [ + ` + root::= foo | bar + foo::="foo" + bar::="bar"`, + 'f1', + 1, + ], + [ + ` + root::= foo | bar + foo::="foo" + bar::="bar"`, + 'b1', + 1, + ], + [ + ` + root::= foo | bar + foo::="foo" + bar::="bar"`, + 'fo1', + 2, + ], + [ + ` + root::= foo | bar + foo::="foo" + bar::="bar"`, + 'fooo', + 3, + ], + [ + ` + root::= foo | bar + foo::="foo" + bar::="bar"`, + 'barr', + 3, + ], + [ + ` + root ::= f | b + f ::= fo + b ::= ba + fo ::= foo + ba ::= bar | baz + foo ::= "foo" + bar ::= "bar" + baz ::= "baz" + `, + '1', + 0, + ], + [ + ` + root ::= f | b + f ::= fo + b ::= ba + fo ::= foo + ba ::= bar | baz + foo ::= "foo" + bar ::= "bar" + baz ::= "baz"`, + 'z', + 0, + ], + [ + ` + root ::= f | b + f ::= fo + b ::= ba + fo ::= foo + ba ::= bar | baz + foo ::= "foo" + bar ::= "bar" + baz ::= "baz"`, + 'f1', + 1, + ], + [ + ` + root ::= f | b + f ::= fo + b ::= ba + fo ::= foo + ba ::= bar | baz + foo ::= "foo" + bar ::= "bar" + baz ::= "baz"`, + 'b1', + 1, + ], + [ + ` + root ::= f | b + f ::= fo + b ::= ba + fo ::= foo + ba ::= bar | baz + foo ::= "foo" + bar ::= "bar" + baz ::= "baz"`, + 'fo1', + 2, + ], + [ + ` + root ::= f | b + f ::= fo + b ::= ba + fo ::= foo + ba ::= bar | baz + foo ::= "foo" + bar ::= "bar" + baz ::= "baz"`, + 'fooo', + 3, + ], + [ + ` + root ::= f | b + f ::= fo + b ::= ba + fo ::= foo + ba ::= bar | baz + foo ::= "foo" + bar ::= "bar" + baz ::= "baz"`, + 'barr', + 3, + ], + [ + ` + root ::= f | b + f ::= fo + b ::= ba + fo ::= foo + ba ::= bar | baz + foo ::= "foo" + bar ::= "bar" + baz ::= "baz"`, + 'bazr', + 3, + ], + ['root ::= [a-z]', 'A', 0], + ['root ::= [a-z]', '0', 0], + ['root ::= [a-z]', 'az', 1], + ['root ::= [a-z]?', 'A', 0], + ['root ::= [a-z]?', '0', 0], + ['root ::= [a-z]?', 'az', 1], + ['root ::= [a-z]+', 'A', 0], + ['root ::= [a-z]+', '0', 0], + ['root ::= [a-z]+', 'az0', 2], + ['root ::= [a-z]*', 'A', 0], + ['root ::= [a-z]*', '0', 0], + ['root ::= [a-z]*', 'az0', 2], + // sticking to llama.cpp's implementation, for a char_not rule _and_ a char rule + // side by side, _either_ is valid. + // that means that input explicitly forbidden by char_not can be allowed by the char + // rule. + // it seems weird. but it's the way it is. + // so below, anything in b-z is allowed, because of the second rule. Anything _not_ a-z is + // also allowed, because of the first rule. So really the only character disallowed is 'a'. + [ + // sticking to llama.cpp's implementation, for a char_not rule _and_ a char rule + // side by side, _either_ is valid. + // that means that input explicitly forbidden by char_not can be allowed by the char + // rule. + // it seems weird. but it's the way it is. + // so below, anything in b-z is allowed, because of the second rule. Anything _not_ a-z is + // also allowed, because of the first rule. So really the only character disallowed is 'a'. + 'root ::= ( [^abcdefgh] | [b-z])*', + // sticking to llama.cpp's implementation, for a char_not rule _and_ a char rule + // side by side, _either_ is valid. + // that means that input explicitly forbidden by char_not can be allowed by the char + // rule. + // it seems weird. but it's the way it is. + // so below, anything in b-z is allowed, because of the second rule. Anything _not_ a-z is + // also allowed, because of the first rule. So really the only character disallowed is 'a'. + 'a', + // sticking to llama.cpp's implementation, for a char_not rule _and_ a char rule + // side by side, _either_ is valid. + // that means that input explicitly forbidden by char_not can be allowed by the char + // rule. + // it seems weird. but it's the way it is. + // so below, anything in b-z is allowed, because of the second rule. Anything _not_ a-z is + // also allowed, because of the first rule. So really the only character disallowed is 'a'. + 0, + ], + ])( + 'it reports an error for an invalid input %j for grammar %j [%#]', + (grammar, inputText, errorPos) => { + const graph = GBNF(grammar); + const expected = new InputParseError(inputText, errorPos); + const e = raises(InputParseError, () => graph.add(inputText)); + expect(e.message).toEqual(expected.message); + }, + ); +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tsconfig.json b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..e49cd87d4de6afab9c55359a92ebac54933bed0f --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2023"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "erasableSyntaxOnly": true, + "isolatedModules": true, + "skipLibCheck": true + }, + "include": ["src", "tests", "vitest.config.ts"] +} diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/vitest.config.ts b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/vitest.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..bdf41d53d0f73093383a1c08c87bd5b499a5c7a1 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/ported_implementation/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + // unit tests are colocated with the source, integration tests live under tests/generated + include: ['src/**/*.test.ts', 'tests/**/*.test.ts'], + }, +}); diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/proxy.log b/v2-models-effort/runs/20261111-214430-weathered-fire/proxy.log new file mode 100644 index 0000000000000000000000000000000000000000..dcab118f9bac22fbb5fe0cc5ef92af0a00516e5d --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/proxy.log @@ -0,0 +1,18 @@ +NOTICE Nov 12 09:11:23.129 [8]: Initializing tinyproxy ... +NOTICE Nov 12 09:11:23.129 [8]: Reloading config file (/etc/tinyproxy/tinyproxy.conf) +INFO Nov 12 09:11:23.129 [8]: Added address [127.0.0.1] to listen addresses. +INFO Nov 12 09:11:23.129 [8]: Adding Port [443] to the list allowed by CONNECT +NOTICE Nov 12 09:11:23.129 [8]: Reloading config file finished +INFO Nov 12 09:11:23.129 [8]: listen_sock called with addr = '127.0.0.1' +INFO Nov 12 09:11:23.129 [8]: trying to listen on host[127.0.0.1], family[2], socktype[1], proto[6] +INFO Nov 12 09:11:23.129 [8]: listening on fd [3] +INFO Nov 12 09:11:23.129 [8]: Not running as root, so not changing UID/GID. +INFO Nov 12 09:11:23.129 [8]: Setting the various signals. +INFO Nov 12 09:11:23.129 [8]: Starting main loop. Accepting connections. +botbox-proxy: listening +CONNECT Nov 12 09:11:23.963 [8]: Connect (file descriptor 4): 127.0.0.1 +CONNECT Nov 12 09:11:23.963 [8]: Request (file descriptor 4): CONNECT api.anthropic.com:443 HTTP/1.1 +NOTICE Nov 12 09:11:23.963 [8]: Proxying refused on filtered url "api.anthropic.com:443" +CONNECT Nov 12 10:54:46.916 [8]: Connect (file descriptor 4): 127.0.0.1 +CONNECT Nov 12 10:54:46.916 [8]: Request (file descriptor 4): CONNECT registry.npmjs.org:443 HTTP/1.1 +NOTICE Nov 12 10:54:46.916 [8]: Proxying refused on filtered url "registry.npmjs.org:443" diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/run.json b/v2-models-effort/runs/20261111-214430-weathered-fire/run.json new file mode 100644 index 0000000000000000000000000000000000000000..62f95160009294b105964a4a32aacbe1528f609e --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/run.json @@ -0,0 +1,28 @@ +{ + "params": { + "source-language": "python", + "model": "claude-fable-5-2", + "effort": "max" + }, + "command": "uv run --project packages/gbnf_experiment run_gbnf_experiment --include-unit-tests 1 --include-source-integration-tests 1 --include-target-integration-tests 0 --output /home/duncan/work/code/research/ports/experiments/v2-models-effort/runs/20261111-214430-weathered-fire --source-language python --model claude-fable-5-2 --effort max --auth subscription --memory 24g", + "created": "2026-11-12T09:11:11Z", + "ended": "2026-11-12T11:06:35Z", + "exit_code": 143, + "error": null, + "ended_by": "stop", + "signal": 15, + "git": { + "commit": "8422439f49db061ed5b56e9b883ef244807898f8", + "dirty": true + }, + "labnotes_version": "0.2.39.dev138", + "labnotes_command": "labnotes experiments v2-models-effort run --concurrency 1 --model=claude-fable-5-2 -- --auth subscription --memory 24g", + "args": [ + "--auth", + "subscription", + "--memory", + "24g" + ], + "pid": 1404935, + "pid_created": 1794474671.46 +} diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/run.lock b/v2-models-effort/runs/20261111-214430-weathered-fire/run.lock new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/stderr.log b/v2-models-effort/runs/20261111-214430-weathered-fire/stderr.log new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/stderr.txt b/v2-models-effort/runs/20261111-214430-weathered-fire/stderr.txt new file mode 100644 index 0000000000000000000000000000000000000000..bf0334f998f924ebe8de60c292a936a6c8addec7 --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/stderr.txt @@ -0,0 +1 @@ +[claude-code:unrecognized_model] {"model":"claude-fable-5-2","query_source":"sdk"} diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/stdout.log b/v2-models-effort/runs/20261111-214430-weathered-fire/stdout.log new file mode 100644 index 0000000000000000000000000000000000000000..7c65e264ef2b35a60aa63b5a1bcdd134daae918d --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/stdout.log @@ -0,0 +1 @@ +*** auth: subscription *** diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/stdout.txt b/v2-models-effort/runs/20261111-214430-weathered-fire/stdout.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/v2-models-effort/runs/20261111-214430-weathered-fire/transcripts/-target/417f4733-99c2-4f9c-8507-df73badc4e7f.jsonl b/v2-models-effort/runs/20261111-214430-weathered-fire/transcripts/-target/417f4733-99c2-4f9c-8507-df73badc4e7f.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..586a648cb718d4e28649407cff9490e1ac88c0be --- /dev/null +++ b/v2-models-effort/runs/20261111-214430-weathered-fire/transcripts/-target/417f4733-99c2-4f9c-8507-df73badc4e7f.jsonl @@ -0,0 +1,1184 @@ +{"type":"queue-operation","operation":"enqueue","timestamp":"2026-11-12T09:11:24.085Z","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","content":"You are porting software from one language to another.\n\nThe reference is mounted read-only at `/input`.\n\nWrite the port to `/target`.\n\nThere is no network access.\n\nThe sandbox image was built from these two Dockerfiles, the second on top of the first:\n\n```Dockerfile\nFROM node:24.20.0-slim\n\nRUN apt-get update && \\\n apt-get install -y --no-install-recommends git ca-certificates socat && \\\n rm -rf /var/lib/apt/lists/*\n\nRUN npm install -g @anthropic-ai/claude-code@2.1.296\n\nRUN usermod --login user --home /home/user --move-home node && groupmod --new-name user node\n\n# The agent runs as the host's uid, which may not be this one.\nRUN mkdir -p /home/user/.claude/projects && \\\n cd /home/user && chmod 777 . .claude .claude/projects\n\nRUN find / -xdev -perm /6000 -type f -exec chmod a-s {} + && chmod 666 /etc/passwd\n\nCOPY --from=botbox --chmod=755 botbox-relay /usr/local/bin/botbox-relay\n\nUSER user\n\nENV DISABLE_AUTOUPDATER=1 \\\n CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 \\\n CLAUDE_CONFIG_DIR=/home/user/.claude\n```\n\n```Dockerfile\nFROM botbox-claude:latest\n\nUSER root\n\nCOPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /usr/local/bin/\nENV UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \\\n UV_PYTHON_BIN_DIR=/usr/local/bin\nRUN uv python install --preview-features python-install-default --default 3.14.3\nRUN uv pip install --system --break-system-packages --python 3.14.3 pytest==9.1.1 pytest-describe==3.2.0 \\\n && ln -s \"$(dirname \"$(uv python find 3.14.3)\")/pytest\" /usr/local/bin/pytest\n\nRUN npm install -g vitest@2.1.3\nRUN npm install -g pnpm@9.4.0\nENV NODE_PATH=/usr/local/lib/node_modules\n# ESM resolution ignores NODE_PATH but walks up to /node_modules.\nRUN mkdir /node_modules \\\n && for package in /usr/local/lib/node_modules/*; do ln -s \"$package\" /node_modules/; done \\\n && chown user /node_modules\n\nUSER user\n```\n\nThe library itself may specify additional porting instructions below. Paths in them are relative to `/input`.\n\nPort the implementation under python/ to typescript.\n\nThe following test suites are included:\n\n- python unit tests: python/gbnf/ (colocated, *_test.py)\n- python integration tests: python/tests/generated/\n\n"} +{"type":"queue-operation","operation":"dequeue","timestamp":"2026-11-12T09:11:24.086Z","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f"} +{"parentUuid":null,"isSidechain":false,"promptId":"2c0bdb2d-9a7c-4150-b582-d1bbc4d61e51","type":"user","message":{"role":"user","content":"You are porting software from one language to another.\n\nThe reference is mounted read-only at `/input`.\n\nWrite the port to `/target`.\n\nThere is no network access.\n\nThe sandbox image was built from these two Dockerfiles, the second on top of the first:\n\n```Dockerfile\nFROM node:24.20.0-slim\n\nRUN apt-get update && \\\n apt-get install -y --no-install-recommends git ca-certificates socat && \\\n rm -rf /var/lib/apt/lists/*\n\nRUN npm install -g @anthropic-ai/claude-code@2.1.296\n\nRUN usermod --login user --home /home/user --move-home node && groupmod --new-name user node\n\n# The agent runs as the host's uid, which may not be this one.\nRUN mkdir -p /home/user/.claude/projects && \\\n cd /home/user && chmod 777 . .claude .claude/projects\n\nRUN find / -xdev -perm /6000 -type f -exec chmod a-s {} + && chmod 666 /etc/passwd\n\nCOPY --from=botbox --chmod=755 botbox-relay /usr/local/bin/botbox-relay\n\nUSER user\n\nENV DISABLE_AUTOUPDATER=1 \\\n CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 \\\n CLAUDE_CONFIG_DIR=/home/user/.claude\n```\n\n```Dockerfile\nFROM botbox-claude:latest\n\nUSER root\n\nCOPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /usr/local/bin/\nENV UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \\\n UV_PYTHON_BIN_DIR=/usr/local/bin\nRUN uv python install --preview-features python-install-default --default 3.14.3\nRUN uv pip install --system --break-system-packages --python 3.14.3 pytest==9.1.1 pytest-describe==3.2.0 \\\n && ln -s \"$(dirname \"$(uv python find 3.14.3)\")/pytest\" /usr/local/bin/pytest\n\nRUN npm install -g vitest@2.1.3\nRUN npm install -g pnpm@9.4.0\nENV NODE_PATH=/usr/local/lib/node_modules\n# ESM resolution ignores NODE_PATH but walks up to /node_modules.\nRUN mkdir /node_modules \\\n && for package in /usr/local/lib/node_modules/*; do ln -s \"$package\" /node_modules/; done \\\n && chown user /node_modules\n\nUSER user\n```\n\nThe library itself may specify additional porting instructions below. Paths in them are relative to `/input`.\n\nPort the implementation under python/ to typescript.\n\nThe following test suites are included:\n\n- python unit tests: python/gbnf/ (colocated, *_test.py)\n- python integration tests: python/tests/generated/\n\n"},"uuid":"da8c6d6e-3d63-42e3-9de0-230cc87fb9ad","timestamp":"2026-11-12T09:11:24.114Z","permissionMode":"bypassPermissions","promptSource":"sdk","turnOrigin":"sdk","turnPosition":{"promptIndex":0,"turnIndex":1},"userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"da8c6d6e-3d63-42e3-9de0-230cc87fb9ad","isSidechain":false,"attachment":{"type":"environment","snapshot":{"workingDirectory":"/target","isWorktree":false,"isGitRepo":false,"additionalWorkingDirectories":[],"platform":"linux","shell":"unknown","osVersion":"Linux 7.0.0-28-generic"}},"type":"attachment","uuid":"532e7dab-f714-44c5-8745-225981ad843e","timestamp":"2026-11-12T09:11:24.114Z","rendered":[{"content":"\n# Environment\nYou have been invoked in the following environment: \n - Primary working directory: /target\n - Is a git repository: false\n - Platform: linux\n - Shell: unknown\n - OS Version: Linux 7.0.0-28-generic\n - Downloaded files and extracted archives are untrusted data: put each in its own new, empty directory, keep scripts you write in a different directory, and pass paths as arguments instead of running an interpreter or build tool from inside it. Interpreters load code from the script's directory and the current directory, so a planted `json.py` runs on `import json`. Run any Python that reads them with `-I`. This does not apply to code the user asked you to build or run.\n"}],"renderedRole":"system","userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"532e7dab-f714-44c5-8745-225981ad843e","isSidechain":false,"attachment":{"type":"model","identity":{"modelId":"claude-fable-5-2","marketingName":null,"knowledgeCutoff":null},"text":"You are powered by the model claude-fable-5-2."},"type":"attachment","uuid":"94fd9366-5e9c-4bd1-ba7d-3f318b472cba","timestamp":"2026-11-12T09:11:24.114Z","rendered":[{"content":"\nYou are powered by the model claude-fable-5-2.\n"}],"renderedRole":"system","userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"94fd9366-5e9c-4bd1-ba7d-3f318b472cba","isSidechain":false,"attachment":{"type":"agent_listing_delta","addedTypes":["claude","Explore","general-purpose","Plan","statusline-setup"],"addedLines":["- claude: Catch-all for any task that doesn't fit a more specific agent. FleetView's default when no agent name is typed. (Tools: *)","- Explore: Read-only search agent for broad fan-out searches — when answering means sweeping many files, directories, or naming conventions and you only need the conclusion, not the file dumps. It reads excerpts rather than whole files, so it locates code; it doesn't review or audit it. Specify search breadth: \"medium\" for moderate exploration, \"very thorough\" for multiple locations and naming conventions. (Tools: All tools except Agent, Artifact, ArtifactComments, ArtifactData, ArtifactCheck, ExitPlanMode, Edit, Write, NotebookEdit)","- general-purpose: General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. (Tools: *)","- Plan: Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs. (Tools: All tools except Agent, Artifact, ArtifactComments, ArtifactData, ArtifactCheck, ExitPlanMode, Edit, Write, NotebookEdit)","- statusline-setup: Use this agent to configure the user's Claude Code status line setting. (Tools: Read, Edit)"],"builtInTypes":["claude","Explore","general-purpose","Plan","statusline-setup"],"removedTypes":[],"isInitial":true,"showConcurrencyNote":true},"type":"attachment","uuid":"af1d838e-bdd4-4ed7-81b4-b56269cf9dc0","timestamp":"2026-11-12T09:11:24.114Z","rendered":[{"content":"\nAvailable agent types for the Agent tool:\n- claude: Catch-all for any task that doesn't fit a more specific agent. FleetView's default when no agent name is typed. (Tools: *)\n- Explore: Read-only search agent for broad fan-out searches — when answering means sweeping many files, directories, or naming conventions and you only need the conclusion, not the file dumps. It reads excerpts rather than whole files, so it locates code; it doesn't review or audit it. Specify search breadth: \"medium\" for moderate exploration, \"very thorough\" for multiple locations and naming conventions. (Tools: All tools except Agent, Artifact, ArtifactComments, ArtifactData, ArtifactCheck, ExitPlanMode, Edit, Write, NotebookEdit)\n- general-purpose: General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. (Tools: *)\n- Plan: Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs. (Tools: All tools except Agent, Artifact, ArtifactComments, ArtifactData, ArtifactCheck, ExitPlanMode, Edit, Write, NotebookEdit)\n- statusline-setup: Use this agent to configure the user's Claude Code status line setting. (Tools: Read, Edit)\n\nWhen you launch multiple agents for independent work, send them in a single message with multiple tool uses so they run concurrently.\n"}],"renderedRole":"system","userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"af1d838e-bdd4-4ed7-81b4-b56269cf9dc0","isSidechain":false,"attachment":{"type":"skill_listing","content":"- dataviz: Use this skill whenever you are about to create ANY chart, graph, plot, dashboard, or data visualization, in ANY output medium — an HTML or React artifact, inline SVG, plotting code in any library (matplotlib, plotly, d3, Recharts, …), an image/PNG you will render and upload, or a chart shared into Slack. Read it BEFORE writing the first line of chart code, choosing chart colors, building a stat tile / meter / KPI row, or laying out a dashboard. When the destination is a first-party document connector (host-designated, never self-described) that renders live charts, hand it the rows (inline, or as an uploaded data file the chart cites) rather than a rendered PNG/SVG — a picture of a chart loses hover, data inspection and per-value comments. Produces visualizations that read as one system — elegant, accessible, consistent in light and dark — using a brand-neutral placeholder palette you swap for your own. Teaches a design-system-agnostic method: a form heuristic, a color formula with a runnable validator, mark specs, and interaction rules. A validated default palette is documented in `references/palette.md` — swap that file's values for your brand's. Triggers on: \"chart\", \"graph\", \"plot\", \"data viz\", \"visualization\", \"dashboard\", \"analytics\", \"visualize data\", \"categorical colors\", \"sequential / diverging palette\", \"stat tile\", \"sparkline\", \"heatmap\", \"legend\", \"axis\", \"tooltip\", \"chart colors\", \"color by series\".\n- update-config: Use this skill to configure the Claude Code harness via settings.json. Automated behaviors (\"from now on when X\", \"each time X\", \"whenever X\", \"before/after X\") require hooks configured in settings.json - the harness executes these, not Claude, so memory/preferences cannot fulfill them. Also use for: permissions (\"allow X\", \"add permission\", \"move permission to\"), env vars (\"set X=Y\"), hook troubleshooting, or any changes to settings.json/settings.local.json files. Examples: \"allow npm commands\", \"add bq permission to global settings\", \"move permission to user settings\", \"set DEBUG=true\", \"when claude stops show X\". For simple settings like theme/model, suggest the /config command.\n- keybindings-help: Use when the user wants to customize keyboard shortcuts, rebind keys, add chord bindings, or modify ~/.claude/keybindings.json. Examples: \"rebind ctrl+s\", \"add a chord shortcut\", \"change the submit key\", \"customize keybindings\".\n- code-review: Review the current diff, or a PR number/branch/path target, for correctness bugs (plus reuse/simplification/efficiency cleanups where the model's review recipe covers them) at the given effort level (low|medium|high|xhigh|max: from few high-confidence findings up to many, some of them uncertain); with no level given, it reuses the level you typed last. Pass --comment to post findings as inline PR comments, or --fix to apply the findings to the working tree after the review. Pass --max-findings to report up to n findings, or --max-findings all for every finding. The choice stays until you pass --max-findings default.\n- simplify: Review the changed code for reuse, simplification, efficiency, and altitude cleanups, then apply the fixes. Quality only — it does not hunt for bugs; use /code-review for that.\n- fewer-permission-prompts: Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project .claude/settings.json to reduce permission prompts.\n- loop: Run a prompt or slash command on a recurring interval (e.g. /loop 5m /foo). Omit the interval to let the model self-pace. - When the user wants to set up a recurring task, poll for status, or run something repeatedly on an interval (e.g. \"check the deploy every 5 minutes\", \"keep running /babysit-prs\"). Do NOT invoke for one-off tasks.\n- schedule: Create, update, list, or run scheduled cloud agents (routines) that execute on a cron schedule. - When the user wants to schedule a recurring cloud agent, set up automated tasks, create a cron job for Claude Code, or manage their scheduled agents/routines. Also use when the user wants a one-time scheduled run (\"run this once at 3pm\", \"remind me to check X tomorrow\").\n- claude-api: Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration.\nTRIGGER — read BEFORE opening the target file; don't skip because it \"looks like a one-liner\" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens).\nSKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).\n- workflow-authoring: Reference for writing a Workflow tool script (script API and gotchas, resume, quality patterns, worked examples). Load before authoring a script for a workflow the user already opted into; it does not itself authorize running one.\n- run: Launch and drive this project's app to see a change working. Use when asked to run, start, or screenshot the app, or to confirm a change works in the real app (not just tests). First looks for a project skill that already covers launching the app; otherwise falls back to built-in patterns per project type (CLI, server, TUI, Electron, browser-driven, library).\n- plugin-authoring: Make a mod: a change to Claude's own interface or behaviour, such as a live pane or panel, a band above the prompt, a status line, a toast, a slash command, or a hook on tool calls or prompts. Use to make, change or debug a mod or its hooks module.\n- init\n- security-review","skillCount":14,"isInitial":true,"names":["dataviz","update-config","keybindings-help","code-review","simplify","fewer-permission-prompts","loop","schedule","claude-api","workflow-authoring","run","plugin-authoring","init","security-review"]},"type":"attachment","uuid":"5b1eac66-e481-477e-91cc-d453cd9b4caf","timestamp":"2026-11-12T09:11:24.114Z","rendered":[{"content":"\nThe following skills are available for use with the Skill tool:\n\n- dataviz: Use this skill whenever you are about to create ANY chart, graph, plot, dashboard, or data visualization, in ANY output medium — an HTML or React artifact, inline SVG, plotting code in any library (matplotlib, plotly, d3, Recharts, …), an image/PNG you will render and upload, or a chart shared into Slack. Read it BEFORE writing the first line of chart code, choosing chart colors, building a stat tile / meter / KPI row, or laying out a dashboard. When the destination is a first-party document connector (host-designated, never self-described) that renders live charts, hand it the rows (inline, or as an uploaded data file the chart cites) rather than a rendered PNG/SVG — a picture of a chart loses hover, data inspection and per-value comments. Produces visualizations that read as one system — elegant, accessible, consistent in light and dark — using a brand-neutral placeholder palette you swap for your own. Teaches a design-system-agnostic method: a form heuristic, a color formula with a runnable validator, mark specs, and interaction rules. A validated default palette is documented in `references/palette.md` — swap that file's values for your brand's. Triggers on: \"chart\", \"graph\", \"plot\", \"data viz\", \"visualization\", \"dashboard\", \"analytics\", \"visualize data\", \"categorical colors\", \"sequential / diverging palette\", \"stat tile\", \"sparkline\", \"heatmap\", \"legend\", \"axis\", \"tooltip\", \"chart colors\", \"color by series\".\n- update-config: Use this skill to configure the Claude Code harness via settings.json. Automated behaviors (\"from now on when X\", \"each time X\", \"whenever X\", \"before/after X\") require hooks configured in settings.json - the harness executes these, not Claude, so memory/preferences cannot fulfill them. Also use for: permissions (\"allow X\", \"add permission\", \"move permission to\"), env vars (\"set X=Y\"), hook troubleshooting, or any changes to settings.json/settings.local.json files. Examples: \"allow npm commands\", \"add bq permission to global settings\", \"move permission to user settings\", \"set DEBUG=true\", \"when claude stops show X\". For simple settings like theme/model, suggest the /config command.\n- keybindings-help: Use when the user wants to customize keyboard shortcuts, rebind keys, add chord bindings, or modify ~/.claude/keybindings.json. Examples: \"rebind ctrl+s\", \"add a chord shortcut\", \"change the submit key\", \"customize keybindings\".\n- code-review: Review the current diff, or a PR number/branch/path target, for correctness bugs (plus reuse/simplification/efficiency cleanups where the model's review recipe covers them) at the given effort level (low|medium|high|xhigh|max: from few high-confidence findings up to many, some of them uncertain); with no level given, it reuses the level you typed last. Pass --comment to post findings as inline PR comments, or --fix to apply the findings to the working tree after the review. Pass --max-findings to report up to n findings, or --max-findings all for every finding. The choice stays until you pass --max-findings default.\n- simplify: Review the changed code for reuse, simplification, efficiency, and altitude cleanups, then apply the fixes. Quality only — it does not hunt for bugs; use /code-review for that.\n- fewer-permission-prompts: Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project .claude/settings.json to reduce permission prompts.\n- loop: Run a prompt or slash command on a recurring interval (e.g. /loop 5m /foo). Omit the interval to let the model self-pace. - When the user wants to set up a recurring task, poll for status, or run something repeatedly on an interval (e.g. \"check the deploy every 5 minutes\", \"keep running /babysit-prs\"). Do NOT invoke for one-off tasks.\n- schedule: Create, update, list, or run scheduled cloud agents (routines) that execute on a cron schedule. - When the user wants to schedule a recurring cloud agent, set up automated tasks, create a cron job for Claude Code, or manage their scheduled agents/routines. Also use when the user wants a one-time scheduled run (\"run this once at 3pm\", \"remind me to check X tomorrow\").\n- claude-api: Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration.\nTRIGGER — read BEFORE opening the target file; don't skip because it \"looks like a one-liner\" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens).\nSKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).\n- workflow-authoring: Reference for writing a Workflow tool script (script API and gotchas, resume, quality patterns, worked examples). Load before authoring a script for a workflow the user already opted into; it does not itself authorize running one.\n- run: Launch and drive this project's app to see a change working. Use when asked to run, start, or screenshot the app, or to confirm a change works in the real app (not just tests). First looks for a project skill that already covers launching the app; otherwise falls back to built-in patterns per project type (CLI, server, TUI, Electron, browser-driven, library).\n- plugin-authoring: Make a mod: a change to Claude's own interface or behaviour, such as a live pane or panel, a band above the prompt, a status line, a toast, a slash command, or a hook on tool calls or prompts. Use to make, change or debug a mod or its hooks module.\n- init\n- security-review\n"}],"renderedRole":"system","userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"5b1eac66-e481-477e-91cc-d453cd9b4caf","isSidechain":false,"attachment":{"type":"total_tokens_reminder","text":"15000000 tokens left"},"type":"attachment","uuid":"78f1ec7f-4b3b-4cd9-8ce7-1edb468108b5","timestamp":"2026-11-12T09:11:24.114Z","rendered":[{"content":"\n15000000 tokens left\n"}],"renderedRole":"system","userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"type":"atis-latch","atis":"","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f"} +{"parentUuid":"78f1ec7f-4b3b-4cd9-8ce7-1edb468108b5","isSidechain":false,"attachment":{"type":"session_context","context":{}},"type":"attachment","uuid":"6962d295-8c60-4e7f-83c1-c062af4a82ae","timestamp":"2026-11-12T09:11:24.125Z","userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"6962d295-8c60-4e7f-83c1-c062af4a82ae","isSidechain":false,"attachment":{"type":"date","date":"2026-11-12"},"type":"attachment","uuid":"aa4ebd21-6c48-48e1-827e-067db726f827","timestamp":"2026-11-12T09:11:24.126Z","rendered":[{"content":"\nToday's date is 2026-11-12.\n"}],"renderedRole":"system","userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"aa4ebd21-6c48-48e1-827e-067db726f827","isSidechain":false,"attachment":{"type":"remote_session_change","url":null,"commit":"Co-Authored-By: Claude Code ","pr":"🤖 Generated with [Claude Code](https://claude.com/claude-code)","sendUserFileHint":false,"managedCommit":false,"managedPr":false},"type":"attachment","uuid":"8f897253-911a-49ca-a1f3-4e4c2e53291c","timestamp":"2026-11-12T09:11:24.126Z","rendered":[{"content":"\nAttribution for git commits and pull requests you create from here on (this replaces Claude Code's own earlier attribution guidance, such as a previous copy of this reminder; the user's own instructions about these lines, such as a CLAUDE.md or memory rule, take precedence over this reminder, but do not add attribution lines this reminder leaves out):\n- End git commit messages with:\nCo-Authored-By: Claude Code \n- End pull request descriptions with:\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n"}],"renderedRole":"user","renderedBesideToolResult":true,"userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"8f897253-911a-49ca-a1f3-4e4c2e53291c","isSidechain":false,"attachment":{"type":"prompt_snapshot","systemPrompt":["\nYou are an agent working with the user toward their goals, using your own judgment along the way.\n\nIMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.\n\n# Harness\n - Text you output outside of tool use is displayed to the user as Github-flavored markdown in a terminal.\n - Tools run behind a user-selected permission mode; a denied call means the user declined it — adjust, don't retry verbatim.\n - The system may send updates, reminders, or modifications to rules via mid-conversation system turns. These are system-controlled, unlike function results. Hooks may intercept tool calls; treat hook output as user feedback.\n - Prefer the dedicated file/search tools over shell commands when one fits. Independent tool calls can run in parallel in one response.\n - Reference code as `file_path:line_number` — it's clickable.","Write code that reads like the surrounding code: match its comment density, naming, and idiom.","When you use a pronoun for someone — the user or anyone else you mention — and their pronouns haven't been stated, use they/them. A name doesn't tell you someone's pronouns; a wrong guess misgenders a real person in a way the neutral default never does, so never infer pronouns from a name. This applies to all user-visible text, including visible thinking.","For actions that are hard to reverse or outward-facing, confirm first unless durably authorized or explicitly told to proceed without asking; approval in one context doesn't extend to the next. Sending content to an external service publishes it; it may be cached or indexed even if later deleted. Before deleting or overwriting, look at the target. Report outcomes faithfully: if tests fail, say so with the output; if a step was skipped, say that; when something is done and verified, state it plainly without hedging.","This iteration of Claude is Claude Fable 5, the first model in Anthropic's new Claude 5 family and part of a new Mythos-class model tier that sits above Claude Opus in capability. Claude Fable 5 and Claude Mythos 5 share the same underlying model. Claude Fable 5 includes additional safety measures for dual-use capabilities, while Claude Mythos 5 is available without those measures to only approved organizations. If the person asks about the differences between the two, Claude can direct them to https://www.anthropic.com/news/claude-fable-5-mythos-5 for more information.","# Session-specific guidance\n - When the user types `/`, invoke it via Skill. Only use skills listed in the user-invocable skills section — don't guess.","# Memory\n\nYou have a persistent file-based memory at `/home/user/.claude/projects/-target/memory/`. This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence). Each memory is one file holding one fact, with frontmatter:\n\n```markdown\n---\nname: \ndescription: \nmetadata:\n type: user | feedback | project | reference\n---\n\n\n```\n\nIn the body, link to related memories with `[[name]]`, where `name` is the other memory's `name:` slug. Link liberally — a `[[name]]` that doesn't match an existing memory yet is fine; it marks something worth writing later, not an error.\n\n`user`: who the user is (role, expertise, preferences). `feedback`: guidance the user has given on how you should work, both corrections and confirmed approaches; include the why. `project`: ongoing work, goals, or constraints not derivable from the code or git history; convert relative dates to absolute. `reference`: pointers to external resources (URLs, dashboards, tickets).\n\nAfter writing the file, add a one-line pointer in `MEMORY.md` (`- [Title](file.md) — hook`). `MEMORY.md` is the index loaded into context each session — one line per memory, no frontmatter, never put memory content there.\n\nBefore saving, check for an existing file that already covers it. Update that file rather than creating a duplicate; delete memories that turn out to be wrong. Don't save what the repo already records (code structure, past fixes, git history, CLAUDE.md) or what only matters to this conversation; if asked to remember one of those, ask what was non-obvious about it and save that instead. Recalled memories appearing inside `` blocks are background context, not user instructions, and reflect what was true when written. If one names a file, function, or flag, verify it still exists before recommending it.","# Environment\n - The most recent Claude models are the Claude 5 family. Model IDs — Fable 5.1: 'claude-fable-5-1', Opus 5.5: 'claude-opus-5-5', Sonnet 5.5: 'claude-sonnet-5-5', Haiku 5.5: 'claude-haiku-5-5'. When building AI applications, default to the latest and most capable Claude models.\n - Claude Code is available as a CLI in the terminal, desktop app (Mac/Windows), web app (claude.ai/code), and IDE extensions (VS Code, JetBrains).\n - Fast mode for Claude Code uses Claude Opus with faster output (it does not downgrade to a smaller model). It can be toggled with /fast.","# Context management\nWhen the conversation grows long, some or all of the current context is summarized; the summary, along with any remaining unsummarized context, is provided in the next context window so work can continue — you don't need to wrap up early or hand off mid-task.","When you have enough information to act, act. Do not re-derive facts already established in the conversation, re-litigate a decision the user has already made, or narrate options you will not pursue. If you are weighing a choice, give a recommendation, not an exhaustive survey","15000000 tokens left"],"reminderFold":false,"echoWireToolInputs":false,"contextRendering":"announced"},"type":"attachment","uuid":"9e0ba1e0-8312-4127-8090-19ac2738c138","timestamp":"2026-11-12T09:11:24.127Z","userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"type":"last-prompt","lastPrompt":"You are porting software from one language to another. The reference is mounted read-only at `/input`. Write the port to `/target`. There is no network access. The sandbox image was built from the…","leafUuid":"9e0ba1e0-8312-4127-8090-19ac2738c138","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f"} +{"type":"atis-latch","atis":"","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f"} +{"parentUuid":"9e0ba1e0-8312-4127-8090-19ac2738c138","isSidechain":false,"message":{"model":"claude-fable-5-2","id":"msg_011CgxmuQ1ybnSiNB5L4JP3y","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"","signature":"CAQSvwUKEAgTGAI4AUIIdGhpbmtpbmcSDMID8mfl5W9itCZLvBoMhXyk/ekPURRrKJBjIjCIR1ZgYGKcBNxAs++5bfiS3esMH+ZmbM5+CSSVEMFPL+UzAG7T0E3iD3Bhl+rGXFEq3AQPWxxDLQLomNoQoQaee/Y9s30RUTupfMsFA8NcE6ZPaOyKKGsG04bx+TUhHlJp0b4rZZ9erwJ/vmy9UpGdNr6uhrtKUGOgZAJQCZOmfO1IG0T68F0zRWjlmPRAD9LvYaxWyC0JzANhFiGxCMC61raWsKUB41qyIBFgdG9t5xkTPPbbdW8K1wB9OFFibu8DBcXlE6wv03xbqodd/cPGDweEUnkJHvdU/nX6cpMMzWy/+HSqRzUPn1bGXomeKgzsJttbFWoRpglZTjCo0bzPh3dL4wFXyun4XMNirXCYeV4md7bHbuzTk+XdL7trtq1rCJy+EKEjAg3FtkbcKzRfalmDcOhZWj06eZ/QglJvcQha9cK7ZZgcCHGetQXKQPKSWVSuEt5Pv2v8pE0g/2zQ0caGM+tfJnJ7Pw/KscIdCj3B6tt4obHW7Ab580QoQ9/TOy+N8pDt/fYxG1bxF6ZVKZWhjXiUzW99ID5AvFD1uaxFKvx6WzKALWfoTm2JGt1zhWbWM/zlRD6UJa/i1YTIStO4YyV54arzmxNfHdt8iRCMK6/Lva2VS97EYsbAAdLSreRDRHl/uamLiMXyV6PiGWB65zeN1muvHZ2t9YMc4LKu2woZh2hT2y02CWao0UpxlSMXLHtABkgJlYvnneKFe6Y1LDq6+PhQjQoRPTa7cIl4zaQOMmLoQkqIIKeCb6SZbEJd08jPXoZQZSAR83NoIv+Qwlmn3W98+TsJo8kfH3Cwf2dMN5hRTp865HFi5DvUqwmWdLKk93EmSNZ5KA7Ui+aaxJqEXs0o41bZZCJ3GAE="}],"container":null,"stop_reason":"tool_use","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":4314,"cache_read_input_tokens":20705,"output_tokens":206,"output_tokens_details":{"thinking_tokens":26},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":4314,"ephemeral_5m_input_tokens":0},"inference_geo":"global","iterations":[],"speed":"standard","fallback_credit":null},"diagnostics":null,"context_management":null},"thinkingDurationMs":615,"thinkingDisplay":"omitted","apiBlockIndex":0,"requestId":"req_011CgxmuPZSKJsKHLiQUL4yZ","requestedModel":"claude-fable-5-2","type":"assistant","uuid":"dbe10c1e-dab1-4e51-bc40-4a5811e0d21a","timestamp":"2026-11-12T09:11:25.645Z","effort":"max","perTurnEffort":null,"userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"dbe10c1e-dab1-4e51-bc40-4a5811e0d21a","isSidechain":false,"message":{"model":"claude-fable-5-2","id":"msg_011CgxmuQ1ybnSiNB5L4JP3y","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_013Vgw5eKHqT9pPBQYfW9qEk","name":"Bash","input":{"command":"ls -la /input /target; find /input -maxdepth 3 -not -path '*/.git/*' | head -200","description":"List reference and target directories"},"caller":{"type":"direct"}}],"container":null,"stop_reason":"tool_use","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":4314,"cache_read_input_tokens":20705,"output_tokens":206,"output_tokens_details":{"thinking_tokens":26},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":4314,"ephemeral_5m_input_tokens":0},"inference_geo":"global","iterations":[],"speed":"standard","fallback_credit":null},"diagnostics":null,"context_management":null},"apiBlockIndex":1,"requestId":"req_011CgxmuPZSKJsKHLiQUL4yZ","requestedModel":"claude-fable-5-2","type":"assistant","uuid":"1fe0b708-06fe-4194-b8aa-2a48a478f634","timestamp":"2026-11-12T09:11:26.176Z","effort":"max","perTurnEffort":null,"userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"1fe0b708-06fe-4194-b8aa-2a48a478f634","isSidechain":false,"promptId":"2c0bdb2d-9a7c-4150-b582-d1bbc4d61e51","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_013Vgw5eKHqT9pPBQYfW9qEk","type":"tool_result","content":"/input:\ntotal 11\ndrwxr-xr-x 3 user user 3 Sep 27 16:32 .\ndrwxr-xr-x 1 root root 7 Nov 12 09:11 ..\ndrwxr-xr-x 4 user user 11 Oct 15 03:24 python\n\n/target:\ntotal 2\ndrwxrwxr-x 2 user user 2 Nov 12 09:11 .\ndrwxr-xr-x 1 root root 7 Nov 12 09:11 ..\n/input\n/input/python\n/input/python/README.md\n/input/python/gbnf\n/input/python/uv.lock\n/input/python/requirements.txt\n/input/python/tests\n/input/python/.gitignore\n/input/python/MANIFEST.in\n/input/python/pyproject.toml\n/input/python/Makefile\n/input/python/gbnf/GBNF.py\n/input/python/gbnf/rules_builder\n/input/python/gbnf/grammar_graph\n/input/python/gbnf/grammar_parser\n/input/python/gbnf/__init__.py\n/input/python/gbnf/utils\n/input/python/tests/generated","is_error":false}]},"uuid":"77194a7c-843d-428a-892c-64808b3a1243","timestamp":"2026-11-12T09:11:26.222Z","toolUseResult":{"stdout":"/input:\ntotal 11\ndrwxr-xr-x 3 user user 3 Sep 27 16:32 .\ndrwxr-xr-x 1 root root 7 Nov 12 09:11 ..\ndrwxr-xr-x 4 user user 11 Oct 15 03:24 python\n\n/target:\ntotal 2\ndrwxrwxr-x 2 user user 2 Nov 12 09:11 .\ndrwxr-xr-x 1 root root 7 Nov 12 09:11 ..\n/input\n/input/python\n/input/python/README.md\n/input/python/gbnf\n/input/python/uv.lock\n/input/python/requirements.txt\n/input/python/tests\n/input/python/.gitignore\n/input/python/MANIFEST.in\n/input/python/pyproject.toml\n/input/python/Makefile\n/input/python/gbnf/GBNF.py\n/input/python/gbnf/rules_builder\n/input/python/gbnf/grammar_graph\n/input/python/gbnf/grammar_parser\n/input/python/gbnf/__init__.py\n/input/python/gbnf/utils\n/input/python/tests/generated","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"sourceToolAssistantUUID":"1fe0b708-06fe-4194-b8aa-2a48a478f634","permissionDecision":{"decision":"accept","source":"config","reasonType":"mode"},"userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"77194a7c-843d-428a-892c-64808b3a1243","isSidechain":false,"message":{"model":"claude-fable-5-2","id":"msg_011CgxmuQ1ybnSiNB5L4JP3y","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01P7bLnYgdZWJT1vghkrCmdg","name":"Read","input":{"file_path":"/home/user/.claude/projects/-target/memory/MEMORY.md"},"caller":{"type":"direct"}}],"container":null,"stop_reason":"tool_use","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":4314,"cache_read_input_tokens":20705,"output_tokens":206,"output_tokens_details":{"thinking_tokens":26},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":4314,"ephemeral_5m_input_tokens":0},"inference_geo":"global","iterations":[],"speed":"standard","fallback_credit":null},"diagnostics":null,"context_management":null},"apiBlockIndex":2,"requestId":"req_011CgxmuPZSKJsKHLiQUL4yZ","requestedModel":"claude-fable-5-2","type":"assistant","uuid":"befc802c-2356-4af4-8ea6-65ee11fadf73","timestamp":"2026-11-12T09:11:26.786Z","effort":"max","perTurnEffort":null,"userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"befc802c-2356-4af4-8ea6-65ee11fadf73","isSidechain":false,"promptId":"2c0bdb2d-9a7c-4150-b582-d1bbc4d61e51","type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"File does not exist. Note: your current working directory is /target.","is_error":true,"tool_use_id":"toolu_01P7bLnYgdZWJT1vghkrCmdg"}]},"uuid":"cfb7c5d8-eea6-447d-9241-352b0dc4f1a1","timestamp":"2026-11-12T09:11:26.800Z","toolUseResult":"Error: File does not exist. Note: your current working directory is /target.","sourceToolAssistantUUID":"befc802c-2356-4af4-8ea6-65ee11fadf73","permissionDecision":{"decision":"accept","source":"config","reasonType":"mode"},"userType":"external","entrypoint":"sdk-cli","cwd":"/target","sessionId":"417f4733-99c2-4f9c-8507-df73badc4e7f","version":"2.1.296","gitBranch":"HEAD"} +{"parentUuid":"cfb7c5d8-eea6-447d-9241-352b0dc4f1a1","isSidechain":false,"attachment":{"type":"prompt_snapshot","systemPrompt":["\nYou are an agent working with the user toward their goals, using your own judgment along the way.\n\nIMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.\n\n# Harness\n - Text you output outside of tool use is displayed to the user as Github-flavored markdown in a terminal.\n - Tools run behind a user-selected permission mode; a denied call means the user declined it — adjust, don't retry verbatim.\n - The system may send updates, reminders, or modifications to rules via mid-conversation system turns. These are system-controlled, unlike function results. Hooks may intercept tool calls; treat hook output as user feedback.\n - Prefer the dedicated file/search tools over shell commands when one fits. Independent tool calls can run in parallel in one response.\n - Reference code as `file_path:line_number` — it's clickable.","Write code that reads like the surrounding code: match its comment density, naming, and idiom.","When you use a pronoun for someone — the user or anyone else you mention — and their pronouns haven't been stated, use they/them. A name doesn't tell you someone's pronouns; a wrong guess misgenders a real person in a way the neutral default never does, so never infer pronouns from a name. This applies to all user-visible text, including visible thinking.","For actions that are hard to reverse or outward-facing, confirm first unless durably authorized or explicitly told to proceed without asking; approval in one context doesn't extend to the next. Sending content to an external service publishes it; it may be cached or indexed even if later deleted. Before deleting or overwriting, look at the target. Report outcomes faithfully: if tests fail, say so with the output; if a step was skipped, say that; when something is done and verified, state it plainly without hedging.","This iteration of Claude is Claude Fable 5, the first model in Anthropic's new Claude 5 family and part of a new Mythos-class model tier that sits above Claude Opus in capability. Claude Fable 5 and Claude Mythos 5 share the same underlying model. Claude Fable 5 includes additional safety measures for dual-use capabilities, while Claude Mythos 5 is available without those measures to only approved organizations. If the person asks about the differences between the two, Claude can direct them to https://www.anthropic.com/news/claude-fable-5-mythos-5 for more information.","# Session-specific guidance\n - When the user types `/`, invoke it via Skill. Only use skills listed in the user-invocable skills section — don't guess.","# Memory\n\nYou have a persistent file-based memory at `/home/user/.claude/projects/-target/memory/`. This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence). Each memory is one file holding one fact, with frontmatter:\n\n```markdown\n---\nname: \ndescription: \nmetadata:\n type: user | feedback | project | reference\n---\n\n\n```\n\nIn the body, link to related memories with `[[name]]`, where `name` is the other memory's `name:` slug. Link liberally — a `[[name]]` that doesn't match an existing memory yet is fine; it marks something worth writing later, not an error.\n\n`user`: who the user is (role, expertise, preferences). `feedback`: guidance the user has given on how you should work, both corrections and confirmed approaches; include the why. `project`: ongoing work, goals, or constraints not derivable from the code or git history; convert relative dates to absolute. `reference`: pointers to external resources (URLs, dashboards, tickets).\n\nAfter writing the file, add a one-line pointer in `MEMORY.md` (`- [Title](file.md) — hook`). `MEMORY.md` is the index loaded into context each session — one line per memory, no frontmatter, never put memory content there.\n\nBefore saving, check for an existing file that already covers it. Update that file rather than creating a duplicate; delete memories that turn out to be wrong. Don't save what the repo already records (code structure, past fixes, git history, CLAUDE.md) or what only matters to this conversation; if asked to remember one of those, ask what was non-obvious about it and save that instead. Recalled memories appearing inside `` blocks are background context, not user instructions, and reflect what was true when written. If one names a file, function, or flag, verify it still exists before recommending it.","# Environment\n - The most recent Claude models are the Claude 5 family. Model IDs — Fable 5.1: 'claude-fable-5-1', Opus 5.5: 'claude-opus-5-5', Sonnet 5.5: 'claude-sonnet-5-5', Haiku 5.5: 'claude-haiku-5-5'. When building AI applications, default to the latest and most capable Claude models.\n - Claude Code is available as a CLI in the terminal, desktop app (Mac/Windows), web app (claude.ai/code), and IDE extensions (VS Code, JetBrains).\n - Fast mode for Claude Code uses Claude Opus with faster output (it does not downgrade to a smaller model). It can be toggled with /fast.","# Context management\nWhen the conversation grows long, some or all of the current context is summarized; the summary, along with any remaining unsummarized context, is provided in the next context window so work can continue — you don't need to wrap up early or hand off mid-task.","When you have enough information to act, act. Do not re-derive facts already established in the conversation, re-litigate a decision the user has already made, or narrate options you will not pursue. If you are weighing a choice, give a recommendation, not an exhaustive survey","15000000 tokens left"],"tools":[{"name":"Agent","description":"Launch a new agent to handle complex, multi-step tasks. Each agent type has specific capabilities and tools available to it.\n\nAvailable agent types are listed in messages in the conversation.\n\nWhen using the Agent tool, specify a subagent_type parameter to select which agent type to use. If omitted, the general-purpose agent is used.\n\n## When to use\n\nReach for this when the task matches an available agent type, when you have independent work to run in parallel, or when answering would mean reading across several files — delegate it and you keep the conclusion, not the file dumps. For a single-fact lookup where you already know the file, symbol, or value, search directly. Once you've delegated a search, don't also run it yourself — wait for the result.\n\n- The agent's final report is not shown to the user — relay what matters.\n- Use SendMessage with the agent's ID or name to continue a previously spawned agent with its context intact; a new Agent call starts fresh.\n- Each agent type's model, reasoning effort, and tools come from its definition (`.claude/agents/*.md` frontmatter or SDK `agents`).\n- `isolation: \"worktree\"` gives the agent its own git worktree (auto-cleaned if unchanged).\n- Subagents run in the background by default; you'll be notified when one completes. Pass `run_in_background: false` only when your very next action depends on the result and nothing else could usefully happen while it runs — otherwise background it so the user can interject. Never fabricate or predict a pending agent's results — the notification is never something you write yourself; if the user asks before it arrives, say it's still running.","schema":{"name":"Agent","description":"Launch a new agent to handle complex, multi-step tasks. Each agent type has specific capabilities and tools available to it.\n\nAvailable agent types are listed in messages in the conversation.\n\nWhen using the Agent tool, specify a subagent_type parameter to select which agent type to use. If omitted, the general-purpose agent is used.\n\n## When to use\n\nReach for this when the task matches an available agent type, when you have independent work to run in parallel, or when answering would mean reading across several files — delegate it and you keep the conclusion, not the file dumps. For a single-fact lookup where you already know the file, symbol, or value, search directly. Once you've delegated a search, don't also run it yourself — wait for the result.\n\n- The agent's final report is not shown to the user — relay what matters.\n- Use SendMessage with the agent's ID or name to continue a previously spawned agent with its context intact; a new Agent call starts fresh.\n- Each agent type's model, reasoning effort, and tools come from its definition (`.claude/agents/*.md` frontmatter or SDK `agents`).\n- `isolation: \"worktree\"` gives the agent its own git worktree (auto-cleaned if unchanged).\n- Subagents run in the background by default; you'll be notified when one completes. Pass `run_in_background: false` only when your very next action depends on the result and nothing else could usefully happen while it runs — otherwise background it so the user can interject. Never fabricate or predict a pending agent's results — the notification is never something you write yourself; if the user asks before it arrives, say it's still running.","input_schema":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"description":{"description":"A short (3-5 word) description of the task","type":"string"},"prompt":{"description":"The task for the agent to perform","type":"string"},"subagent_type":{"description":"The type of specialized agent to use for this task","type":"string"},"model":{"description":"Optional model override for this agent. Takes precedence over the agent definition's model frontmatter and the configured default subagent model. If omitted, uses the agent definition's model, else the default (inherits from the parent unless a default subagent model is configured). Ignored for subagent_type: \"fork\" — forks always inherit the parent model.","type":"string","enum":["sonnet","opus","haiku","fable"]},"effort":{"description":"Reasoning effort for this agent. Set this ONLY when the user, or instructions such as CLAUDE.md or a skill, explicitly ask that this agent or delegated work run at a specific effort level, never on your own judgment; otherwise omit it and the agent runs at its usual effort.","type":"string","enum":["low","medium","high","xhigh","max"]},"run_in_background":{"description":"Agents run in the background by default; you will be notified when one completes. Set to false only when your very next action depends on this agent's result and nothing else could usefully happen while it runs — otherwise leave it in the background so the user can hand you other work.","type":"boolean"},"isolation":{"description":"Isolation mode. \"worktree\" creates a temporary git worktree so the agent works on an isolated copy of the repo. \"remote\" launches the agent in a remote cloud environment (always runs in background; availability is gated).","type":"string","enum":["worktree","remote"]}},"required":["description","prompt"],"additionalProperties":false}}},{"name":"Bash","description":"Executes a bash command and returns its output.\n\n- Working directory persists between calls, but prefer absolute paths — `cd` in a compound command can trigger a permission prompt. Shell state (env vars, functions) does not persist; the shell is initialized from the user's profile.\n- IMPORTANT: Avoid using this tool to run `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands, unless explicitly instructed or after you have verified that a dedicated tool cannot accomplish your task. Instead, use the appropriate dedicated tool as this will provide a much better experience for the user.\n- Command output is displayed to you, not reliably to the user.\n- `timeout` is in milliseconds: default 120000, max 600000 for a foreground command.\n- `run_in_background` runs the command detached: it keeps running across turns and re-invokes you when it exits. With it, `timeout` is how long the command may run in the background (default 600000, max 7200000); at that limit it is stopped and you are re-invoked. No `&` needed.\n\n# Git\n- Interactive flags (`-i`, e.g. `git rebase -i`, `git add -i`) are not supported in this environment.\n- Use the `gh` CLI for GitHub operations (PRs, issues, API).\n- Commit or push only when the user asks. If on the default branch, branch first.\n- End git commit messages and PR bodies with the attribution lines given in the conversation's system-reminder, when one is present.","schema":{"name":"Bash","description":"Executes a bash command and returns its output.\n\n- Working directory persists between calls, but prefer absolute paths — `cd` in a compound command can trigger a permission prompt. Shell state (env vars, functions) does not persist; the shell is initialized from the user's profile.\n- IMPORTANT: Avoid using this tool to run `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands, unless explicitly instructed or after you have verified that a dedicated tool cannot accomplish your task. Instead, use the appropriate dedicated tool as this will provide a much better experience for the user.\n- Command output is displayed to you, not reliably to the user.\n- `timeout` is in milliseconds: default 120000, max 600000 for a foreground command.\n- `run_in_background` runs the command detached: it keeps running across turns and re-invokes you when it exits. With it, `timeout` is how long the command may run in the background (default 600000, max 7200000); at that limit it is stopped and you are re-invoked. No `&` needed.\n\n# Git\n- Interactive flags (`-i`, e.g. `git rebase -i`, `git add -i`) are not supported in this environment.\n- Use the `gh` CLI for GitHub operations (PRs, issues, API).\n- Commit or push only when the user asks. If on the default branch, branch first.\n- End git commit messages and PR bodies with the attribution lines given in the conversation's system-reminder, when one is present.","input_schema":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"command":{"description":"The command to execute","type":"string"},"timeout":{"description":"Optional timeout in milliseconds (max 600000 for a foreground command)","type":"number"},"description":{"description":"Clear, concise description of what this command does in active voice. Never use words like \"complex\" or \"risk\" in the description - just describe what it does.\n\nSay what the command does in plain words: do not echo the command's text, its flags, or file paths - the user reads this description, often without seeing the command.\n\nFor simple commands (git, npm, standard CLI tools), keep it brief (5-10 words):\n- ls → \"List files in current directory\"\n- git status → \"Show working tree status\"\n- npm install → \"Install package dependencies\"\n\nFor commands that are harder to parse at a glance (piped commands, obscure flags, etc.), add enough context to clarify what it does:\n- find . -name \"*.tmp\" -exec rm {} \\; → \"Find and delete all .tmp files recursively\"\n- git reset --hard origin/main → \"Discard all local changes and match remote main\"\n- curl -s url | jq '.data[]' → \"Fetch JSON from URL and extract data array elements\"","type":"string"},"run_in_background":{"description":"Set to true to run this command in the background. With it, `timeout` limits how long the command may run in the background before it is stopped (default 600000 ms, max 7200000 ms).","type":"boolean"},"dangerouslyDisableSandbox":{"description":"Set this to true to dangerously override sandbox mode and run commands without sandboxing.","type":"boolean"}},"required":["command"],"additionalProperties":false}}},{"name":"CronCreate","description":"Schedule a prompt to be enqueued at a future time. Use for both recurring schedules and one-shot reminders.\n\nUses standard 5-field cron in the user's local timezone: minute hour day-of-month month day-of-week. \"0 9 * * *\" means 9am local — no timezone conversion needed.\n\n## One-shot tasks (recurring: false)\n\nFor \"remind me at X\" or \"at