import type { TimeArgument } from 'sandstone/arguments/basics' import type { NBTObject, NBTSerializable } from 'sandstone/arguments/nbt' import type { ScheduleType } from 'sandstone/commands' import type { FinalCommandOutput } from 'sandstone/commands/helpers' import type { ContainerCommandNode, MacroArgument, Node, ResourceClassArguments, ResourceNode, SandstoneCore, } from 'sandstone/core' import { formatDebugString, makeCallable, makeClassCallable } from 'sandstone/utils' import * as util from 'util' import type { MakeInstanceCallable } from '../../../utils' import { ResolveNBTPart } from '../../../variables/ResolveNBT' import { AwaitNode, ContainerNode } from '../../nodes' import { CallableResourceClass } from '../resource' import { TagClass } from './tag' import type { DataPointClass } from 'sandstone/variables' // interface AttributeWrapper { // attributes: string[] // } // type MapperA2 = { // [Index in keyof Wrapper['attributes']]: Wrapper['attributes'][Index] // } /** * A node representing a Minecraft function. */ export class MCFunctionNode extends ContainerNode implements ResourceNode { contextStack: (ContainerNode | ContainerCommandNode)[] constructor( sandstoneCore: SandstoneCore, public resource: MCFunctionClass, ) { super(sandstoneCore) this.contextStack = [this] } /** * Sandstone-created child MCFunctions extracted from this MCFunction's * body by `ContainerCommandsToMCFunctionVisitor`. Populated lazily as * the visitor walks the tree and extracts execute bodies whose contents * exceed the 1-child constraint. Lets visitors iterate transient * helpers in O(n) over the children of a single MCFunction instead of * O(n²) over `core.resourceNodes`. * * @internal */ transientChildMCFunctions: Set = new Set() /** * The currently active context. * * For example, the current context is the function body if the function is not in a loop. * If the function is in a loop, the current context is the loop body. * * @internal */ get currentContext() { return this.contextStack[this.contextStack.length - 1] } /** * Sequentially add node(s) to the end of the body of the function. * * @param node The node(s) to add. * * @internal */ appendNode = (node: Node | Node[]) => { if (Array.isArray(node)) { for (const _node of node) { this.currentContext.append(_node) } } else { this.currentContext.append(node) } } /** * Sequentially add node(s) to the beginning of the body of the function. * * @param node The node(s) to add. * * @internal */ prependNode = (node: Node | Node[]) => { if (Array.isArray(node)) { for (const _node of node) { this.currentContext.prepend(_node) } } else { this.currentContext.prepend(node) } } /** * Switch the current context to the given node. * Also adds the node to the body of the current context, except if addNode is False. * * @param node The node to switch to. * @param addNode Whether to add the node to the body of the current context. * * @internal */ enterContext = (node: ContainerNode | ContainerCommandNode, addNode: boolean = true) => { if (addNode) { this.currentContext.append(node) // For an AwaitNode being appended, the "parent MCFunction" is // whichever MCFunction directly contains the IMMEDIATE container of // the await — e.g. for a second `_.await.until(...)` placed inside // the first await's post-await body, the second await's parent is // the first await's continuation mcfunction (not the outermost // mcfunction the user wrote). Walk the contextStack from the top: // if we hit an AwaitNode first, its `mcfunction` (the continuation) // is the parent; otherwise the nearest MCFunctionNode wins. if (node instanceof AwaitNode && node.parentMCFunction === undefined) { let parent: MCFunctionNode | undefined // Walk the stack EXCLUDING the node we're about to push (we want // the parent's container, not ourselves). for (let i = this.contextStack.length - 1; i >= 0; i--) { const ctx = this.contextStack[i] if (ctx instanceof AwaitNode) { parent = ctx.mcfunction?.node break } if (ctx instanceof MCFunctionNode) { parent = ctx break } } node.parentMCFunction = parent } } this.contextStack.push(node) } /** * Switch the current context to the given node, run the given function, and switch back to the original context. * Also adds the node to the body of the current context, except if addNode is False. * * @param node The node to switch to. * @param callback The function to run. * @param addNode Whether to add the node to the body of the current context. * * @return The previously active context. * @throws Error if there is no previous context. * * @internal */ insideContext = (node: ContainerNode | ContainerCommandNode, callback: () => void, addNode: boolean = true) => { this.enterContext(node, addNode) callback() return this.exitContext() } /** * Enters `node`'s context, runs `callback`, then pops the entire stack * back to the pre-enter depth (not just one level). * * Use this when the callback may contain awaits — `_.await.until(...)` * inside the callback calls `enterContext(this=UntilClass)` and never * pops itself, so a single `exitContext()` here would leave the await's * `UntilClass` (or the wrapper `ExecuteCommandNode` it was nested * inside) on the stack, causing subsequent commands to commit to the * wrong body. * * Mirrors the `while (length > preDepth) exit()` pattern that * `FlowClauseNode.append` and the various flow-node constructors * already use for the same reason (see CLAUDE.md "MCFunction Context * System"). Prefer calling this over open-coding the while-loop. * * @internal */ balanceContext = (node: ContainerNode | ContainerCommandNode, callback: () => void, addNode: boolean = true) => { const beforeIn = this.contextStack.length this.enterContext(node, addNode) callback() this.popToDepth(beforeIn) return this.contextStack[this.contextStack.length - 1] } /** * Pop the context stack until its length equals `depth`. No-op if the * stack is already at or below `depth`. Used by `balanceContext` and by * split enter/exit patterns (e.g. `FlowClauseNode.append`) where the * "exit" happens in a different method than the "enter". * * @internal */ popToDepth = (depth: number) => { while (this.contextStack.length > depth) { this.exitContext() } } /** * Leave the current context, and return to the previous one. * * @return The previously active context. * @throws Error if there is no previous context. * * @internal */ exitContext = () => { if (this.contextStack.length === 0) { throw new Error('No previous context to return to.') } if (this.contextStack.length === 1) { throw new Error( 'It is forbidden for a MCFunction to exit its latest context, since the MCFunction itself must be in the context stack.', ) } return this.contextStack.pop() } getValue = () => { this.sandstoneCore.currentNode = this.resource.name return this.body .filter((node) => node.getValue() !== null) .map((node) => node.getValue()) .join('\n') }; [util.inspect.custom](_depth: number, options: any) { return formatDebugString( this.constructor.name, { name: this.resource.name, }, this.body, options.indent, ) } } export type MCFunctionClassArguments = { /** * The callback to run when the MCFunction is generated. * * @default () => {} */ callback?: (...params: [loop: MCFunctionClass, ...params: MacroArgument[]]) => void /** * If true, then the function will only be created if it is called from another function. */ lazy?: boolean /** * Whether the function should run when the datapack loads. * * Defaults to `true` if `runEvery` is specified, else `false`. * * Incompatible with macro parameters. */ runOnLoad?: boolean /** * The function tags to put this function in. */ tags?: readonly (string | TagClass<'function'>)[] /** * If specified, the function will run every given time. * * If `runOnLoad` is unspecified or `true`, then it will run on load too. * * If `runOnLoad` is `false`, you will have to manually start it. * * You can stop the automatic scheduling by running `theFunction.clearSchedule()`. * * Incompatible with macro parameters. * * @example * * // Run every 5 ticks, including on datapack load. * { * runEvery: 5, * } * * // Run every 5 ticks, but wait until 5 ticks after the datapack loads for 1st execution. * { * runEvery: 5, * runOnLoad: false, * } * * // Run every 8 seconds * { * runEvery: '8s' * } */ runEvery?: TimeArgument /** * Whether the function should run each tick. * * Incompatible with macro parameters. */ runEveryTick?: boolean /** * Optional. Whether to retain the execution context through async calls. Defaults to false. */ asyncContext?: boolean } & ResourceClassArguments<'function'> export class _RawMCFunctionClass< PARAMS extends readonly MacroArgument[] | undefined, ENV extends readonly MacroArgument[] | undefined, > extends CallableResourceClass implements NBTSerializable { static readonly resourceType = 'function' /* @internal */ public callback: NonNullable /* @internal */ nested = 0 public asyncContext: NonNullable tags: MCFunctionClassArguments['tags'] lazy: boolean readonly env?: ENV readonly macroPoint: ENV extends undefined ? PARAMS extends undefined ? undefined : DataPointClass<'storage'> : DataPointClass<'storage'> constructor(core: SandstoneCore, name: string, args: MCFunctionClassArguments, env?: ENV) { if (name.startsWith('./')) { // We have a relative name. const currentMCFunctionName = core.currentMCFunction?.resource.name if (!currentMCFunctionName) { throw new Error('Cannot use relative paths outside of an existing MCFunction.') } name = `${currentMCFunctionName}/${name.slice(2)}` } super( core, { packType: core.pack.dataPack(), extension: 'mcfunction' }, MCFunctionNode, _RawMCFunctionClass.resourceType, core.pack.resourceToPath(name, ['function']), { ...args, addToSandstoneCore: args.lazy ? false : args.addToSandstoneCore, }, ) this.callback = args.callback ?? (() => {}) if (this.nested !== 0) { // eslint-disable-next-line no-plusplus for (let i = 0; i < this.nested; i++) { this.node.exitContext() } } this.asyncContext = args.asyncContext === undefined ? false : args.asyncContext this.lazy = !!args.lazy this.addToSandstoneCore = !!args.addToSandstoneCore this.tags = args.tags if (env && env.length !== 0) { this.env = env } if (this.env || this.callback.length > 1) { this.macroPoint = core.pack.DataVariable() as any } else { this.macroPoint = undefined as any } if (args.runOnLoad) { this.addToTag(core.pack.loadTags.load) } else if (args.runEveryTick || args.runEvery) { const runEvery = args.runEvery ?? 1 core.pack.registerTicked(runEvery, this as unknown as MCFunctionClass) } if (args.tags) { for (const tag of args.tags) { this.addToTag(tag) } } this.handleConflicts() } private generated = false /** @internal */ generate = () => { if (this.generated) { return } this.generated = true this.push(this.callback.bind(undefined, makeCallable(this, this.__call__))) } addToTag = (tag: string | TagClass<'function'>) => { let func: MCFunctionClass if (this.env !== undefined) { func = this.core.pack.MCFunction(`${this.name}/tag_call`, { addToSandstoneCore: true, creator: 'sandstone', onConflict: 'rename', // @ts-ignore: this breaks functions with parameters callback: () => this.__call__(), }) } else { func = this as unknown as MCFunctionClass } if (typeof tag === 'string') { // Cache lives on SandstoneCore so its lifetime matches the core (cleared on reset). // This prevents stale TagClass references from a previous pack surviving across // watch-mode rebuilds and silently dropping the tag from the new build's output. const existing = this.core.functionTags.get(tag) if (existing) { existing.push(func) } else { const newTag = new TagClass(this.core, 'function', tag, { values: [func], addToSandstoneCore: true, creator: 'sandstone', onConflict: 'append', }) this.core.functionTags.set(tag, newTag) } } else { tag.push(func) } } __call__ = (..._params: PARAMS extends undefined ? [] : PARAMS): FinalCommandOutput => { if (this.env || _params.length !== 0) { const args: NBTObject = {} // Set up env locals FIRST, so they're available when callback runs if (this.env) { for (const [i, env] of this.env.entries()) { args[`env_${i}`] = ResolveNBTPart(env) env.local.set(this.name, `env_${i}`) } } if (_params.length !== 0) { for (const [i, param] of _params.entries()) { args[`param_${i}`] = ResolveNBTPart(param) param.local.set(this.name, `param_${i}`) } // Yeah this is cursed, but there's not really a better way to do this this.node.body = [] // Push this MCFunction onto the stack so toMacro() can resolve the correct function name this.core.enterMCFunction(this) this.core.insideContext( this.node, () => this.callback( makeCallable(this, (this as any).__call__.bind(undefined, ..._params)), ...(_params as MacroArgument[]), ), false, ) this.core.exitMCFunction() // Mark as generated so the later generateResources iteration doesn't re-run // the callback (which would re-execute with undefined params and append a // second broken command to the body). this.generated = true } else if (this.callback.length > 1) { throw new Error(`[MCFunctionClass] Function ${this.name} expects ${this.callback.length - 1} params at the call-site`) } return this.commands.functionCmd(this.name, 'with', this.pack.ResolveNBT(args, this.macroPoint!, true).dataPoint) } return this.commands.functionCmd(this.name) } schedule = { clear: (): FinalCommandOutput => this.commands.schedule.clear(this.name), function: (delay: TimeArgument, type: ScheduleType): FinalCommandOutput => this.commands.schedule.function(this.name, delay, type), } push(...contents: _RawMCFunctionClass[] | [() => any]) { this.generate() if (contents[0] instanceof _RawMCFunctionClass) { for (const mcfunction of contents as _RawMCFunctionClass[]) { mcfunction.generate() this.node.body.push(...mcfunction.node.body) } } else { this.core.enterMCFunction(this) this.core.insideContext(this.node, contents[0], false) this.core.exitMCFunction() } } unshift(...contents: _RawMCFunctionClass[] | [() => any]) { this.generate() const fake = new MCFunctionClass(this.core, 'fake', { addToSandstoneCore: false, creator: 'sandstone', onConflict: 'ignore', }) if (contents[0] instanceof _RawMCFunctionClass) { for (const mcfunction of contents as _RawMCFunctionClass[]) { mcfunction.generate() this.node.body.unshift(...mcfunction.node.body) } } else { this.core.enterMCFunction(fake) this.core.insideContext(fake.node, contents[0], false) this.core.exitMCFunction() fake.generate() this.node.body.unshift(...fake.node.body) } } splice(start: number, removeItems: number | 'auto', ...contents: _RawMCFunctionClass[] | [() => void]) { const fake = new MCFunctionClass(this.core, 'fake', { addToSandstoneCore: false, creator: 'sandstone', onConflict: 'ignore', }) const fullBody: Node[] = [] if (contents[0] instanceof _RawMCFunctionClass) { for (const mcfunction of contents as _RawMCFunctionClass[]) { mcfunction.generate() fullBody.push(...mcfunction.node.body) } } else { this.core.enterMCFunction(fake) this.core.insideContext(fake.node, contents[0], false) this.core.exitMCFunction() fake.generate() fullBody.push(...fake.node.body) } this.node.body.splice(start, removeItems === 'auto' ? fullBody.length : removeItems, ...fullBody) } } export const MCFunctionClass = makeClassCallable(_RawMCFunctionClass) export type MCFunctionClass< PARAMS extends readonly MacroArgument[] | undefined = undefined, ENV extends readonly MacroArgument[] | undefined = undefined, > = MakeInstanceCallable<_RawMCFunctionClass> & NBTSerializable