lua

package module
v0.0.0-...-c565dd5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2026 License: MIT Imports: 34 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

TOL logo

TOL — The Open Language

A smart contract language built for Agents: verifiable, metered, and composable.


Why Agent-Native?

Traditional smart contracts are designed to be human-readable. A developer reads the source, audits the logic, and makes a judgment call. When something goes wrong, a human can stop, review, and recover.

Agents are different:

  • High-frequency — thousands of calls per day, per strategy, per account.
  • Automated — no gut feeling that says "this seems wrong, let me pause."
  • Contagious — one flawed strategy can replicate instantly across thousands of agents.
  • Compositional — multiple contracts, modules, and external services are chained together automatically.

The root problem is not that agents make mistakes. It is that mistakes get automated and amplified. A human auditor catching a bug in one contract saves one contract. An agent framework that can verify contracts before executing them saves every contract in the ecosystem.

TOL elevates identity, task, capability, payment, and trust to first-class language primitives — the same leap Solidity made when it introduced msg.sender, payable, transfer(), and msg.value.


Three Pillars

1. Verifiable — Know what will happen before calling

TOL functions carry compiler-verified @effects annotations directly in the .toc ABI artifact:

/**
 * @effects(reads:  storage.balances[caller], storage.allowances[caller,to])
 * @effects(writes: storage.balances[caller], storage.balances[to])
 * @effects(emits:  Transfer)
 * @effects(calls:  [])
 * @gas(upper:  50000)
 */
function transfer(agent to, u256 amount) external returns (bool ok) {
    require(balances[msg.sender] >= amount, "INSUFFICIENT_BALANCE");
    balances[msg.sender] -= amount;
    balances[to] += amount;
    emit Transfer(msg.sender, to, amount);
    return true;
}

The compiler checks that effects_actual ⊆ effects_declared. If the implementation reads a storage slot that is not listed, compilation fails. The resulting .toc artifact binds these declarations to the BytecodeHash, so any caller — human or agent — can trust the metadata without re-reading the source.

An agent reading this ABI knows, before sending a single transaction:

  • Exactly which storage keys may change.
  • Which event will be emitted.
  • No external calls — no re-entrancy risk.
  • Maximum gas to budget.
2. Metered — Know the cost before committing

Every bounded TOL function can carry a static gas upper bound:

/// @bounds(positions_len <= 64)
/// @gas(upper: 8200 + positions_len * 420 + OracleCap.max_gas)
function settle(u256 n) external { ... }

The compiler verifies this bound against a conservative cost model (SSTORE, SLOAD, LOG, external call budgets). If the declared bound is too low, compilation fails.

For agents operating in task markets, oracle networks, or prediction markets, this matters enormously:

  • Estimate cost → decide whether to execute.
  • Compute fee, quote, or margin before the transaction.
  • Give external partners a verifiable SLA with a concrete price.
3. Composable — Combine modules with contracts, not conventions

External calls in TOL are expressed as capability references:

/// @effects(calls: cap:OracleCap iface:IOracle selector:0x12345678 max_gas:3000 max_calls:1 max_depth:1)

This is not documentation — it is a machine-checkable authorization boundary. A module is only allowed to call oracle.getPrice, not any other method. It may call it at most once, with a bounded gas budget, at a call depth of at most 1.

A function that makes arbitrary external calls is marked non_composable: true in the ABI JSON — a fast-path signal for tooling that this function requires additional human review before automation.


Agent-Native Primitives

TOL provides first-class primitives that eliminate boilerplate guards and manual state machines in agent contracts.

capability — Permission Declarations
capability Registrar;    // may register / suspend agents
capability Arbitrator;   // may rule on disputes
capability OracleResolver;

Use @requires(caller: X) to gate a function. The compiler inserts the capability check automatically:

@requires(caller: Arbitrator)
function rule(u256 dispute_id, agent winner, u16 slash_bps, string reason) public { ... }

Emitted in the .toc ABI as "requires_capability": "Arbitrator" — so any agent can check authorization without reading source.

Write-Once Oracle Pattern (openlib)

No compiler magic — use plain storage with require(!is_set) guard:

u8   winning_outcome;
bool outcome_is_set;

@requires(caller: OracleResolver)
function resolve(u8 outcome) public {
    require(!outcome_is_set, "AlreadyResolved");   // write-once guard
    set winning_outcome = outcome;
    set outcome_is_set = true;
    emit Resolved(outcome, agent(msg.sender));
}

function claim() public {
    require(outcome_is_set, "NotResolved");
    u256 payout = shares[msg.sender][winning_outcome] * totalPool / totalShares;
    release(agent(msg.sender), payout);
}

See openlib/Oracle.tol, openlib/Vote.tol, openlib/Task.tol for reusable patterns.

Task State Machine Pattern (openlib)

Use explicit state constants and require() guards — no hardcoded compiler state machine:

u8 constant STATE_OPEN      = 1;
u8 constant STATE_ACCEPTED  = 2;
u8 constant STATE_SUBMITTED = 3;
u8 constant STATE_APPROVED  = 4;

mapping(u256 => u8)    task_state;
mapping(u256 => agent) task_worker;
mapping(u256 => u256)  task_reward;

function approveTask(u256 task_id) public {
    require(task_state[task_id] == STATE_SUBMITTED, "TaskNotSubmitted");
    set task_state[task_id] = STATE_APPROVED;
    release(task_worker[task_id], task_reward[task_id]);
}
agent — Identity with Native Properties

agent is TOL's native identity type — registry semantics are built in, no manual require(registry.isActive(addr)) needed:

function updateProfile(string metadata_uri) public {
    require(agent(msg.sender).is_active, "NotActive");   // reads from protocol registry
    emit AgentProfileUpdated(agent(msg.sender), metadata_uri);
}

function totalScoreOf(agent who) public view returns (i256 score) {
    return who.reputation;       // agent property — no storage lookup boilerplate
}

Available properties: .stake, .is_active, .reputation, .rating_count, .suspended.

escrow / release / slash — Intent-Explicit Payment
escrow(agent(msg.sender), msg.value);          // lock funds against agent identity
release(t.worker, t.reward);                   // unlock reward to worker
slash(loser, loser.stake * slash_bps / 10000); // penalize + route proceeds
manifest {} — Machine-Readable Contract Metadata
manifest {
    version:      "1.0.0";
    capabilities: [Arbitrator];
    spec:         "ipfs://Qm_task_escrow_spec";
    sla_uptime:   9900;
}

Emitted verbatim into the .toc ABI JSON as a top-level "manifest" key — inspectable by tooling without executing the contract.

@pay / @verifiable / @delegated
@pay(10_000_000)                  // enforces msg.value >= fee at language level
function createBinaryMarket(...) public returns (agent market) { ... }

@verifiable                       // result provable off-chain; ABI field "verifiable": true
function totalScoreOf(agent who) public view returns (i256 score) { ... }

@delegated                        // accepts delegated calls; injects delegation verify
function acceptJob(u256 tid) external payable { ... }

Policy Wallet Contracts

The examples/policy_wallet/ directory contains five canonical contract templates that implement the on-chain policy wallet architecture:

Contract File Purpose
PolicyWallet PolicyWallet.tol Base account contract with spend caps, allowlists, and suspension
SpendGuard SpendGuard.tol Enforces daily and per-transaction spending limits with rolling windows
GuardianRecovery GuardianRecovery.tol Timelocked guardian-initiated account recovery with owner cancellation
TerminalAuthority TerminalAuthority.tol Per-terminal-class policy enforcement — independent value ceilings and trust tier minimums for app, card, POS, voice, kiosk, robot, and API channels
DelegatedAgent DelegatedAgent.tol Grants capped, time-bounded spending authority to delegate addresses (agents, assistants, bots) with instant revocation

These contracts are designed so that the authority to spend lives in the account, not in the terminal device. A single policy wallet can be accessed from a mobile app, a contactless card, a voice assistant, or an autonomous agent — each governed by the same on-chain rules with terminal-scoped limits.

Each template compiles to a .toc artifact with is_account: true and a PolicyProfile in the metadata, enabling discovery clients to understand the account's policy features without executing any code.


Agent Economy Contracts

The examples/agent_economy/ directory contains five canonical contracts that demonstrate the structural patterns of machine-native commerce:

Contract File Pattern
TaskEscrow TaskEscrow.tol Agent-to-agent task market with escrow, submission, approval, dispute, and automatic payout
OracleResolver OracleResolver.tol Write-once oracle resolution with capability-gated fulfillment and downstream settlement
RecurringPayment RecurringPayment.tol Scheduled recurring payments with policy-checked execution and cancellation
SponsorRelay SponsorRelay.tol Gas sponsorship relay — a sponsor pays gas on behalf of an agent, with policy-bound attribution and audit receipts
MerchantPayment MerchantPayment.tol Merchant payment acceptance with terminal-class restrictions, spend cap enforcement, and settlement callbacks

These contracts use TOL's agent-native primitives (agent, escrow/release/slash, capability, @delegated) and openlib patterns (openlib/Task.tol, openlib/Oracle.tol) to eliminate boilerplate and make the economic logic machine-verifiable.


Contract Metadata for Discovery

TOL emits rich, machine-readable metadata in every .toc artifact. The metadata/ package (schema version 0.1.0) defines the canonical types that enable discovery clients and agent runtimes to inspect contracts before execution:

  • ContractMetadata — the top-level structure: artifact references, function metadata, events, manifest, gas model, capabilities, account flag, and policy profile.
  • FunctionMeta — per-function metadata including mutability (pure, view, payable, nonpayable), named parameters (ParamMeta with name and type), named return values, effects, gas upper bound, risk level, and flags for verifiable, delegated, and non_composable.
  • EffectsMeta — what a function reads, writes, emits, and calls, with CallMeta entries specifying capability, interface, selector, and max gas for each external call.
  • PolicyProfile — declares which policy wallet features a contract supports (spend caps, allowlist, terminal policy, guardian, recovery, delegation, suspension).
  • CapabilityManifest — standardized capability advertisement built from contract metadata via BuildCapabilityManifest. Includes capability ads (required vs. provided), verifiable methods with proof types, delegated methods with scope fields, inferred task interfaces, and oracle slots.
  • DiscoveryManifest — the standardized manifest format for discovery clients, built via BuildDiscoveryManifest. Includes contract type inference (token, policy_wallet, task_escrow, oracle, payment, delegation, custom), service kind inference, searchable tags, and a human-readable risk summary generated by the HumanReadableSummary system.

An agent evaluating whether to interact with a contract can read the discovery manifest, check the capability requirements, verify the effects bounds, estimate gas cost, and assess risk level — all without executing the contract or reading its source code.


Contract Verification

The verify/ package provides source verification against deployed on-chain code. Given a .tol source file and a contract address, the verifier:

  1. Compiles the source locally to produce a .toc artifact.
  2. Fetches the deployed code from the chain via tos_getCode RPC.
  3. Compares bytecode hashes and ABI hashes between the local compilation and the deployed artifact.

Verification modes:

  • VerifySource — compare local source compilation against raw deployed .toc bytes.
  • VerifyArtifact — compare two .toc artifacts byte-for-byte via their bytecode and ABI hashes.
  • VerifyPackage — compare two .tor packages by verifying each contract entry inside them.
  • VerifyDeployed — end-to-end: compile source, fetch on-chain code via RPC, compare. Supports both .toc and .tor formats.
  • VerifyDeployedBatch — verify multiple contracts against their deployed code in a single pass.
  • VerifyDirectory — verify deterministic compilation of all .tol files in a directory (compile twice, compare artifacts).
  • VerifyAllExamples — verify all contracts in examples/policy_wallet/ and examples/agent_economy/.

The SimpleRPCClient provides a ready-made JSON-RPC client for tos_getCode. Verification reports include per-contract pass/fail status, source hashes, bytecode hashes, ABI hashes, and detailed error messages.


Language

TOL is a statically-typed, Solidity-inspired language. Developers familiar with Solidity will recognize the same type system, storage model, ABI encoding, events, modifiers, and inheritance. The surface syntax is deliberately explicit — no implicit casts, no hidden state transitions.

pragma tolang 0.3.0;

contract TRC20 {
    u256                             total_supply;
    mapping(agent => u256)           balances;
    mapping(agent => mapping(agent => u256)) allowances;

    constant NOBODY: agent = "0x0000000000000000000000000000000000000000000000000000000000000000";

    event Transfer(agent indexed from, agent indexed to, u256 value)
    event Approval(agent indexed owner, agent indexed spender, u256 value)

    constructor(u256 initialSupply) {
        total_supply = initialSupply;
        balances[msg.sender] = initialSupply;
        emit Transfer(NOBODY, msg.sender, initialSupply);
    }

    /**
     * @effects(reads:  storage.balances[caller])
     * @effects(writes: storage.balances[caller], storage.balances[to])
     * @effects(emits:  Transfer)
     * @gas(upper:  50000)
     */
    function transfer(agent to, u256 amount) external returns (bool ok) {
        require(balances[msg.sender] >= amount, "INSUFFICIENT_BALANCE");
        balances[msg.sender] -= amount;
        balances[to] += amount;
        emit Transfer(msg.sender, to, amount);
        return true;
    }

    function balanceOf(agent owner) external view returns (u256 balance) {
        return balances[owner];
    }
}

Agent-Native Example

The following excerpt shows a prediction market where double-resolution is structurally impossible and payout is automatic — using plain storage with write-once guards:

pragma tolang 0.4.0;

capability OracleResolver;

contract PredictionMarket is IPredictionMarket {
    manifest {
        version:      "1.0.0";
        capabilities: [OracleResolver];
        spec:         "ipfs://Qm_prediction_market_spec";
    }

    u8   winning_outcome;
    bool outcome_is_set;                           // write-once guard
    mapping(u8 => u256)                    pool;
    mapping(agent => mapping(u8 => u256)) shares;

    @requires(caller: OracleResolver)
    function resolve(u8 outcome) public {
        require(block.timestamp_ms >= close_time_ms, "MarketNotClosed");
        require(!outcome_is_set, "AlreadyResolved");   // write-once
        set winning_outcome = outcome;
        set outcome_is_set = true;
        emit Resolved(outcome, agent(msg.sender));
    }

    function claim() public {
        require(outcome_is_set, "NotResolved");
        u256 payout = shares[msg.sender][winning_outcome]
                      * (pool[0] + pool[1])
                      / pool[winning_outcome];
        release(agent(msg.sender), payout);
        emit Claimed(agent(msg.sender), payout);
    }
}

See docs/AGENT_PROTOCOL_DRAFT2.tol for a complete agent economy protocol (registry, reputation, task escrow, dispute resolution, prediction market, reward vault).


The VM

TOL compiles to a hardened, deterministic Lua 5.4 VM. All non-deterministic operations are removed — no I/O, no floating-point, no OS access — and the VM is extended with:

  • 256-bit integer arithmetic — LUint256 is a native struct{lo, ml, mh, hi uint64}. All hot-path operations (add, sub, mul, bitwise, shift, compare) use math/bits with zero allocations. No math/big in production paths.
  • Gas metering — every VM instruction increments a counter; execution halts deterministically when the limit is reached.
  • Signed integer intrinsics — i8..i256 two's-complement arithmetic built on the same native primitives.
TOL source → sema → lower → codegen → Lua bytecode → VM
Lua source  →                          Lua bytecode → VM

Both paths produce the same bytecode format and run on the same VM.

Standard Libraries
Library Status
base (restricted) available
table available
string available
math (integer subset) available
io, os, debug, coroutine removed

Removed from base: print, dofile, loadfile, load, loadstring, require, collectgarbage.


Artifact Formats

The TOL toolchain produces three artifact types:

Extension Name Contents
.toc Artifact Compiled bytecode + ABI JSON (with @effects, manifest, capability fields) + source/bytecode hashes
.abi Interface Human- and machine-readable interface definition for cross-contract typing
.tor Package Deterministic ZIP archive: manifest + .toc + .abi + sources

All artifacts are content-addressed. The .toc BytecodeHash field covers exactly the bytecode that was verified against the effect and capability declarations, making the ABI JSON as trustworthy as the bytecode itself.

Example .toc ABI excerpt for an agent-native function:

{
  "name": "rule",
  "visibility": "public",
  "mutability": "nonpayable",
  "selector": "0x...",
  "params": [
    {"name": "dispute_id", "type": "u256"},
    {"name": "winner", "type": "agent"},
    {"name": "slash_bps", "type": "u16"},
    {"name": "reason", "type": "string"}
  ],
  "returns": [],
  "requires_capability": "Arbitrator",
  "verifiable": false,
  "delegated": false,
  "non_composable": false,
  "risk_level": "medium",
  "effects": {
    "reads": ["storage.disputes[dispute_id]"],
    "writes": ["storage.disputes[dispute_id]", "storage.balances[winner]"],
    "emits": ["DisputeRuled"],
    "calls": []
  },
  "gas_upper": 85000
}

The mutability field (pure, view, payable, nonpayable) tells agents whether a function modifies state or requires payment. The named_params and named_returns fields (expressed as ParamMeta objects with name and type) allow agents to construct calls by name rather than positional index, reducing integration errors.


CLI

go build -o bin/tol ./cmd/tolang
tol compile Contract.tol             # compile to .toc artifact
tol compile --emit abi Contract.tol  # compile to .abi interface
tol compile --emit tor ./pkg/        # compile to .tor package
tol fmt Contract.tol                 # format source to stdout
tol fmt -w Contract.tol              # format in place
tol fmt -l ./contracts/              # list files that need formatting
tol lsp                              # start Language Server (stdin/stdout)
tol inspect artifact.toc             # show metadata (text)
tol inspect --json artifact.toc      # show metadata (JSON)
tol verify artifact.toc              # verify artifact integrity
tol verify --source src.tol a.toc    # verify + source hash check
tol pack -o out.tor ./contracts/     # package directory into .tor
tol test ./contracts/                # run *_test.tol test files
tol test --cover --covermin 80 .     # with coverage gate
tol --help

Developer Tooling

Formatter — tol fmt

Canonical code formatting, like gofmt for TOL:

tol fmt Contract.tol           # print formatted source to stdout
tol fmt -w Contract.tol        # format in place
tol fmt -w ./contracts/        # recursively format all .tol files
tol fmt -l ./contracts/        # list files that need formatting (CI gate)

4-space indentation, consistent brace style, preserved doc comments. Idempotent — formatting twice produces identical output.

Language Server — tol lsp

IDE integration via the Language Server Protocol:

tol lsp                        # start LSP server on stdin/stdout

Features:

  • Real-time diagnostics — parse errors and sema warnings as you type
  • Hover — type information for keywords and built-in types
  • Works with any LSP-compatible editor (VS Code, Neovim, Helix, etc.)
Canonical Types Only

TOL requires canonical type names — Solidity aliases are rejected:

# uint256 → error: "Solidity type alias 'uint256' is not allowed; use 'u256'"
# Use: u256, i128, u8, bool, agent, bytes32, etc.
Coverage — tol test --cover

Line, branch, and function coverage with HTML reports:

tol test --cover ./contracts/              # print coverage summary
tol test --cover --covermin 80 ./contracts/ # fail if coverage < 80%

Safety by Design

TOL enforces several safety properties at the language level:

Rule Enforcement
Storage writes require set balances[addr] = 100 → error; must write set balances[addr] = 100
UNO encrypted ops are explicit a == b on uno type → error; must write a.eq(b) (150k gas)
msg.value always encrypted msg.value returns encrypted ciphertext in all payable functions
Error model typed require → Error(string), assert → Panic(uint256), revert → custom selector
No implicit operator overloading using SafeMath for u256 allows x.add(y) but NOT x + y dispatch
Effects verified @effects(writes: [storage.x]) checked against actual code — undeclared writes fail compilation

Test Framework

Write tests alongside contracts in *_test.tol files:

pragma tolang 0.3.0;

test TRC20Suite {
    setup {
        deploy TRC20(1000000) -> token;
    }

    function test_transfer() {
        with msg.sender = 0x8ac013baac6fd392efc57bb097b1c813eae702332ba3eaa1625f942c5472626d {
            assert_eq(token.transfer(0x473302ca547d5f9877e272cffe58d4def43198b66ba35cff4b2e584be19efa05, 100), true);
        }
        assert_eq(token.balanceOf(0x473302ca547d5f9877e272cffe58d4def43198b66ba35cff4b2e584be19efa05), 100);
    }

    function test_insufficient_balance() {
        assert_revert(function() { token.transfer(0x473302ca547d5f9877e272cffe58d4def43198b66ba35cff4b2e584be19efa05, 9999999); });
    }
}
tol test ./examples/trc20_tol/
# ok   ./examples/trc20_tol/trc20_test.tol   (10 tests, 0 failures)

Embedding

import lua "gitlab.com/tos-network/tolang"

L := lua.NewState()
defer L.Close()

L.SetGasLimit(1_000_000)
L.RegisterModule("chain", map[string]lua.LGFunction{
    "get": getStorage,
    "set": setStorage,
})

if err := L.DoString(src); err != nil {
    // handle error
}
fmt.Println("gas used:", L.GasUsed())

Compile TOL source directly:

// Compile to bytecode artifact (.toc)
artifact, err := lua.CompileArtifact(src, "TRC20")

// Or compile to raw bytecode
bc, err := lua.CompileBytecode(src, "TRC20")
err = L.DoBytecode(bc)

License

MIT. See LICENSE.

Documentation

Overview

Tolang: deterministic Lua VM for the TOS blockchain

Index

Constants

View Source
const (
	VarArgHasArg   uint8 = 1
	VarArgIsVarArg uint8 = 2
	VarArgNeedsArg uint8 = 4
)
View Source
const (
	// BaseLibName is here for consistency; the base functions have no namespace/library.
	BaseLibName = ""
	// LoadLibName is here for consistency; the loading system has no namespace/library.
	LoadLibName = "package"
	// TabLibName is the name of the table Library.
	TabLibName = "table"
	// IoLibName is the name of the io Library.
	IoLibName = "io"
	// OsLibName is the name of the os Library.
	OsLibName = "os"
	// StringLibName is the name of the string Library.
	StringLibName = "string"
	// MathLibName is the name of the math Library.
	MathLibName = "math"
	// DebugLibName is the name of the debug Library.
	DebugLibName = "debug"
	// CoroutineLibName is the name of the coroutine Library.
	CoroutineLibName = "coroutine"
)
View Source
const (
	OP_MOVE     int = iota /*      A B     R(A) := R(B)                            */
	OP_MOVEN               /*      A B     R(A) := R(B); followed by R(C) MOVE ops */
	OP_LOADK               /*     A Bx    R(A) := Kst(Bx)                          */
	OP_LOADBOOL            /*  A B C   R(A) := (Bool)B; if (C) pc++                */
	OP_LOADNIL             /*   A B     R(A) := ... := R(B) := nil                 */
	OP_GETUPVAL            /*  A B     R(A) := UpValue[B]                          */

	OP_GETGLOBAL  /* A Bx    R(A) := Gbl[Kst(Bx)]                            */
	OP_GETTABLE   /*  A B C   R(A) := R(B)[RK(C)]                             */
	OP_GETTABLEKS /*  A B C   R(A) := R(B)[RK(C)] ; RK(C) is constant string */

	OP_SETGLOBAL  /* A Bx    Gbl[Kst(Bx)] := R(A)                            */
	OP_SETUPVAL   /*  A B     UpValue[B] := R(A)                              */
	OP_SETTABLE   /*  A B C   R(A)[RK(B)] := RK(C)                            */
	OP_SETTABLEKS /*  A B C   R(A)[RK(B)] := RK(C) ; RK(B) is constant string */

	OP_NEWTABLE /*  A B C   R(A) := {} (size = BC)                         */

	OP_SELF /*      A B C   R(A+1) := R(B); R(A) := R(B)[RK(C)]             */

	OP_ADD /*       A B C   R(A) := RK(B) + RK(C)                           */
	OP_SUB /*       A B C   R(A) := RK(B) - RK(C)                           */
	OP_MUL /*       A B C   R(A) := RK(B) * RK(C)                           */
	OP_DIV /*       A B C   R(A) := RK(B) / RK(C)                           */
	OP_MOD /*       A B C   R(A) := RK(B) % RK(C)                           */
	OP_POW /*       A B C   R(A) := RK(B) ^ RK(C)                           */
	OP_UNM /*       A B     R(A) := -R(B)                                   */
	OP_NOT /*       A B     R(A) := not R(B)                                */
	OP_LEN /*       A B     R(A) := length of R(B)                          */

	OP_CONCAT /*    A B C   R(A) := R(B).. ... ..R(C)                       */

	OP_JMP /*       sBx     pc+=sBx                                 */

	OP_EQ /*        A B C   if ((RK(B) == RK(C)) ~= A) then pc++            */
	OP_LT /*        A B C   if ((RK(B) <  RK(C)) ~= A) then pc++            */
	OP_LE /*        A B C   if ((RK(B) <= RK(C)) ~= A) then pc++            */

	OP_TEST    /*      A C     if not (R(A) <=> C) then pc++                   */
	OP_TESTSET /*   A B C   if (R(B) <=> C) then R(A) := R(B) else pc++     */

	OP_CALL     /*      A B C   R(A) ... R(A+C-2) := R(A)(R(A+1) ... R(A+B-1)) */
	OP_TAILCALL /*  A B C   return R(A)(R(A+1) ... R(A+B-1))              */
	OP_RETURN   /*    A B     return R(A) ... R(A+B-2)      (see note)      */

	OP_FORLOOP /*   A sBx   R(A)+=R(A+2);
	     if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/
	OP_FORPREP /*   A sBx   R(A)-=R(A+2); pc+=sBx                           */

	OP_TFORLOOP /*  A C     R(A+3) ... R(A+3+C) := R(A)(R(A+1) R(A+2));
	    if R(A+3) ~= nil then { pc++; R(A+2)=R(A+3); }  */
	OP_SETLIST /*   A B C   R(A)[(C-1)*FPF+i] := R(A+i) 1 <= i <= B        */

	OP_CLOSE   /*     A       close all variables in the stack up to (>=) R(A)*/
	OP_CLOSURE /*   A Bx    R(A) := closure(KPROTO[Bx] R(A) ... R(A+n))  */

	OP_VARARG /*     A B     R(A) R(A+1) ... R(A+B-1) = vararg            */

	OP_BAND /*      A B C   R(A) := RK(B) & RK(C)                           */
	OP_BOR  /*      A B C   R(A) := RK(B) | RK(C)                           */
	OP_BXOR /*      A B C   R(A) := RK(B) ~ RK(C)                           */
	OP_SHL  /*      A B C   R(A) := RK(B) << RK(C)                          */
	OP_SHR  /*      A B C   R(A) := RK(B) >> RK(C)                          */
	OP_IDIV /*      A B C   R(A) := RK(B) // RK(C)                          */
	OP_BNOT /*      A B     R(A) := ~R(B)                                   */

	OP_NOP /* NOP */
)
View Source
const ArtifactFormatVersion uint16 = 1

ArtifactFormatVersion is the binary format version for .toc artifacts.

View Source
const BytecodeFormatVersion uint16 = 1

BytecodeFormatVersion is the binary format version for tolang bytecode.

View Source
const EnvironIndex = -10001
View Source
const FramesPerSegment = 8

FramesPerSegment should be a power of 2 constant for performance reasons. It will allow the go compiler to change the divs and mods into bitshifts. Max is 256 due to current use of uint8 to count how many frames in a segment are used.

View Source
const GlobalsIndex = -10002
View Source
const LUint256Bit = 256
View Source
const LuaVersion = "Lua 5.1 (uint256)"
View Source
const MappingLibName = "mapping"
View Source
const MultRet = -1
View Source
const PackageAuthors = "TOS Network"
View Source
const PackageCopyRight = PackageName + " " + PackageVersion + " Copyright (C) 2024-2025 " + PackageAuthors
View Source
const PackageName = "Tolang"
View Source
const PackageVersion = "0.2"
View Source
const RegistryIndex = -10000

Variables

View Source
var CallStackSize = 256
View Source
var CompatVarArg = true
View Source
var FieldsPerFlush = 50
View Source
var LFalse = LBool(false)
View Source
var LNil = LValue(&LNilType{})
View Source
var LTrue = LBool(true)
View Source
var LUint256One = LUint256{/* contains filtered or unexported fields */}
View Source
var LUint256Zero = LUint256{}
View Source
var LuaDirSep string
View Source
var LuaExecDir = "!"
View Source
var LuaIgMark = "-"
View Source
var LuaLDir string
View Source
var LuaOS string
View Source
var LuaPath = "LUA_PATH"
View Source
var LuaPathDefault string
View Source
var LuaPathMark = "?"
View Source
var LuaPathSep = ";"
View Source
var MaxArrayHoleGrowth = 64
View Source
var MaxArrayIndex = 67108864
View Source
var MaxTableGetLoop = 100
View Source
var RegistryGrowStep = 32
View Source
var RegistrySize = 256 * 20

Functions

func BuildInterface

func BuildInterface(mod *tolast.Module) ([]byte, error)

BuildInterface renders a parsed module into a textual interface declaration.

func BuildInterfaceForContract

func BuildInterfaceForContract(mod *tolast.Module, c *tolast.ContractDecl, interfaceName string) ([]byte, error)

BuildInterfaceForContract renders a specific ContractDecl as a .abi interface.

func BuildInterfaceForDecl

func BuildInterfaceForDecl(mod *tolast.Module, iface *tolast.InterfaceDecl) ([]byte, error)

BuildInterfaceForDecl renders a top-level InterfaceDecl as a .abi file.

func BuildInterfaceWithOptions

func BuildInterfaceWithOptions(mod *tolast.Module, opts *InterfaceOptions) ([]byte, error)

BuildInterfaceWithOptions renders a parsed module into textual interface declaration. When opts.ContractName is set, that contract is used; otherwise the first contract.

func BuildLowered

func BuildLowered(source []byte, name string) (*lower.Program, error)

BuildLowered builds typed and lowered TOL program for diagnostics/testing. Import declarations are resolved relative to the directory of name using the OS filesystem.

func BuildOpenlibFamilyBundlePackage

func BuildOpenlibFamilyBundlePackage(entries []OpenlibReleaseEntry, sources map[string][]byte) ([]byte, error)

BuildOpenlibFamilyBundlePackage builds a multi-contract family bundle .tor for families that contain more than one published contract release.

func CompileArtifact

func CompileArtifact(source []byte, name string) ([]byte, error)

CompileArtifact compiles TOL source into a .toc artifact.

func CompileArtifactWithOptions

func CompileArtifactWithOptions(source []byte, name string, opts *ArtifactOptions) ([]byte, error)

CompileArtifactWithOptions compiles TOL source into a .toc artifact with configurable bytecode debug metadata emission.

func CompileBytecode

func CompileBytecode(source []byte, name string) ([]byte, error)

CompileBytecode compiles TOL source into deterministic bytecode.

func CompileBytecodeFromLowered

func CompileBytecodeFromLowered(prog *lower.Program, name string) ([]byte, error)

CompileBytecodeFromLowered compiles a lowered TOL program into deterministic bytecode.

func CompileBytecodeWithOptions

func CompileBytecodeWithOptions(source []byte, name string, opts *CompileOptions) ([]byte, error)

CompileBytecodeWithOptions compiles TOL source into deterministic bytecode with configurable debug metadata emission.

func CompileInitBytecode

func CompileInitBytecode(source []byte, name string) ([]byte, error)

CompileInitBytecode compiles TOL source into init-mode bytecode (constructor only, no tos.oninvoke dispatch). The init artifact is used for constructor-at-deploy-time execution and exposes tos.oncreate for test-path constructor calls.

func CompileInterface

func CompileInterface(source []byte, name string) ([]byte, error)

CompileInterface compiles TOL source into a textual .abi interface declaration.

func CompileInterfaceWithOptions

func CompileInterfaceWithOptions(source []byte, name string, opts *InterfaceOptions) ([]byte, error)

CompileInterfaceWithOptions compiles TOL source into textual .abi with options.

func CompilePackage

func CompilePackage(source []byte, name string, opts *PackageOptions) ([]byte, error)

CompilePackage compiles source into a deterministic .tor package. For single-contract files the behaviour is identical to before. For multi-contract files every contract is compiled to its own .toc/.abi entry. PackageOptions path overrides (ArtifactPath, InterfacePath, InterfaceName) are applied only when there is exactly one contract; they are ignored for multi-contract packages.

func CompileSourceToBytecode

func CompileSourceToBytecode(source []byte, name string) ([]byte, error)

CompileSourceToBytecode compiles Lua source into deterministic bytecode.

func EncodeArtifact

func EncodeArtifact(a *Artifact) ([]byte, error)

EncodeArtifact serializes a compiled artifact into deterministic binary bytes.

func EncodeFunctionProto

func EncodeFunctionProto(proto *FunctionProto) ([]byte, error)

EncodeFunctionProto serializes an executable function prototype into a deterministic bytecode blob.

func EncodePackage

func EncodePackage(manifestJSON []byte, files map[string][]byte) ([]byte, error)

EncodePackage serializes manifest + files into deterministic .tor bytes.

func IsArtifact

func IsArtifact(data []byte) bool

IsArtifact reports whether the input starts with .toc magic bytes.

func IsBytecode

func IsBytecode(data []byte) bool

IsBytecode reports whether the input starts with tolang bytecode magic bytes.

func IsPackage

func IsPackage(data []byte) bool

IsPackage reports whether input starts with local-file ZIP magic.

func LVAsBool

func LVAsBool(v LValue) bool

LVIsFalse returns false if a given LValue is a nil or false otherwise true.

func LVAsString

func LVAsString(v LValue) string

LVAsString returns string representation of a given LValue if the LValue is a string or number, otherwise an empty string.

func LVCanConvToString

func LVCanConvToString(v LValue) bool

LVCanConvToString returns true if a given LValue is a string or number otherwise false.

func LVIsFalse

func LVIsFalse(v LValue) bool

LVIsFalse returns true if a given LValue is a nil or false otherwise false.

func Lu256Cmp

func Lu256Cmp(a, b LUint256) int

Lu256Cmp is the exported comparison function for LUint256. Returns -1 if a < b, 0 if a == b, +1 if a > b.

func NewOSFileResolver

func NewOSFileResolver(baseDir string) sema.FileResolver

NewOSFileResolver returns a FileResolver that resolves paths relative to baseDir.

func OpenBase

func OpenBase(L *LState) int

func OpenMath

func OpenMath(L *LState) int

func OpenString

func OpenString(L *LState) int

func OpenTable

func OpenTable(L *LState) int

func PackageHash

func PackageHash(data []byte) string

PackageHash computes blake3 hash of a .tor archive.

func ParseModule

func ParseModule(source []byte, name string) (*ast.Module, error)

ParseModule parses TOL source into a syntax tree.

func SignPackage

func SignPackage(pkgBytes []byte, privKeySeed []byte) ([]byte, error)

SignPackage adds an ed25519 publisher signature to an existing .tor archive. privKeySeed must be a 32-byte ed25519 seed (hex-encoded or raw bytes). Returns the new .tor bytes with publisher_key and signature embedded in manifest.json.

func UpvalueIndex

func UpvalueIndex(i int) int

func ValidateInterface

func ValidateInterface(data []byte) error

ValidateInterface performs a lightweight structural validation for textual .abi content.

func VerifyPackageSignature

func VerifyPackageSignature(pkgBytes []byte) error

VerifyPackageSignature verifies the ed25519 publisher signature embedded in a .tor archive. Returns nil if the package is unsigned (no signature field) — unsigned packages are accepted. Returns an error if a signature is present but invalid or the public key is malformed.

func VerifySourceHash

func VerifySourceHash(art *Artifact, source []byte) error

VerifySourceHash checks whether a decoded artifact matches the given source bytes.

Types

type ApiError

type ApiError struct {
	Type       ApiErrorType
	Object     LValue
	StackTrace string
	// Underlying error. This attribute is set only if the Type is ApiErrorFile or ApiErrorSyntax
	Cause error
}

func (*ApiError) Error

func (e *ApiError) Error() string

type ApiErrorType

type ApiErrorType int
const (
	ApiErrorSyntax ApiErrorType = iota
	ApiErrorFile
	ApiErrorRun
	ApiErrorError
	ApiErrorPanic
)

type Artifact

type Artifact struct {
	Version           uint16
	Compiler          string
	ContractName      string
	Bytecode          []byte
	ABIJSON           []byte
	StorageLayoutJSON []byte
	SourceHash        string
	BytecodeHash      string
	// Gas metadata (ArtifactFormatVersion >= 2)
	MaxStackSlots         uint32
	BytecodeLen           uint32
	ContainsUnboundedLoop bool
}

Artifact is a decoded .toc payload.

func CompileAllArtifacts

func CompileAllArtifacts(source []byte, name string, opts *CompileOptions) ([]*Artifact, error)

CompileAllArtifacts compiles all contracts in a multi-contract TOL source file, returning one Artifact per contract.

func DecodeArtifact

func DecodeArtifact(data []byte) (*Artifact, error)

DecodeArtifact deserializes a .toc payload into a structured artifact.

type ArtifactOptions

type ArtifactOptions struct {
	// IncludeSourceMap controls whether embedded bytecode contains source map/debug metadata.
	// Default is false for reproducible builds.
	IncludeSourceMap bool

	// PackageSearchPaths provides explicit directories for package-style import
	// resolution, passed through to the underlying CompileOptions.
	PackageSearchPaths []string
}

ArtifactOptions controls .artifact compilation behavior.

type CompileError

type CompileError struct {
	Line    int
	Message string
	// contains filtered or unexported fields
}

func (*CompileError) Error

func (e *CompileError) Error() string

type CompileOptions

type CompileOptions struct {
	// IncludeSourceMap controls whether debug metadata (source map / line table /
	// local/call/upvalue debug sections) is embedded in output bytecode.
	// Default is false for reproducible builds.
	IncludeSourceMap bool

	// PackageSearchPaths provides explicit directories where package-style
	// imports are resolved before falling back to the directory-walk heuristic.
	// This eliminates the need for synthetic compile paths in tests.
	PackageSearchPaths []string
}

CompileOptions controls bytecode debug metadata emission.

type DbgCall

type DbgCall struct {
	Name string
	Pc   int
}

type DbgLocalInfo

type DbgLocalInfo struct {
	Name    string
	Reg     int
	Attr    uint8
	StartPc int
	EndPc   int
}

type Debug

type Debug struct {
	Name            string
	What            string
	Source          string
	CurrentLine     int
	NUpvalues       int
	LineDefined     int
	LastLineDefined int
	// contains filtered or unexported fields
}

type FunctionProto

type FunctionProto struct {
	SourceName         string
	LineDefined        int
	LastLineDefined    int
	NumUpvalues        uint8
	NumParameters      uint8
	IsVarArg           uint8
	NumUsedRegisters   uint8
	Code               []uint32
	Constants          []LValue
	FunctionPrototypes []*FunctionProto

	DbgSourcePositions []int
	DbgLocals          []*DbgLocalInfo
	DbgCalls           []DbgCall
	DbgUpvalues        []string
	// contains filtered or unexported fields
}

func Compile

func Compile(chunk []ast.Stmt, name string) (proto *FunctionProto, err error)

Compile compiles AST statements using a multi-stage pipeline: AST -> IR -> bytecode(FunctionProto).

func CompileIR

func CompileIR(program *IRProgram) (*FunctionProto, error)

CompileIR lowers IR back to executable FunctionProto bytecode.

func DecodeFunctionProto

func DecodeFunctionProto(data []byte) (*FunctionProto, error)

DecodeFunctionProto deserializes a bytecode blob into an executable function prototype.

func (*FunctionProto) String

func (fp *FunctionProto) String() string

type Global

type Global struct {
	MainThread    *LState
	CurrentThread *LState
	Registry      *LTable
	Global        *LTable
	// contains filtered or unexported fields
}

type IRFunction

type IRFunction struct {
	SourceName      string
	LineDefined     int
	LastLineDefined int
	NumUpvalues     uint8
	NumParameters   uint8
	IsVarArg        uint8
	NumUsedRegs     uint8

	Instructions []IRInstruction
	Constants    []LValue
	Functions    []*IRFunction

	DbgSourcePositions []int
	DbgLocals          []*DbgLocalInfo
	DbgCalls           []DbgCall
	DbgUpvalues        []string
}

IRFunction mirrors FunctionProto but stores decoded instructions.

type IRInstruction

type IRInstruction struct {
	Op   int
	Type opType
	A    int
	B    int
	C    int
	Bx   int
	Sbx  int
	Raw  uint32
}

IRInstruction is a normalized representation of one VM instruction. It keeps decoded operands and original op encoding kind.

type IRProgram

type IRProgram struct {
	Name string
	Root *IRFunction
}

IRProgram is a compiled unit root.

func BuildIR

func BuildIR(source []byte, name string) (*IRProgram, error)

BuildIR parses and type-checks TOL source and prepares lowering to VM IR. Import declarations are resolved relative to the directory of name using the OS filesystem.

func BuildIRFromChunk

func BuildIRFromChunk(chunk []ast.Stmt, name string) (*IRProgram, error)

BuildIRFromChunk compiles a Lua AST chunk to the IR layer.

func BuildIRFromLowered

func BuildIRFromLowered(prog *lower.Program, name string) (*IRProgram, error)

BuildIRFromLowered lowers a typed/lowered TOL program directly into VM IR (runtime mode). The emitted artifact contains tos.oninvoke dispatch but no constructor entry point.

func BuildIRFromLoweredInit

func BuildIRFromLoweredInit(prog *lower.Program, name string) (*IRProgram, error)

BuildIRFromLoweredInit lowers a typed/lowered TOL program into VM IR for the init artifact. The emitted artifact contains only the constructor, called directly at module top-level (no tos.oninvoke, no tos.oncreate wrapper). Used for init_code in the init/runtime split.

func BuildIRFromProto

func BuildIRFromProto(proto *FunctionProto, name string) *IRProgram

BuildIRFromProto decodes a FunctionProto into IR.

func BuildIRWithResolver

func BuildIRWithResolver(source []byte, name string, resolver sema.FileResolver) (*IRProgram, error)

BuildIRWithResolver is like BuildIR but uses the provided resolver for import resolution. Pass nil to disable import resolution.

func (*IRProgram) String

func (p *IRProgram) String() string

type InterfaceInfo

type InterfaceInfo struct {
	Version       string
	InterfaceName string
	FunctionCount int
	EventCount    int
}

InterfaceInfo is lightweight metadata extracted from textual .abi content.

func InspectInterface

func InspectInterface(data []byte) (*InterfaceInfo, error)

InspectInterface validates and extracts lightweight metadata from textual .abi content.

type InterfaceOptions

type InterfaceOptions struct {
	InterfaceName string // interface name to emit (defaults to "I"+ContractName)
	ContractName  string // which contract to render (defaults to first contract in module)
}

InterfaceOptions configures .abi textual generation.

type LAgent

type LAgent string

func (LAgent) Format

func (ad LAgent) Format(f fmt.State, c rune)

fmt.Formatter interface

func (LAgent) String

func (ad LAgent) String() string

func (LAgent) Type

func (ad LAgent) Type() LValueType

type LBool

type LBool bool

func (LBool) String

func (bl LBool) String() string

func (LBool) Type

func (bl LBool) Type() LValueType

type LFunction

type LFunction struct {
	IsG       bool
	Env       *LTable
	Proto     *FunctionProto
	GFunction LGFunction
	Upvalues  []*Upvalue
}

func (*LFunction) LocalName

func (fn *LFunction) LocalName(regno, pc int) (string, bool)

func (*LFunction) String

func (fn *LFunction) String() string

func (*LFunction) Type

func (fn *LFunction) Type() LValueType

type LGFunction

type LGFunction func(*LState) int

type LNilType

type LNilType struct{}

func (*LNilType) String

func (nl *LNilType) String() string

func (*LNilType) Type

func (nl *LNilType) Type() LValueType

type LState

type LState struct {
	G       *Global
	Env     *LTable
	Panic   func(*LState)
	Dead    bool
	Options Options
	// contains filtered or unexported fields
}

func NewState

func NewState(opts ...Options) *LState

func (*LState) ArgError

func (ls *LState) ArgError(n int, message string)

func (*LState) Call

func (ls *LState) Call(nargs, nret int)

func (*LState) CallByParam

func (ls *LState) CallByParam(cp P, args ...LValue) error

func (*LState) CallMeta

func (ls *LState) CallMeta(obj LValue, event string) LValue

func (*LState) CheckAgent

func (ls *LState) CheckAgent(n int) LAgent

func (*LState) CheckAny

func (ls *LState) CheckAny(n int) LValue

func (*LState) CheckBool

func (ls *LState) CheckBool(n int) bool

func (*LState) CheckFunction

func (ls *LState) CheckFunction(n int) *LFunction

func (*LState) CheckInt

func (ls *LState) CheckInt(n int) int

func (*LState) CheckInt64

func (ls *LState) CheckInt64(n int) int64

func (*LState) CheckOption

func (ls *LState) CheckOption(n int, options []string) int

func (*LState) CheckString

func (ls *LState) CheckString(n int) string

func (*LState) CheckTable

func (ls *LState) CheckTable(n int) *LTable

func (*LState) CheckType

func (ls *LState) CheckType(n int, typ LValueType)

func (*LState) CheckTypes

func (ls *LState) CheckTypes(n int, typs ...LValueType)

func (*LState) CheckUint256

func (ls *LState) CheckUint256(n int) LUint256

func (*LState) CheckUserData

func (ls *LState) CheckUserData(n int) *LUserData

func (*LState) Close

func (ls *LState) Close()

func (*LState) Concat

func (ls *LState) Concat(values ...LValue) string

func (*LState) CreateTable

func (ls *LState) CreateTable(acap, hcap int) *LTable

func (*LState) DoBytecode

func (ls *LState) DoBytecode(data []byte) error

DoBytecode executes precompiled bytecode.

func (*LState) DoString

func (ls *LState) DoString(source string) error

func (*LState) Equal

func (ls *LState) Equal(lhs, rhs LValue) bool

func (*LState) Error

func (ls *LState) Error(lv LValue, level int)

This function is equivalent to lua_error( http://www.lua.org/manual/5.1/manual.html#lua_error ).

func (*LState) FindTable

func (ls *LState) FindTable(obj *LTable, n string, size int) LValue

func (*LState) ForEach

func (ls *LState) ForEach(tb *LTable, cb func(LValue, LValue))

func (*LState) GPCall

func (ls *LState) GPCall(fn LGFunction, data LValue) error

func (*LState) GasUsed

func (ls *LState) GasUsed() uint64

GasUsed returns the number of VM instructions executed so far.

func (*LState) Get

func (ls *LState) Get(idx int) LValue

func (*LState) GetFEnv

func (ls *LState) GetFEnv(obj LValue) LValue

func (*LState) GetField

func (ls *LState) GetField(obj LValue, skey string) LValue

func (*LState) GetGlobal

func (ls *LState) GetGlobal(name string) LValue

func (*LState) GetInfo

func (ls *LState) GetInfo(what string, dbg *Debug, fn LValue) (LValue, error)

func (*LState) GetLocal

func (ls *LState) GetLocal(dbg *Debug, no int) (string, LValue)

func (*LState) GetMetaField

func (ls *LState) GetMetaField(obj LValue, event string) LValue

func (*LState) GetMetatable

func (ls *LState) GetMetatable(obj LValue) LValue

func (*LState) GetStack

func (ls *LState) GetStack(level int) (*Debug, bool)

func (*LState) GetTable

func (ls *LState) GetTable(obj LValue, key LValue) LValue

func (*LState) GetTop

func (ls *LState) GetTop() int

func (*LState) GetTypeMetatable

func (ls *LState) GetTypeMetatable(typ string) LValue

func (*LState) GetUpvalue

func (ls *LState) GetUpvalue(fn *LFunction, no int) (string, LValue)

func (*LState) Insert

func (ls *LState) Insert(value LValue, index int)

func (*LState) IsClosed

func (ls *LState) IsClosed() bool

func (*LState) LessThan

func (ls *LState) LessThan(lhs, rhs LValue) bool

func (*LState) Load

func (ls *LState) Load(reader io.Reader, name string) (*LFunction, error)

func (*LState) LoadBytecode

func (ls *LState) LoadBytecode(data []byte) (*LFunction, error)

LoadBytecode loads a precompiled bytecode blob.

func (*LState) LoadIR

func (ls *LState) LoadIR(program *IRProgram) (*LFunction, error)

LoadIR compiles IR into bytecode and returns an executable Lua function.

func (*LState) LoadString

func (ls *LState) LoadString(source string) (*LFunction, error)

func (*LState) NewClosure

func (ls *LState) NewClosure(fn LGFunction, upvalues ...LValue) *LFunction

func (*LState) NewFunction

func (ls *LState) NewFunction(fn LGFunction) *LFunction

func (*LState) NewFunctionFromProto

func (ls *LState) NewFunctionFromProto(proto *FunctionProto) *LFunction

func (*LState) NewTable

func (ls *LState) NewTable() *LTable

func (*LState) NewTypeMetatable

func (ls *LState) NewTypeMetatable(typ string) *LTable

func (*LState) NewUserData

func (ls *LState) NewUserData() *LUserData

func (*LState) Next

func (ls *LState) Next(tb *LTable, key LValue) (LValue, LValue)

func (*LState) ObjLen

func (ls *LState) ObjLen(v1 LValue) int

func (*LState) OpenLibs

func (ls *LState) OpenLibs()

OpenLibs loads the built-in libraries. It is equivalent to running OpenLoad, then OpenBase, then iterating over the other OpenXXX functions in any order.

func (*LState) OptAgent

func (ls *LState) OptAgent(n int, d LAgent) LAgent

func (*LState) OptBool

func (ls *LState) OptBool(n int, d bool) bool

func (*LState) OptFunction

func (ls *LState) OptFunction(n int, d *LFunction) *LFunction

func (*LState) OptInt

func (ls *LState) OptInt(n int, d int) int

func (*LState) OptInt64

func (ls *LState) OptInt64(n int, d int64) int64

func (*LState) OptString

func (ls *LState) OptString(n int, d string) string

func (*LState) OptTable

func (ls *LState) OptTable(n int, d *LTable) *LTable

func (*LState) OptUint256

func (ls *LState) OptUint256(n int, d LUint256) LUint256

func (*LState) OptUserData

func (ls *LState) OptUserData(n int, d *LUserData) *LUserData

func (*LState) PCall

func (ls *LState) PCall(nargs, nret int, errfunc *LFunction) (err error)

func (*LState) Pop

func (ls *LState) Pop(n int)

func (*LState) PreloadModule

func (ls *LState) PreloadModule(name string, loader LGFunction)

Set a module loader to the package.preload table.

func (*LState) Push

func (ls *LState) Push(value LValue)

func (*LState) RaiseError

func (ls *LState) RaiseError(format string, args ...interface{})

This function is equivalent to luaL_error( http://www.lua.org/manual/5.1/manual.html#luaL_error ).

func (*LState) RawEqual

func (ls *LState) RawEqual(lhs, rhs LValue) bool

func (*LState) RawGet

func (ls *LState) RawGet(tb *LTable, key LValue) LValue

func (*LState) RawGetInt

func (ls *LState) RawGetInt(tb *LTable, key int) LValue

func (*LState) RawSet

func (ls *LState) RawSet(tb *LTable, key LValue, value LValue)

func (*LState) RawSetInt

func (ls *LState) RawSetInt(tb *LTable, key int, value LValue)

func (*LState) Register

func (ls *LState) Register(name string, fn LGFunction)

func (*LState) RegisterModule

func (ls *LState) RegisterModule(name string, funcs map[string]LGFunction) LValue

func (*LState) Remove

func (ls *LState) Remove(index int)

func (*LState) RemoveCallerFrame

func (ls *LState) RemoveCallerFrame() *callFrame

RemoveCallerFrame removes the stack frame above the current stack frame. This is useful in tail calls. It returns the new current frame.

func (*LState) Replace

func (ls *LState) Replace(idx int, value LValue)

func (*LState) SetFEnv

func (ls *LState) SetFEnv(obj LValue, env LValue)

func (*LState) SetField

func (ls *LState) SetField(obj LValue, key string, value LValue)

func (*LState) SetFuncs

func (ls *LState) SetFuncs(tb *LTable, funcs map[string]LGFunction, upvalues ...LValue) *LTable

func (*LState) SetGasLimit

func (ls *LState) SetGasLimit(limit uint64)

SetGasLimit configures the maximum number of VM instructions this LState may execute. Must be called before DoString/DoFile/Call. Zero means unlimited.

func (*LState) SetGlobal

func (ls *LState) SetGlobal(name string, value LValue)

func (*LState) SetLineHook

func (ls *LState) SetLineHook(fn func(string, int))

SetLineHook installs a hook function that is called after each VM instruction with the FunctionProto.SourceName and the source line from DbgSourcePositions. Pass nil to disable. Host hooks are disabled by default and must be enabled with Options.AllowHostHooks for off-chain testing/debugging only.

func (*LState) SetLocal

func (ls *LState) SetLocal(dbg *Debug, no int, lv LValue) string

func (*LState) SetMetatable

func (ls *LState) SetMetatable(obj LValue, mt LValue)

func (*LState) SetTable

func (ls *LState) SetTable(obj LValue, key LValue, value LValue)

func (*LState) SetTop

func (ls *LState) SetTop(idx int)

func (*LState) SetUpvalue

func (ls *LState) SetUpvalue(fn *LFunction, no int, lv LValue) string

func (*LState) ToAgent

func (ls *LState) ToAgent(n int) LAgent

func (*LState) ToBool

func (ls *LState) ToBool(n int) bool

func (*LState) ToFunction

func (ls *LState) ToFunction(n int) *LFunction

func (*LState) ToInt

func (ls *LState) ToInt(n int) int

func (*LState) ToInt64

func (ls *LState) ToInt64(n int) int64

func (*LState) ToString

func (ls *LState) ToString(n int) string

func (*LState) ToStringMeta

func (ls *LState) ToStringMeta(lv LValue) LValue

ToStringMeta returns string representation of given LValue. This method calls the `__tostring` meta method if defined. If __tostring is absent but __name is in the metatable, falls back to the stable type label in __name. Unlike stock Lua, TOL must never expose host pointer addresses in contract-visible strings.

func (*LState) ToTable

func (ls *LState) ToTable(n int) *LTable

func (*LState) ToUint256

func (ls *LState) ToUint256(n int) LUint256

func (*LState) ToUserData

func (ls *LState) ToUserData(n int) *LUserData

func (*LState) TypeError

func (ls *LState) TypeError(n int, typ LValueType)

func (*LState) Where

func (ls *LState) Where(level int) string

type LString

type LString string

func (LString) Format

func (st LString) Format(f fmt.State, c rune)

fmt.Formatter interface

func (LString) String

func (st LString) String() string

func (LString) Type

func (st LString) Type() LValueType

type LTable

type LTable struct {
	Metatable LValue
	// contains filtered or unexported fields
}

func (*LTable) Append

func (tb *LTable) Append(value LValue)

Append appends a given LValue to this LTable.

func (*LTable) ForEach

func (tb *LTable) ForEach(cb func(LValue, LValue))

ForEach iterates over this table of elements, yielding each in turn to a given function.

func (*LTable) Insert

func (tb *LTable) Insert(i int, value LValue)

Insert inserts a given LValue at position `i` in this table.

func (*LTable) InsertWithCost

func (tb *LTable) InsertWithCost(i int, value LValue) int

func (*LTable) Len

func (tb *LTable) Len() int

Len returns length of this LTable without using __len.

func (*LTable) LenWithCost

func (tb *LTable) LenWithCost() (int, int)

func (*LTable) MaxN

func (tb *LTable) MaxN() int

MaxN returns a maximum number key that nil value does not exist before it.

func (*LTable) MaxNWithCost

func (tb *LTable) MaxNWithCost() (int, int)

func (*LTable) Next

func (tb *LTable) Next(key LValue) (LValue, LValue)

This function is equivalent to lua_next ( http://www.lua.org/manual/5.1/manual.html#lua_next ).

func (*LTable) NextWithCost

func (tb *LTable) NextWithCost(key LValue) (LValue, LValue, int)

func (*LTable) RawGet

func (tb *LTable) RawGet(key LValue) LValue

RawGet returns an LValue associated with a given key without __index metamethod.

func (*LTable) RawGetH

func (tb *LTable) RawGetH(key LValue) LValue

RawGet returns an LValue associated with a given key without __index metamethod.

func (*LTable) RawGetInt

func (tb *LTable) RawGetInt(key int) LValue

RawGetInt returns an LValue at position `key` without __index metamethod.

func (*LTable) RawGetString

func (tb *LTable) RawGetString(key string) LValue

RawGetString returns an LValue associated with a given key without __index metamethod.

func (*LTable) RawSet

func (tb *LTable) RawSet(key LValue, value LValue)

RawSet sets a given LValue to a given index without the __newindex metamethod. It is recommended to use `RawSetString` or `RawSetInt` for performance if you already know the given LValue is a string or number.

func (*LTable) RawSetH

func (tb *LTable) RawSetH(key LValue, value LValue)

RawSetH sets a given LValue to a given index without the __newindex metamethod.

func (*LTable) RawSetInt

func (tb *LTable) RawSetInt(key int, value LValue)

RawSetInt sets a given LValue at a position `key` without the __newindex metamethod.

func (*LTable) RawSetString

func (tb *LTable) RawSetString(key string, value LValue)

RawSetString sets a given LValue to a given string index without the __newindex metamethod.

func (*LTable) Remove

func (tb *LTable) Remove(pos int) LValue

Remove removes from this table the element at a given position.

func (*LTable) RemoveWithCost

func (tb *LTable) RemoveWithCost(pos int) (LValue, int)

func (*LTable) String

func (tb *LTable) String() string

func (*LTable) Type

func (tb *LTable) Type() LValueType

type LUint256

type LUint256 struct {
	// contains filtered or unexported fields
}

LUint256 is a 256-bit unsigned integer stored as four 64-bit words in little-endian order: lo holds bits 0–63, ml bits 64–127, mh bits 128–191, hi bits 192–255. Simple operations (add, sub, bitwise, shifts, compare) are implemented natively with math/bits; complex operations (div, mod, pow) bridge to math/big.Int.

func LVAsUint256

func LVAsUint256(v LValue) LUint256

LVAsUint256 tries to convert a given LValue to a uint256.

func Lu256FromUint64

func Lu256FromUint64(v uint64) LUint256

Lu256FromUint64 creates an LUint256 from a uint64.

func (LUint256) Format

func (nm LUint256) Format(f fmt.State, c rune)

fmt.Formatter interface

func (LUint256) String

func (nm LUint256) String() string

func (LUint256) Type

func (nm LUint256) Type() LValueType

type LUserData

type LUserData struct {
	Value     interface{}
	Env       *LTable
	Metatable LValue
}

func (*LUserData) String

func (ud *LUserData) String() string

func (*LUserData) Type

func (ud *LUserData) Type() LValueType

type LValue

type LValue interface {
	String() string
	Type() LValueType
}

type LValueType

type LValueType int
const (
	LTNil LValueType = iota
	LTBool
	LTUint256
	LTString
	LTAgent
	LTFunction
	LTUserData
	LTTable
)

func (LValueType) String

func (vt LValueType) String() string

type OSFileResolver

type OSFileResolver struct {
	BaseDir            string
	PackageSearchPaths []string
}

OSFileResolver is a sema.FileResolver that reads files from the OS filesystem. Relative import paths are resolved against BaseDir.

PackageSearchPaths provides explicit directories where package-style imports are resolved before falling back to the walk-up heuristic. Each entry is a root directory that may contain package family subdirectories (e.g., if PackageSearchPaths includes "/repo/openlib" then "tolang.openlib.account" will check "/repo/openlib/account/" first).

func (*OSFileResolver) ListPackage

func (r *OSFileResolver) ListPackage(pkgPath string) ([]string, error)

ListPackage implements sema.PackageLister. It returns the names of all TOL contracts/interfaces available in pkgPath by scanning the corresponding directory (e.g. "tol.lang" -> <base>/tol/lang/). Only files with recognised TOL extensions (.tol, .abi, .toc, .tor) are listed; the extension is stripped to produce the bare contract name.

func (*OSFileResolver) Resolve

func (r *OSFileResolver) Resolve(importingFile string, importPath string, importName string) ([]byte, string, error)

type OpenlibReleaseArtifacts

type OpenlibReleaseArtifacts struct {
	ArtifactPath  string
	ArtifactTOC   []byte
	InterfacePath string
	InterfaceABI  []byte
	InitPath      string
	InitTOC       []byte
	PackageTOR    []byte
}

OpenlibReleaseArtifacts is the deterministic release payload generated from a openlib source file.

func BuildOpenlibReleaseArtifacts

func BuildOpenlibReleaseArtifacts(source []byte, sourcePath string, entry OpenlibReleaseEntry) (*OpenlibReleaseArtifacts, error)

BuildOpenlibReleaseArtifacts compiles a openlib source file into deterministic release artifacts (.toc/.abi/init .toc if needed/.tor).

type OpenlibReleaseEntry

type OpenlibReleaseEntry struct {
	Family             string
	Contract           string
	SourcePath         string
	SourcePackagePath  string
	ReleasePackageName string
}

OpenlibReleaseEntry describes one published openlib contract artifact set.

func OpenlibReleaseCatalog

func OpenlibReleaseCatalog() []OpenlibReleaseEntry

OpenlibReleaseCatalog returns the published openlib contract set.

type Options

type Options struct {
	// Call stack size. This defaults to `lua.CallStackSize`.
	CallStackSize int
	// Data stack size. This defaults to `lua.RegistrySize`.
	RegistrySize int
	// Allow the registry to grow from the registry size specified up to a value of RegistryMaxSize. A value of 0
	// indicates no growth is permitted. The registry will not shrink again after any growth.
	RegistryMaxSize int
	// If growth is enabled, step up by an additional `RegistryGrowStep` each time to avoid having to resize too often.
	// This defaults to `lua.RegistryGrowStep`
	RegistryGrowStep int
	// Controls whether or not libraries are opened by default
	SkipOpenLibs bool
	// Tells whether a Go stacktrace should be included in a Lua stacktrace when panics occur.
	IncludeGoStackTrace bool
	// If `MinimizeStackMemory` is set, the call stack will be automatically grown or shrank up to a limit of
	// `CallStackSize` in order to minimize memory usage. This does incur a slight performance penalty.
	MinimizeStackMemory bool
	// AllowHostHooks enables host-installed debug hooks such as SetLineHook.
	// It is disabled by default so consensus execution remains gas-driven only.
	AllowHostHooks bool
}

Options is a configuration that is used to create a new LState.

type P

type P struct {
	Fn      LValue
	NRet    int
	Protect bool
	Handler *LFunction
}

type Package

type Package struct {
	ManifestJSON []byte
	Files        map[string][]byte // excludes manifest.json
}

Package is a decoded .tor archive payload.

func DecodePackage

func DecodePackage(data []byte) (*Package, error)

DecodePackage deserializes .tor bytes and validates manifest/files.

type PackageOptions

type PackageOptions struct {
	PackageName    string
	PackageVersion string
	ArtifactPath   string
	InterfacePath  string
	InterfaceName  string
	// IncludeSourceMap controls whether embedded .toc bytecode contains source map/debug metadata.
	// nil means default-off for reproducible builds.
	IncludeSourceMap *bool
	IncludeSource    bool
	SourcePath       string
	// SigningKey is an ed25519 private key seed (32 bytes) used to sign the package.
	// If nil, the package is produced unsigned. Unsigned packages are always accepted.
	SigningKey []byte
}

PackageOptions configures one-shot .tol -> .tor compilation.

type Upvalue

type Upvalue struct {
	// contains filtered or unexported fields
}

func (*Upvalue) Close

func (uv *Upvalue) Close()

func (*Upvalue) IsClosed

func (uv *Upvalue) IsClosed() bool

func (*Upvalue) SetValue

func (uv *Upvalue) SetValue(value LValue)

func (*Upvalue) Value

func (uv *Upvalue) Value() LValue

Directories

Path Synopsis
cmd
openlib-export command
tolang command
Package metadata defines the stable, versioned metadata schema for the GTOS 2046 architecture.
Package metadata defines the stable, versioned metadata schema for the GTOS 2046 architecture.
Lua pattern match functions for Go
Lua pattern match functions for Go
tol
ast
format
Package format implements canonical formatting for TOL source files.
Package format implements canonical formatting for TOL source files.
test
Package toltest provides the P2 test runner for TOL test blocks.
Package toltest provides the P2 test runner for TOL test blocks.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址