Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
"datasig",
"defi",
"deserialisation",
"destructures",
"divmod",
"docblock",
"electroncash",
"electrum",
Expand Down
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# CLAUDE.md

NEVER stage changes, just leave them in the working directory.

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview
Expand Down
9 changes: 0 additions & 9 deletions packages/cashc/src/Errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import {
InstantiationNode,
StatementNode,
ContractNode,
ExpressionNode,
SliceNode,
IntLiteralNode,
} from './ast/AST.js';
Expand Down Expand Up @@ -272,14 +271,6 @@ export class AssignTypeError extends TypeError {
}
}

export class TupleAssignmentError extends CashScriptError {
constructor(
node: ExpressionNode,
) {
super(node, 'Expression must return a tuple to use destructuring');
}
}

export class ConstantConditionError extends CashScriptError {
constructor(
node: BranchNode | RequireNode,
Expand Down
14 changes: 9 additions & 5 deletions packages/cashc/src/ast/AST.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export class FunctionDefinitionNode extends Node implements Named {
public name: string,
public parameters: ParameterNode[],
public body: BlockNode,
public returnType?: Type,
public returnTypes?: Type[],
) {
super();
}
Expand Down Expand Up @@ -127,11 +127,15 @@ export class VariableDefinitionNode extends NonControlStatementNode implements N
}
}

export interface TupleAssignmentTarget {
name: string;
type: Type;
}

export class TupleAssignmentNode extends NonControlStatementNode {
constructor(
// TODO: Use an IdentifierNode instead of a custom type
public left: { name: string, type: Type },
public right: { name: string, type: Type },
// TODO: Use IdentifierNodes instead of a custom type
public targets: TupleAssignmentTarget[],
public tuple: ExpressionNode,
) {
super();
Expand Down Expand Up @@ -211,7 +215,7 @@ export class FunctionCallStatementNode extends NonControlStatementNode {

export class ReturnNode extends NonControlStatementNode {
constructor(
public expression: ExpressionNode,
public expressions: ExpressionNode[],
) {
super();
}
Expand Down
19 changes: 10 additions & 9 deletions packages/cashc/src/ast/AstBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,19 +167,21 @@ export default class AstBuilder
}

visitGlobalFunctionDefinition(ctx: GlobalFunctionDefinitionContext): FunctionDefinitionNode {
const returnType = ctx.typeName() ? parseType(ctx.typeName().getText()) : undefined;
return this.buildFunctionDefinition(ctx, FunctionKind.GLOBAL, returnType);
const returnTypes = ctx.typeName_list().length > 0
? ctx.typeName_list().map((typeName) => parseType(typeName.getText()))
: undefined;
return this.buildFunctionDefinition(ctx, FunctionKind.GLOBAL, returnTypes);
}

private buildFunctionDefinition(
ctx: ContractFunctionDefinitionContext | GlobalFunctionDefinitionContext,
kind: FunctionKind,
returnType?: Type,
returnTypes?: Type[],
): FunctionDefinitionNode {
const name = ctx.Identifier().getText();
const parameters = ctx.parameterList().parameter_list().map((p) => this.visit(p) as ParameterNode);
const body = this.visit(ctx.functionBody()) as BlockNode;
const functionDefinition = new FunctionDefinitionNode(kind, name, parameters, body, returnType);
const functionDefinition = new FunctionDefinitionNode(kind, name, parameters, body, returnTypes);
functionDefinition.location = Location.fromCtx(ctx);
return functionDefinition;
}
Expand Down Expand Up @@ -231,13 +233,12 @@ export default class AstBuilder

visitTupleAssignment(ctx: TupleAssignmentContext): TupleAssignmentNode {
const expression = this.visit(ctx.expression());
const names = ctx.Identifier_list();
const types = ctx.typeName_list();
const [var1, var2] = names.map((name, i) => ({
const targets = ctx.Identifier_list().map((name, i) => ({
name: name.getText(),
type: parseType(types[i].getText()),
}));
const tupleAssignment = new TupleAssignmentNode(var1, var2, expression);
const tupleAssignment = new TupleAssignmentNode(targets, expression);
tupleAssignment.location = Location.fromCtx(ctx);
return tupleAssignment;
}
Expand Down Expand Up @@ -295,8 +296,8 @@ export default class AstBuilder
}

visitReturnStatement(ctx: ReturnStatementContext): ReturnNode {
const expression = this.visit(ctx.expression());
const returnNode = new ReturnNode(expression);
const expressions = ctx.expression_list().map((expression) => this.visit(expression) as ExpressionNode);
const returnNode = new ReturnNode(expressions);
returnNode.location = Location.fromCtx(ctx);
return returnNode;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cashc/src/ast/AstTraversal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export default class AstTraversal extends AstVisitor<Node> {
}

visitReturn(node: ReturnNode): Node {
node.expression = this.visit(node.expression);
node.expressions = this.visitList(node.expressions);
return node;
}

Expand Down
6 changes: 3 additions & 3 deletions packages/cashc/src/ast/SymbolTable.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Type, PrimitiveType, Script, Op, encodeInt } from '@cashscript/utils';
import { Type, Script, Op, encodeInt } from '@cashscript/utils';
import {
VariableDefinitionNode,
ParameterNode,
FunctionDefinitionNode,
IdentifierNode,
Node,
} from './AST.js';
import { functionReturnType } from '../utils.js';

export class Symbol {
references: IdentifierNode[] = [];
Expand Down Expand Up @@ -34,8 +35,7 @@ export class Symbol {

static userFunction(node: FunctionDefinitionNode, functionId: number): Symbol {
const parameterTypes = node.parameters.map((parameter) => parameter.type);
const returnType = node.returnType ?? PrimitiveType.VOID;
const symbol = new Symbol(node.name, returnType, SymbolType.FUNCTION, node, parameterTypes);
const symbol = new Symbol(node.name, functionReturnType(node.returnTypes), SymbolType.FUNCTION, node, parameterTypes);
symbol.setFunctionId(functionId);
return symbol;
}
Expand Down
51 changes: 29 additions & 22 deletions packages/cashc/src/generation/GenerateTargetTraversal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
SingleLocationData,
StackItem,
BytesType,
TupleType,
CompilerOptions,
SourceTagEntry,
SourceTagKind,
Expand Down Expand Up @@ -206,11 +207,8 @@ export default class GenerateTargetTraversal extends AstTraversal {
}

cleanGlobalFunctionStack(node: FunctionDefinitionNode): void {
if (node.returnType === undefined) {
this.removeScopedVariables(0, node.body); // void: drop the entire frame
} else {
this.cleanStack(node.body); // value: OP_NIP everything below the return value on top
}
// Drop everything below the return values on top (or the entire frame for a void function)
this.cleanStack(node.body, node.returnTypes?.length ?? 0);
}

visitContract(node: ContractNode): Node {
Expand Down Expand Up @@ -319,14 +317,24 @@ export default class GenerateTargetTraversal extends AstTraversal {
}
}

cleanStack(functionBodyNode: Node): void {
// Keep final verification value, OP_NIP the other stack values
// Keep only the top `keepCount` values (a contract function's verification value, or a global
// function's return values), dropping everything below them while preserving their order.
cleanStack(functionBodyNode: Node, keepCount: number = 1): void {
this.dropFromStack(functionBodyNode, keepCount, this.stack.length - keepCount);
}

private dropFromStack(node: Node, keepCount: number, dropCount: number): void {
const tagStartIndex = this.output.length;
const stackSize = this.stack.length;
for (let i = 0; i < stackSize - 1; i += 1) {
this.emit(Op.OP_NIP, { location: functionBodyNode.location, positionHint: PositionHint.END });
this.nipFromStack();
const locationData = { location: node.location, positionHint: PositionHint.END };

// Note that in case of keepCount = 1, this gets optimised to just OP_NIP, or for keepCount = 0 to OP_DROP
for (let i = 0; i < dropCount; i += 1) {
this.emit(encodeInt(BigInt(keepCount)), locationData);
this.emit(Op.OP_ROLL, locationData);
this.emit(Op.OP_DROP, locationData);
this.removeFromStack(keepCount);
}

this.tagScopeCleanup(tagStartIndex);
}

Expand Down Expand Up @@ -389,9 +397,8 @@ export default class GenerateTargetTraversal extends AstTraversal {

visitTupleAssignment(node: TupleAssignmentNode): Node {
node.tuple = this.visit(node.tuple);
this.popFromStack(2);
this.pushToStack(node.left.name);
this.pushToStack(node.right.name);
this.popFromStack(node.targets.length);
node.targets.forEach((target) => this.pushToStack(target.name));
return node;
}

Expand Down Expand Up @@ -625,14 +632,9 @@ export default class GenerateTargetTraversal extends AstTraversal {
});
}

// Drop the values that a scope (a branch or loop body) added on top of the pre-scope stack.
removeScopedVariables(depthBeforeScope: number, node: Node): void {
const tagStartIndex = this.output.length;
const dropCount = this.stack.length - depthBeforeScope;
for (let i = 0; i < dropCount; i += 1) {
this.emit(Op.OP_DROP, { location: node.location, positionHint: PositionHint.END });
this.popFromStack();
}
this.tagScopeCleanup(tagStartIndex);
this.dropFromStack(node, 0, this.stack.length - depthBeforeScope);
}

private tagScopeCleanup(tagStartIndex: number): void {
Expand Down Expand Up @@ -665,7 +667,12 @@ export default class GenerateTargetTraversal extends AstTraversal {
node.parameters = this.visitList(node.parameters);
this.emit(symbol.bytecode!, { location: node.location, positionHint: PositionHint.END });
this.popFromStack(node.parameters.length);
if (symbol.type !== PrimitiveType.VOID) this.pushToStack('(value)');

// The call leaves one value per declared return type (none for a void function); a multi-return
// function's values (a TupleType) are subsequently bound by visitTupleAssignment.
const returnValueCount = symbol.type === PrimitiveType.VOID ? 0
: symbol.type instanceof TupleType ? symbol.type.elementTypes.length : 1;
for (let i = 0; i < returnValueCount; i += 1) this.pushToStack('(value)');

return node;
}
Expand Down
6 changes: 3 additions & 3 deletions packages/cashc/src/grammar/CashScript.g4
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ topLevelDefinition
;

globalFunctionDefinition
: 'function' Identifier parameterList ('returns' '(' typeName ')')? functionBody
: 'function' Identifier parameterList ('returns' '(' typeName (',' typeName)* ')')? functionBody
;

contractDefinition
Expand Down Expand Up @@ -83,7 +83,7 @@ functionCallStatement
;

returnStatement
: 'return' expression
: 'return' expression (',' expression)*
;

controlStatement
Expand All @@ -96,7 +96,7 @@ variableDefinition
;

tupleAssignment
: typeName Identifier ',' typeName Identifier '=' expression
: typeName Identifier (',' typeName Identifier)+ '=' expression
;

assignStatement
Expand Down
Loading
Loading