Add regex to reef #1

Merged
defunkt merged 11 commits from regex into main 2025-10-16 21:15:42 +00:00
2 changed files with 36 additions and 1 deletions
Showing only changes of commit 2be87c381d - Show all commits

View File

@ -495,6 +495,18 @@ function toBytecodeFromString(str: string): Bytecode /* throws */ {
bytecode.constants.push(toValue(null))
operandValue = bytecode.constants.length - 1
} else if (/^\/.*\/[a-z]*$/.test(operand)) {
// regex literal (/pattern/flags)
const lastSlash = operand.lastIndexOf('/')
const pattern = operand.slice(1, lastSlash)
const flags = operand.slice(lastSlash + 1)
try {
const regex = new RegExp(pattern, flags)
bytecode.constants.push(toValue(regex))
operandValue = bytecode.constants.length - 1
} catch (e) {
throw new Error(`Invalid regex literal: ${operand}`)
}
}else {
// Assume it's a variable name if it doesn't match any other pattern
// This allows emoji, Unicode, and other creative identifiers

View File

@ -102,6 +102,29 @@ test("EQ - equality comparison", async () => {
expect(await run(toBytecode(str2))).toEqual({ type: 'boolean', value: false })
})
test('EQ - equality with regexes', async () => {
const str = `
PUSH /cool/i
PUSH /cool/i
EQ
`
expect(await run(toBytecode(str))).toEqual({ type: 'boolean', value: true })
const str2 = `
PUSH /cool/
PUSH /cool/i
EQ
`
expect(await run(toBytecode(str2))).toEqual({ type: 'boolean', value: false })
const str3 = `
PUSH /not-cool/
PUSH /cool/
EQ
`
expect(await run(toBytecode(str3))).toEqual({ type: 'boolean', value: false })
})
test("NEQ - not equal comparison", async () => {
const str = `
PUSH 5