import type { SandstonePack } from 'sandstone' import type { SandstoneCommands } from 'sandstone/commands' import type { Macroable, MCFunctionNode } from 'sandstone/core' import type { Node } from 'sandstone/core/nodes' import { CommandNode, ContainerCommandNode } from 'sandstone/core/nodes' import { makeCallable } from 'sandstone/utils' import { CommandArguments, FinalCommandOutput } from '../../helpers' import { FunctionCommandNode } from './function' export class ReturnRunCommandNode extends ContainerCommandNode { command = 'return' as const /** * By default, the execute is treated as single (execute.run.stuff). * This is set to `false` if the execute is used as a function (execute.run(() => { stuff })). */ isSingleExecute: boolean /** * When true, this return run is needed for flow control (e.g., if/elseIf early exit). * When false, the return run was added for function boundary semantics and can be * unwrapped when the function is inlined. */ isFlowControl: boolean /** * When true, this return run was auto-inserted to propagate a function's return * value across a function boundary (e.g. by ContainerCommandsToMCFunctionVisitor * wrapping a `FunctionCommandNode` in a child MCFunction). It exists only for * function-call semantics and can be safely unwrapped when the called function * is inlined. * * Distinct from `isFlowControl`: * - `isFlowControl` — set by IfElseTransformationVisitor to preserve early-exit * semantics for `if/elseIf` chains. * - `isFunctionBoundary` — set by visitors that wrap a function call in * `return run function X` to carry X's return value up one level. * * User-written `returnCmd.run(...)` and `_.return.run(...)` leave both flags * `false`, so the `return` keyword is preserved through inlining. */ isFunctionBoundary: boolean constructor( sandstonePack: SandstonePack, isMacro: boolean = false, args: [...args: unknown[]] = [], { isSingleExecute = true, body = [] as Node[], isFlowControl = false, isFunctionBoundary = false } = {}, ) { super(sandstonePack, ...args) this.isSingleExecute = isSingleExecute this.isFlowControl = isFlowControl this.isFunctionBoundary = isFunctionBoundary this.append(...body) } getValue = () => { if (this.body.length > 1) { throw new Error('Return run nodes can only have one child node when toString is called.') } let command = this.body[0].getValue() if (command.startsWith('$')) { this.isMacro = true command = command.slice(1) } return `${this.isMacro ? '$' : ''}${this.command} run ${command}` } createMCFunction = (currentMCFunction: MCFunctionNode | null) => { if (this.isSingleExecute || !currentMCFunction) { return { node: this as ReturnRunCommandNode } } const namespace = currentMCFunction.resource.name.includes(':') ? `${currentMCFunction.resource.name.split(':')[0]}:` : '' // Create a new MCFunctionNode with the body of the ExecuteNode. const mcFunction = this.sandstonePack.MCFunction( `${namespace}${currentMCFunction.resource.path.slice(2).join('/')}/return_run`, { addToSandstoneCore: false, creator: 'sandstone', onConflict: 'rename', }, ) const mcFunctionNode = mcFunction.node mcFunctionNode.body = this.body // Return an execute calling this MCFunction. const mcFunctionCall = new FunctionCommandNode(this.sandstonePack, mcFunction) this.body = [mcFunctionCall] return { node: this as ReturnRunCommandNode, mcFunction: mcFunctionNode } } append = (...nodes: Node[]) => { for (const node of nodes) { this.body.push(node) if (this.isSingleExecute) { this.sandstoneCore.getCurrentMCFunctionOrThrow().exitContext() } } return (nodes.length === 1 ? nodes[0] : nodes) as any } } export class ReturnArgumentsCommand extends CommandArguments { protected NodeType = ReturnRunCommandNode /** * Execute a command and return its result value. * * This allows functions to return specific values based on command execution results. * The returned value can be used by the caller for conditional logic or stored in objectives. * * Can be used in two ways: * - Chain with other commands: return.run.say('hello') * - With a callback function: return.run(() => { commands }) * * @example * return.run.execute.if.score('@p', 'health').matches([1, 10]).run.returnCmd(1) */ get run(): SandstoneCommands & ((callback: () => void) => FinalCommandOutput) { const node = this.getNode() // Macro propagate: route through macroCommands when this return is part // of a macro chain. See execute.ts for the rationale. const commandsSource = (this.sandstonePack as any)[this.isMacro ? 'macroCommands' : 'commands'] as any // Use 'any' to avoid TS2859 complexity limit with SandstoneCommands generic const commands = new Proxy(commandsSource, { get: (_t, p, _r) => { // The context will automatically be exited by the node itself this.sandstoneCore.getCurrentMCFunctionOrThrow().enterContext(node) return commandsSource[p] }, }) as SandstoneCommands return makeCallable( commands, (callback: () => void) => { node.isSingleExecute = false this.sandstoneCore.insideContext(node, callback, true) return new FinalCommandOutput(node) }, true, ) } } export class ReturnCommandNode extends CommandNode { command = 'return' as const } export class ReturnCommand extends CommandArguments { protected NodeType = ReturnCommandNode /** * Return from a function with a specific value or failure state. * * Functions normally return 1 when successful. This command allows returning * custom values or indicating failure. The return value can be captured by * the caller using `execute store result`. * * @param value Optional integer value to return (0-2147483647). Defaults to 0 if not specified. * Higher values typically indicate better success or more significant results. * * @example * ```ts * // Return success with a specific value * returnCmd(42) * * // Return default value (0) * returnCmd() * * // Return based on conditions * execute.if.entity('@p[tag=vip]').run.returnCmd(100) // VIP bonus * execute.unless.entity('@p[tag=vip]').run.returnCmd(50) // Regular bonus * ``` */ get return() { // Pass `this.isMacro` through so `Macro.returnCmd.run.` chains land // in the macro command graph. Without this, the inner ReturnArgumentsCommand // is constructed with isMacro=false and its `.run` proxy forwards to // `this.sandstonePack.commands` (always ), silently stripping the // macro flag — even though the outer ReturnCommand was created via Macro. const run = new ReturnArgumentsCommand(this.sandstonePack, this.isMacro) return makeCallable( { run: run.run, fail: this.fail, }, (value?: Macroable) => this.finalCommand([value || 0]), true, ) } /** * Return from a function with a failure state. * * Immediately exits the function and returns 0, indicating failure. * This is equivalent to `returnCmd(0)` but more semantically clear * when you want to explicitly indicate failure. * * Useful for error handling and early exits when conditions aren't met. * * @example * ```ts * // Early exit on invalid conditions * execute.unless.entity('@p').run.returnCmd.fail() // No player found * * // Validation check * execute.if.score('@p', 'level').matches([..0]).run.returnCmd.fail() // Invalid level * * // Error handling * execute.unless.block('~ ~ ~', 'minecraft:chest').run.returnCmd.fail() // Expected chest not found * ``` */ fail = () => this.finalCommand(['fail']) }