redscript-mc 1.2.24 → 1.2.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/.github/workflows/publish-extension-on-ci.yml +1 -0
  2. package/dist/__tests__/cli.test.js +1 -1
  3. package/dist/__tests__/codegen.test.js +12 -6
  4. package/dist/__tests__/e2e.test.js +6 -6
  5. package/dist/__tests__/lowering.test.js +8 -8
  6. package/dist/__tests__/optimizer.test.js +31 -0
  7. package/dist/__tests__/stdlib-advanced.test.d.ts +4 -0
  8. package/dist/__tests__/stdlib-advanced.test.js +264 -0
  9. package/dist/__tests__/stdlib-math.test.d.ts +7 -0
  10. package/dist/__tests__/stdlib-math.test.js +352 -0
  11. package/dist/__tests__/stdlib-vec.test.d.ts +4 -0
  12. package/dist/__tests__/stdlib-vec.test.js +264 -0
  13. package/dist/ast/types.d.ts +17 -1
  14. package/dist/codegen/mcfunction/index.js +159 -18
  15. package/dist/codegen/var-allocator.d.ts +17 -0
  16. package/dist/codegen/var-allocator.js +33 -3
  17. package/dist/compile.d.ts +14 -0
  18. package/dist/compile.js +62 -5
  19. package/dist/index.js +20 -1
  20. package/dist/ir/types.d.ts +4 -0
  21. package/dist/lexer/index.d.ts +1 -1
  22. package/dist/lexer/index.js +1 -0
  23. package/dist/lowering/index.d.ts +5 -0
  24. package/dist/lowering/index.js +83 -10
  25. package/dist/optimizer/dce.js +21 -5
  26. package/dist/optimizer/passes.js +18 -6
  27. package/dist/optimizer/structure.js +7 -0
  28. package/dist/parser/index.d.ts +5 -0
  29. package/dist/parser/index.js +43 -2
  30. package/dist/runtime/index.d.ts +6 -0
  31. package/dist/runtime/index.js +109 -9
  32. package/editors/vscode/package-lock.json +3 -3
  33. package/editors/vscode/package.json +1 -1
  34. package/package.json +1 -1
  35. package/src/__tests__/cli.test.ts +1 -1
  36. package/src/__tests__/codegen.test.ts +12 -6
  37. package/src/__tests__/e2e.test.ts +6 -6
  38. package/src/__tests__/lowering.test.ts +8 -8
  39. package/src/__tests__/optimizer.test.ts +33 -0
  40. package/src/__tests__/stdlib-advanced.test.ts +259 -0
  41. package/src/__tests__/stdlib-math.test.ts +374 -0
  42. package/src/__tests__/stdlib-vec.test.ts +259 -0
  43. package/src/ast/types.ts +11 -1
  44. package/src/codegen/mcfunction/index.ts +148 -19
  45. package/src/codegen/var-allocator.ts +36 -3
  46. package/src/compile.ts +72 -5
  47. package/src/index.ts +21 -1
  48. package/src/ir/types.ts +2 -0
  49. package/src/lexer/index.ts +2 -1
  50. package/src/lowering/index.ts +96 -10
  51. package/src/optimizer/dce.ts +22 -5
  52. package/src/optimizer/passes.ts +18 -5
  53. package/src/optimizer/structure.ts +6 -1
  54. package/src/parser/index.ts +47 -2
  55. package/src/runtime/index.ts +108 -10
  56. package/src/stdlib/advanced.mcrs +249 -0
  57. package/src/stdlib/math.mcrs +259 -19
  58. package/src/stdlib/vec.mcrs +246 -0
@@ -106,6 +106,8 @@ const BUILTINS: Record<string, (args: string[]) => string | null> = {
106
106
  setTimeout: () => null, // Special handling
107
107
  setInterval: () => null, // Special handling
108
108
  clearInterval: () => null, // Special handling
109
+ storage_get_int: () => null, // Special handling (dynamic NBT array read via macro)
110
+ storage_set_array: () => null, // Special handling (write literal NBT array to storage)
109
111
  }
110
112
 
111
113
  export interface Warning {
@@ -215,6 +217,14 @@ export class Lowering {
215
217
  private implMethods: Map<string, Map<string, { fn: FnDecl; loweredName: string }>> = new Map()
216
218
  private specializedFunctions: Map<string, string> = new Map()
217
219
  private currentFn: string = ''
220
+
221
+ /** Unique IR variable name for a local variable, scoped to the current function.
222
+ * Prevents cross-function scoreboard slot collisions: $fn_x ≠ $gn_x.
223
+ * Only applies to user-defined locals/params; internal slots ($p0, $ret) are
224
+ * intentionally global (calling convention). */
225
+ private fnVar(name: string): string {
226
+ return `$${this.currentFn}_${name}`
227
+ }
218
228
  private currentStdlibCallSite?: StdlibCallSiteContext
219
229
  private foreachCounter: number = 0
220
230
  private lambdaCounter: number = 0
@@ -617,12 +627,12 @@ export class Lowering {
617
627
  continue
618
628
  }
619
629
 
620
- this.varMap.set(param.name, `$${param.name}`)
630
+ this.varMap.set(param.name, this.fnVar(param.name))
621
631
  }
622
632
  } else {
623
633
  for (const param of runtimeParams) {
624
634
  const paramName = param.name
625
- this.varMap.set(paramName, `$${paramName}`)
635
+ this.varMap.set(paramName, this.fnVar(paramName))
626
636
  this.varTypes.set(paramName, this.normalizeType(param.type))
627
637
  }
628
638
  }
@@ -635,11 +645,15 @@ export class Lowering {
635
645
  // Start entry block
636
646
  this.builder.startBlock('entry')
637
647
 
638
- // Copy params from $p0, $p1, ... to named variables
648
+ // Copy params from the parameter-passing slots to named local variables.
649
+ // Use { kind: 'param', index: i } so the codegen resolves to
650
+ // alloc.internal('p{i}') consistently in both mangle and no-mangle modes,
651
+ // avoiding the slot-collision between the internal register and a user variable
652
+ // named 'p0'/'p1' that occurred with { kind: 'var', name: '$p0' }.
639
653
  for (let i = 0; i < runtimeParams.length; i++) {
640
654
  const paramName = runtimeParams[i].name
641
- const varName = `$${paramName}`
642
- this.builder.emitAssign(varName, { kind: 'var', name: `$p${i}` })
655
+ const varName = this.fnVar(paramName)
656
+ this.builder.emitAssign(varName, { kind: 'param', index: i })
643
657
  }
644
658
 
645
659
  if (staticEventDec) {
@@ -647,7 +661,7 @@ export class Lowering {
647
661
  const param = fn.params[i]
648
662
  const expected = eventParamSpecs[i]
649
663
  if (expected?.type.kind === 'named' && expected.type.name !== 'string') {
650
- this.builder.emitAssign(`$${param.name}`, { kind: 'const', value: 0 })
664
+ this.builder.emitAssign(this.fnVar(param.name), { kind: 'const', value: 0 })
651
665
  }
652
666
  }
653
667
  }
@@ -716,6 +730,23 @@ export class Lowering {
716
730
  irFn.isLoadInit = true
717
731
  }
718
732
 
733
+ // @requires("dep_fn") — when this function is compiled in, dep_fn is also
734
+ // called from __load. The dep_fn itself does NOT need @load; it can be a
735
+ // private (_) function that only runs at load time when this fn is used.
736
+ const requiredLoads: string[] = []
737
+ for (const d of fn.decorators) {
738
+ if (d.name === 'require_on_load') {
739
+ for (const arg of d.rawArgs ?? []) {
740
+ if (arg.kind === 'string') {
741
+ requiredLoads.push(arg.value)
742
+ }
743
+ }
744
+ }
745
+ }
746
+ if (requiredLoads.length > 0) {
747
+ irFn.requiredLoads = requiredLoads
748
+ }
749
+
719
750
  // Handle tick rate counter if needed
720
751
  if (tickRate && tickRate > 1) {
721
752
  this.wrapWithTickRate(irFn, tickRate)
@@ -860,7 +891,7 @@ export class Lowering {
860
891
  )
861
892
  }
862
893
 
863
- const varName = `$${stmt.name}`
894
+ const varName = this.fnVar(stmt.name)
864
895
  this.varMap.set(stmt.name, varName)
865
896
 
866
897
  // Track variable type
@@ -1196,7 +1227,7 @@ export class Lowering {
1196
1227
  }
1197
1228
 
1198
1229
  private lowerForRangeStmt(stmt: Extract<Stmt, { kind: 'for_range' }>): void {
1199
- const loopVar = `$${stmt.varName}`
1230
+ const loopVar = this.fnVar(stmt.varName)
1200
1231
  const subFnName = `${this.currentFn}/__for_${this.foreachCounter++}`
1201
1232
 
1202
1233
  // Initialize loop variable
@@ -1385,7 +1416,7 @@ export class Lowering {
1385
1416
  }
1386
1417
 
1387
1418
  const arrayType = this.inferExprType(stmt.iterable)
1388
- const bindingVar = `$${stmt.binding}`
1419
+ const bindingVar = this.fnVar(stmt.binding)
1389
1420
  const indexVar = this.builder.freshTemp()
1390
1421
  const lengthVar = this.builder.freshTemp()
1391
1422
  const condVar = this.builder.freshTemp()
@@ -2543,6 +2574,61 @@ export class Lowering {
2543
2574
  return { kind: 'var', name: dst }
2544
2575
  }
2545
2576
 
2577
+ // storage_get_int(storage_ns, array_key, index) -> int
2578
+ // Reads one element from an NBT int-array stored in data storage.
2579
+ // storage_ns : e.g. "math:tables"
2580
+ // array_key : e.g. "sin"
2581
+ // index : integer index (const or runtime)
2582
+ //
2583
+ // Const index: execute store result score $dst rs run data get storage math:tables sin[N] 1
2584
+ // Runtime index: macro sub-function via rs:heap, mirrors readArrayElement.
2585
+ if (name === 'storage_get_int') {
2586
+ const storageNs = this.exprToString(args[0]) // "math:tables"
2587
+ const arrayKey = this.exprToString(args[1]) // "sin"
2588
+ const indexOperand = this.lowerExpr(args[2])
2589
+ const dst = this.builder.freshTemp()
2590
+
2591
+ if (indexOperand.kind === 'const') {
2592
+ this.builder.emitRaw(
2593
+ `execute store result score ${dst} rs run data get storage ${storageNs} ${arrayKey}[${indexOperand.value}] 1`
2594
+ )
2595
+ } else {
2596
+ // Runtime index: store the index into rs:heap under a unique key,
2597
+ // then call a macro sub-function that uses $(key) to index the array.
2598
+ const macroKey = `__sgi_${this.foreachCounter++}`
2599
+ const subFnName = `${this.currentFn}/__sgi_${this.foreachCounter++}`
2600
+ const indexVar = indexOperand.kind === 'var'
2601
+ ? indexOperand.name
2602
+ : this.operandToVar(indexOperand)
2603
+ this.builder.emitRaw(
2604
+ `execute store result storage rs:heap ${macroKey} int 1 run scoreboard players get ${indexVar} rs`
2605
+ )
2606
+ this.builder.emitRaw(`function ${this.namespace}:${subFnName} with storage rs:heap`)
2607
+ // Prefix \x01 is a sentinel for the MC macro '$' line-start marker.
2608
+ // We avoid using literal '$execute' here so the pre-alloc pass
2609
+ // doesn't mistakenly register 'execute' as a scoreboard variable.
2610
+ // Codegen replaces \x01 → '$' when emitting the mc function file.
2611
+ this.emitRawSubFunction(
2612
+ subFnName,
2613
+ `\x01execute store result score ${dst} rs run data get storage ${storageNs} ${arrayKey}[$(${macroKey})] 1`
2614
+ )
2615
+ }
2616
+ return { kind: 'var', name: dst }
2617
+ }
2618
+
2619
+ // storage_set_array(storage_ns, array_key, nbt_array_literal)
2620
+ // Writes a literal NBT int array to data storage (used in @load for tables).
2621
+ // storage_set_array("math:tables", "sin", "[0, 17, 35, ...]")
2622
+ if (name === 'storage_set_array') {
2623
+ const storageNs = this.exprToString(args[0])
2624
+ const arrayKey = this.exprToString(args[1])
2625
+ const nbtLiteral = this.exprToString(args[2])
2626
+ this.builder.emitRaw(
2627
+ `data modify storage ${storageNs} ${arrayKey} set value ${nbtLiteral}`
2628
+ )
2629
+ return { kind: 'const', value: 0 }
2630
+ }
2631
+
2546
2632
  // data_merge(target, nbt) — merge NBT into entity/block/storage
2547
2633
  // data_merge(@s, { Invisible: 1b, Silent: 1b })
2548
2634
  if (name === 'data_merge') {
@@ -3447,7 +3533,7 @@ export class Lowering {
3447
3533
  this.builder.emitRaw(`function ${this.namespace}:${subFnName} with storage rs:heap`)
3448
3534
  this.emitRawSubFunction(
3449
3535
  subFnName,
3450
- `$execute store result score ${dst} rs run data get storage rs:heap ${arrayName}[$(${macroKey})]`
3536
+ `\x01execute store result score ${dst} rs run data get storage rs:heap ${arrayName}[$(${macroKey})]`
3451
3537
  )
3452
3538
  return { kind: 'var', name: dst }
3453
3539
  }
@@ -134,13 +134,18 @@ export class DeadCodeEliminator {
134
134
  const entries = new Set<string>()
135
135
 
136
136
  for (const fn of program.declarations) {
137
- // All top-level functions are entry points (callable via /function)
138
- // Exception: functions starting with _ are considered private/internal
139
- if (!fn.name.startsWith('_')) {
140
- entries.add(fn.name)
137
+ // Library functions (from `module library;` or `librarySources`) are
138
+ // NOT MC entry points they're only kept if reachable from user code.
139
+ // Exception: decorators like @tick / @load / @on / @keep always force inclusion.
140
+ if (!fn.isLibraryFn) {
141
+ // All top-level non-library functions are entry points (callable via /function)
142
+ // Exception: functions starting with _ are considered private/internal
143
+ if (!fn.name.startsWith('_')) {
144
+ entries.add(fn.name)
145
+ }
141
146
  }
142
147
 
143
- // Decorated functions are always entry points (even if prefixed with _)
148
+ // Decorated functions are always entry points regardless of library mode or _ prefix
144
149
  if (fn.decorators.some(decorator => [
145
150
  'tick',
146
151
  'load',
@@ -172,6 +177,18 @@ export class DeadCodeEliminator {
172
177
 
173
178
  this.reachableFunctions.add(fnName)
174
179
  this.collectFunctionRefs(fn)
180
+
181
+ // @requires("dep") — when fn is reachable, its required dependencies are
182
+ // also pulled into the reachable set so they survive DCE.
183
+ for (const decorator of fn.decorators) {
184
+ if (decorator.name === 'require_on_load') {
185
+ for (const arg of decorator.rawArgs ?? []) {
186
+ if (arg.kind === 'string') {
187
+ this.markReachable(arg.value)
188
+ }
189
+ }
190
+ }
191
+ }
175
192
  }
176
193
 
177
194
  private collectFunctionRefs(fn: FnDecl): void {
@@ -95,30 +95,43 @@ export function copyPropagation(fn: IRFunction): IRFunction {
95
95
  return copies.get(op.name) ?? op
96
96
  }
97
97
 
98
+ /**
99
+ * Invalidate all copies that became stale because `written` was modified.
100
+ * When $y is overwritten, any mapping copies[$tmp] = $y is now stale:
101
+ * reading $tmp would return the OLD $y value via the copy, but $y now holds
102
+ * a different value. Remove both the direct entry (copies[$y]) and every
103
+ * reverse entry that points at $y.
104
+ */
105
+ function invalidate(written: string): void {
106
+ copies.delete(written)
107
+ for (const [k, v] of copies) {
108
+ if (v.kind === 'var' && v.name === written) copies.delete(k)
109
+ }
110
+ }
111
+
98
112
  const newInstrs: IRInstr[] = []
99
113
  for (const instr of block.instrs) {
100
114
  switch (instr.op) {
101
115
  case 'assign': {
102
116
  const src = resolve(instr.src)
117
+ invalidate(instr.dst)
103
118
  // Only propagate scalars (var or const), not storage
104
119
  if (src.kind === 'var' || src.kind === 'const') {
105
120
  copies.set(instr.dst, src)
106
- } else {
107
- copies.delete(instr.dst)
108
121
  }
109
122
  newInstrs.push({ ...instr, src })
110
123
  break
111
124
  }
112
125
  case 'binop':
113
- copies.delete(instr.dst)
126
+ invalidate(instr.dst)
114
127
  newInstrs.push({ ...instr, lhs: resolve(instr.lhs), rhs: resolve(instr.rhs) })
115
128
  break
116
129
  case 'cmp':
117
- copies.delete(instr.dst)
130
+ invalidate(instr.dst)
118
131
  newInstrs.push({ ...instr, lhs: resolve(instr.lhs), rhs: resolve(instr.rhs) })
119
132
  break
120
133
  case 'call':
121
- if (instr.dst) copies.delete(instr.dst)
134
+ if (instr.dst) invalidate(instr.dst)
122
135
  newInstrs.push({ ...instr, args: instr.args.map(resolve) })
123
136
  break
124
137
  default:
@@ -24,7 +24,8 @@ function varRef(name: string): string {
24
24
  function operandToScore(op: Operand): string {
25
25
  if (op.kind === 'var') return `${varRef(op.name)} ${OBJ}`
26
26
  if (op.kind === 'const') return `$const_${op.value} ${OBJ}`
27
- throw new Error(`Cannot convert storage operand to score: ${op.path}`)
27
+ if (op.kind === 'param') return `$p${op.index} ${OBJ}`
28
+ throw new Error(`Cannot convert storage operand to score: ${(op as any).path}`)
28
29
  }
29
30
 
30
31
  function emitInstr(instr: IRInstr, namespace: string): IRCommand[] {
@@ -38,6 +39,10 @@ function emitInstr(instr: IRInstr, namespace: string): IRCommand[] {
38
39
  commands.push({
39
40
  cmd: `scoreboard players operation ${varRef(instr.dst)} ${OBJ} = ${varRef(instr.src.name)} ${OBJ}`,
40
41
  })
42
+ } else if (instr.src.kind === 'param') {
43
+ commands.push({
44
+ cmd: `scoreboard players operation ${varRef(instr.dst)} ${OBJ} = $p${instr.src.index} ${OBJ}`,
45
+ })
41
46
  } else {
42
47
  commands.push({
43
48
  cmd: `execute store result score ${varRef(instr.dst)} ${OBJ} run data get storage ${instr.src.path}`,
@@ -76,6 +76,11 @@ export class Parser {
76
76
  private pos: number = 0
77
77
  private sourceLines: string[]
78
78
  private filePath?: string
79
+ /** Set to true once `module library;` is seen — all subsequent fn declarations
80
+ * will be marked isLibraryFn=true. When library sources are parsed via the
81
+ * `librarySources` compile option, each source is parsed by its own fresh
82
+ * Parser instance, so this flag never bleeds into user code. */
83
+ private inLibraryMode: boolean = false
79
84
 
80
85
  constructor(tokens: Token[], source?: string, filePath?: string) {
81
86
  this.tokens = tokens
@@ -169,6 +174,7 @@ export class Parser {
169
174
  const implBlocks: ImplBlock[] = []
170
175
  const enums: EnumDecl[] = []
171
176
  const consts: ConstDecl[] = []
177
+ let isLibrary = false
172
178
 
173
179
  // Check for namespace declaration
174
180
  if (this.check('namespace')) {
@@ -178,6 +184,20 @@ export class Parser {
178
184
  this.expect(';')
179
185
  }
180
186
 
187
+ // Check for module declaration: `module library;`
188
+ // Library-mode: all functions parsed from this point are marked isLibraryFn=true.
189
+ // When using the `librarySources` compile option, each library source is parsed
190
+ // by its own fresh Parser — so this flag never bleeds into user code.
191
+ if (this.check('module')) {
192
+ this.advance()
193
+ const modKind = this.expect('ident')
194
+ if (modKind.value === 'library') {
195
+ isLibrary = true
196
+ this.inLibraryMode = true
197
+ }
198
+ this.expect(';')
199
+ }
200
+
181
201
  // Parse struct and function declarations
182
202
  while (!this.check('eof')) {
183
203
  if (this.check('let')) {
@@ -199,7 +219,7 @@ export class Parser {
199
219
  }
200
220
  }
201
221
 
202
- return { namespace, globals, declarations, structs, implBlocks, enums, consts }
222
+ return { namespace, globals, declarations, structs, implBlocks, enums, consts, isLibrary }
203
223
  }
204
224
 
205
225
  // -------------------------------------------------------------------------
@@ -322,7 +342,11 @@ export class Parser {
322
342
 
323
343
  const body = this.parseBlock()
324
344
 
325
- return this.withLoc({ name, params, returnType, decorators, body }, fnToken)
345
+ const fn: import('../ast/types').FnDecl = this.withLoc(
346
+ { name, params, returnType, decorators, body, isLibraryFn: this.inLibraryMode || undefined },
347
+ fnToken,
348
+ )
349
+ return fn
326
350
  }
327
351
 
328
352
  /** Parse a `declare fn name(params): returnType;` stub — no body, just discard. */
@@ -397,6 +421,27 @@ export class Parser {
397
421
  }
398
422
  }
399
423
 
424
+ // @require_on_load(fn_name) — when this fn is used, fn_name is called from __load.
425
+ // Accepts bare identifiers (with optional leading _) or quoted strings.
426
+ if (name === 'require_on_load') {
427
+ const rawArgs: NonNullable<Decorator['rawArgs']> = []
428
+ for (const part of argsStr.split(',')) {
429
+ const trimmed = part.trim()
430
+ // Bare identifier: @require_on_load(_math_init)
431
+ const identMatch = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)$/)
432
+ if (identMatch) {
433
+ rawArgs.push({ kind: 'string', value: identMatch[1] })
434
+ } else {
435
+ // Quoted string fallback: @require_on_load("_math_init")
436
+ const strMatch = trimmed.match(/^"([^"]*)"$/)
437
+ if (strMatch) {
438
+ rawArgs.push({ kind: 'string', value: strMatch[1] })
439
+ }
440
+ }
441
+ }
442
+ return { name, rawArgs }
443
+ }
444
+
400
445
  // Handle key=value format (e.g., rate=20)
401
446
  for (const part of argsStr.split(',')) {
402
447
  const [key, val] = part.split('=').map(s => s.trim())
@@ -266,6 +266,9 @@ export class MCRuntime {
266
266
  // Flag to stop function execution (for return)
267
267
  private shouldReturn: boolean = false
268
268
 
269
+ // Current MC macro context: key → value (set by 'function ... with storage')
270
+ private currentMacroContext: Record<string, any> | null = null
271
+
269
272
  constructor(namespace: string) {
270
273
  this.namespace = namespace
271
274
  // Initialize default objective
@@ -363,6 +366,13 @@ export class MCRuntime {
363
366
  cmd = cmd.trim()
364
367
  if (!cmd || cmd.startsWith('#')) return true
365
368
 
369
+ // MC macro command: line starts with '$'.
370
+ // Expand $(key) placeholders from currentMacroContext, then execute.
371
+ if (cmd.startsWith('$')) {
372
+ const expanded = this.expandMacro(cmd.slice(1))
373
+ return this.execCommand(expanded, executor)
374
+ }
375
+
366
376
  // Parse command
367
377
  if (cmd.startsWith('scoreboard ')) {
368
378
  return this.execScoreboard(cmd)
@@ -542,7 +552,10 @@ export class MCRuntime {
542
552
  // Track execute state
543
553
  let currentExecutor = executor
544
554
  let condition: boolean = true
545
- let storeTarget: { player: string; objective: string; type: 'result' | 'success' } | null = null
555
+ let storeTarget:
556
+ | { player: string; objective: string; type: 'result' | 'success' }
557
+ | { storagePath: string; field: string; type: 'result' }
558
+ | null = null
546
559
 
547
560
  while (rest.length > 0) {
548
561
  rest = rest.trimStart()
@@ -557,7 +570,11 @@ export class MCRuntime {
557
570
  const value = storeTarget.type === 'result'
558
571
  ? (this.returnValue ?? (result ? 1 : 0))
559
572
  : (result ? 1 : 0)
560
- this.setScore(storeTarget.player, storeTarget.objective, value)
573
+ if ('storagePath' in storeTarget) {
574
+ this.setStorageField(storeTarget.storagePath, storeTarget.field, value)
575
+ } else {
576
+ this.setScore(storeTarget.player, storeTarget.objective, value)
577
+ }
561
578
  }
562
579
 
563
580
  return result
@@ -630,15 +647,34 @@ export class MCRuntime {
630
647
  // Handle 'unless score ...'
631
648
  if (rest.startsWith('unless score ')) {
632
649
  rest = rest.slice(13)
633
- const scoreParts = rest.match(/^(\S+)\s+(\S+)\s+matches\s+(\S+)(.*)$/)
634
- if (scoreParts) {
635
- const [, player, obj, rangeStr, remaining] = scoreParts
650
+ // unless score <player> <obj> matches <range>
651
+ const matchesParts = rest.match(/^(\S+)\s+(\S+)\s+matches\s+(\S+)(.*)$/)
652
+ if (matchesParts) {
653
+ const [, player, obj, rangeStr, remaining] = matchesParts
636
654
  const range = parseRange(rangeStr)
637
655
  const score = this.getScore(player, obj)
638
656
  condition = condition && !matchesRange(score, range)
639
657
  rest = remaining.trim()
640
658
  continue
641
659
  }
660
+ // unless score <p1> <o1> <op> <p2> <o2>
661
+ const compareMatch = rest.match(/^(\S+)\s+(\S+)\s+([<>=]+)\s+(\S+)\s+(\S+)(.*)$/)
662
+ if (compareMatch) {
663
+ const [, p1, o1, op, p2, o2, remaining] = compareMatch
664
+ const v1 = this.getScore(p1, o1)
665
+ const v2 = this.getScore(p2, o2)
666
+ let matches = false
667
+ switch (op) {
668
+ case '=': matches = v1 === v2; break
669
+ case '<': matches = v1 < v2; break
670
+ case '<=': matches = v1 <= v2; break
671
+ case '>': matches = v1 > v2; break
672
+ case '>=': matches = v1 >= v2; break
673
+ }
674
+ condition = condition && !matches // unless = negate
675
+ rest = remaining.trim()
676
+ continue
677
+ }
642
678
  }
643
679
 
644
680
  // Handle 'if entity <selector>'
@@ -661,6 +697,19 @@ export class MCRuntime {
661
697
  continue
662
698
  }
663
699
 
700
+ // Handle 'store result storage <ns:path> <field> <type> <scale>'
701
+ if (rest.startsWith('store result storage ')) {
702
+ rest = rest.slice(21)
703
+ // format: <ns:path> <field> <type> <scale> <run-cmd>
704
+ const storageParts = rest.match(/^(\S+)\s+(\S+)\s+(\S+)\s+([\d.]+)\s+(.*)$/)
705
+ if (storageParts) {
706
+ const [, storagePath, field, , , remaining] = storageParts
707
+ storeTarget = { storagePath, field, type: 'result' }
708
+ rest = remaining.trim()
709
+ continue
710
+ }
711
+ }
712
+
664
713
  // Handle 'store result score <player> <obj>'
665
714
  if (rest.startsWith('store result score ')) {
666
715
  rest = rest.slice(19)
@@ -695,7 +744,11 @@ export class MCRuntime {
695
744
  const value = storeTarget.type === 'result'
696
745
  ? (this.returnValue ?? (condition ? 1 : 0))
697
746
  : (condition ? 1 : 0)
698
- this.setScore(storeTarget.player, storeTarget.objective, value)
747
+ if ('storagePath' in storeTarget) {
748
+ this.setStorageField(storeTarget.storagePath, storeTarget.field, value)
749
+ } else {
750
+ this.setScore(storeTarget.player, storeTarget.objective, value)
751
+ }
699
752
  }
700
753
 
701
754
  return condition
@@ -721,13 +774,39 @@ export class MCRuntime {
721
774
  // -------------------------------------------------------------------------
722
775
 
723
776
  private execFunctionCmd(cmd: string, executor?: Entity): boolean {
724
- const fnName = cmd.slice(9).trim() // remove 'function '
777
+ let fnRef = cmd.slice(9).trim() // remove 'function '
778
+
779
+ // Handle 'function ns:name with storage ns:path' — MC macro calling convention.
780
+ // The called function may have $( ) placeholders that need to be expanded
781
+ // using the provided storage compound. We execute the function after
782
+ // expanding its macro context.
783
+ const withStorageMatch = fnRef.match(/^(\S+)\s+with\s+storage\s+(\S+)$/)
784
+ if (withStorageMatch) {
785
+ const [, actualFnName, storagePath] = withStorageMatch
786
+ const macroContext = this.getStorageCompound(storagePath) ?? {}
787
+ const outerShouldReturn = this.shouldReturn
788
+ const outerMacroCtx = this.currentMacroContext
789
+ this.currentMacroContext = macroContext
790
+ this.execFunction(actualFnName, executor)
791
+ this.currentMacroContext = outerMacroCtx
792
+ this.shouldReturn = outerShouldReturn
793
+ return true
794
+ }
795
+
725
796
  const outerShouldReturn = this.shouldReturn
726
- this.execFunction(fnName, executor)
797
+ this.execFunction(fnRef, executor)
727
798
  this.shouldReturn = outerShouldReturn
728
799
  return true
729
800
  }
730
801
 
802
+ /** Expand MC macro placeholders: $(key) → value from currentMacroContext */
803
+ private expandMacro(cmd: string): string {
804
+ return cmd.replace(/\$\(([^)]+)\)/g, (_, key) => {
805
+ const val = this.currentMacroContext?.[key]
806
+ return val !== undefined ? String(val) : `$(${key})`
807
+ })
808
+ }
809
+
731
810
  // -------------------------------------------------------------------------
732
811
  // Data Commands
733
812
  // -------------------------------------------------------------------------
@@ -755,8 +834,19 @@ export class MCRuntime {
755
834
  return true
756
835
  }
757
836
 
758
- // data get storage <ns:path> <field>
759
- const getMatch = cmd.match(/^data get storage (\S+) (\S+)$/)
837
+ // data get storage <ns:path> <field>[<index>] [scale] (array element access)
838
+ const getArrMatch = cmd.match(/^data get storage (\S+) (\S+)\[(\d+)\](?:\s+[\d.]+)?$/)
839
+ if (getArrMatch) {
840
+ const [, storagePath, field, indexStr] = getArrMatch
841
+ const arr = this.getStorageField(storagePath, field)
842
+ const idx = parseInt(indexStr, 10)
843
+ const value = Array.isArray(arr) ? arr[idx] : undefined
844
+ this.returnValue = typeof value === 'number' ? value : 0
845
+ return true
846
+ }
847
+
848
+ // data get storage <ns:path> <field> [scale]
849
+ const getMatch = cmd.match(/^data get storage (\S+) (\S+)(?:\s+[\d.]+)?$/)
760
850
  if (getMatch) {
761
851
  const [, storagePath, field] = getMatch
762
852
  const value = this.getStorageField(storagePath, field)
@@ -803,6 +893,14 @@ export class MCRuntime {
803
893
  }
804
894
  }
805
895
 
896
+ /** Return the whole storage compound at storagePath as a flat key→value map.
897
+ * Used by 'function ... with storage' to provide macro context. */
898
+ private getStorageCompound(storagePath: string): Record<string, any> | null {
899
+ const data = this.storage.get(storagePath)
900
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null
901
+ return data as Record<string, any>
902
+ }
903
+
806
904
  private getStorageField(storagePath: string, field: string): any {
807
905
  const data = this.storage.get(storagePath) ?? {}
808
906
  const segments = this.parseStoragePath(field)