74 lines
1.5 KiB
TypeScript
74 lines
1.5 KiB
TypeScript
/**
|
|
* Demonstrates the ADD opcode working with both numbers and strings
|
|
*
|
|
* ADD now behaves like JavaScript's + operator:
|
|
* - If either operand is a string, it does string concatenation
|
|
* - Otherwise, it does numeric addition
|
|
*/
|
|
|
|
import { toBytecode, run } from "#reef"
|
|
|
|
// Numeric addition
|
|
const numericAdd = toBytecode(`
|
|
PUSH 10
|
|
PUSH 5
|
|
ADD
|
|
HALT
|
|
`)
|
|
|
|
console.log('Numeric addition (10 + 5):')
|
|
console.log(await run(numericAdd))
|
|
// Output: { type: 'number', value: 15 }
|
|
|
|
// String concatenation
|
|
const stringConcat = toBytecode(`
|
|
PUSH "hello"
|
|
PUSH " world"
|
|
ADD
|
|
HALT
|
|
`)
|
|
|
|
console.log('\nString concatenation ("hello" + " world"):')
|
|
console.log(await run(stringConcat))
|
|
// Output: { type: 'string', value: 'hello world' }
|
|
|
|
// Mixed: string + number
|
|
const mixedConcat = toBytecode(`
|
|
PUSH "count: "
|
|
PUSH 42
|
|
ADD
|
|
HALT
|
|
`)
|
|
|
|
console.log('\nMixed concatenation ("count: " + 42):')
|
|
console.log(await run(mixedConcat))
|
|
// Output: { type: 'string', value: 'count: 42' }
|
|
|
|
// Building a message
|
|
const buildMessage = toBytecode(`
|
|
PUSH "You have "
|
|
PUSH 3
|
|
ADD
|
|
PUSH " new messages"
|
|
ADD
|
|
HALT
|
|
`)
|
|
|
|
console.log('\nBuilding a message:')
|
|
console.log(await run(buildMessage))
|
|
// Output: { type: 'string', value: 'You have 3 new messages' }
|
|
|
|
// Computing then concatenating
|
|
const computeAndConcat = toBytecode(`
|
|
PUSH "Result: "
|
|
PUSH 10
|
|
PUSH 5
|
|
ADD
|
|
ADD
|
|
HALT
|
|
`)
|
|
|
|
console.log('\nComputing then concatenating ("Result: " + (10 + 5)):')
|
|
console.log(await run(computeAndConcat))
|
|
// Output: { type: 'string', value: 'Result: 15' }
|