Repository navigation
Add the Sand language, language server, and Zed support - #507
ThatOneToast wants to merge 83 commits into
Conversation
Introduce `.sand` source files that compile through the portable program backend, so packs need neither Cargo nor sand.toml. - sand-lang: parser, analysis, execution-context inference, typed vanilla values, naming lints, and editor queries with position-aware completion - sand-lsp and `sand lsp`: diagnostics, hover, completion, signature help, navigation, and rename - `sand lang new|check|build|run|emit|zed`; `sand run` also accepts language projects - Portable model: arithmetic, control flow, text, entities and entity State, attributes, teleport, player events, custom items, recipes, and tags - Generated `sand::vanilla::ParticleType` and `Attribute` registries - tree-sitter grammar and Zed extension Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
Add custom events, timers, world actions and conditions, boss bars, single-pool loot tables, and smithing upgrades to the Sand language and the portable program, with completion, hover, highlighting, and docs. Portable output now runs through the same final 26.3 resource-schema pass as Rust export, so packs targeting 26.3 emit predicates with `type` and load instead of failing registry parsing. Player loops keep Rust's contract of changing the executor only; event dispatch runs at the player, as Rust's does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… the Sand language Calls that can re-enter their caller save the caller's locals, parameters, and temporaries on a command-storage stack (PushFrame/PopFrame) and restore them afterwards; other calls compile exactly as before. Self-calls and arguments that call functions are computed into temporaries before any parameter is written. Loops gain `for i in a..b` / `a..=b`, `loop`, `break`, and `continue` inside `while`; `while` accepts any condition. Functions returning bool can be used directly as conditions. The portable program gains DataGet for reading entity data such as health and food. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`Player.health`, `Player.food`, and other entity data read as typed values; every attribute is a property that can be read and assigned, such as `Player.max_health = 40.0;` or `zombie.scale *= 2.0;`. Loop bindings act as handles for the entity they run as. get_attribute and set_attribute are removed in favour of properties. Editors complete properties after a handle, show their type and whether they are writable, and complete break, continue, loop, and counting for. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`as` converts between number, float, bool, and enums with one rule shared by constants and run time, and explains impossible casts. Unary minus binds tighter than `as`, as in Rust. `emit Name(args);` replaces the emit builtin, handlers may ignore an event's payload, and the old spelling gets a fix-it message. Keyword hover covers loops, jumps, casts, and emit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…itter grammar Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…face The language guide covers counting for, loop, break and continue, any while condition, recursion and how frames are saved, the cast table, Player and loop-handle properties, and payload-free event handlers. API surface tests record the frame, entity-data, and EntityData method additions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
.sandfiles express gameplay and compile through the portable backend shared with Rust and JSON packs. Language projects need neither Cargo norsand.toml.Language and runtime
number, fixed-pointfloat,bool, enums), constants, modules, imports, and privacy.::<...>, including qualified constructors and method parameters. Instances have separate slots and context inference, bounded expansion, and authored source identities for navigation/rename. Concrete signatures drive nested-type signature help and call-result completions.[T; N]) support literals/repeats, nested values, indexed reads/writes, borrowed element methods, snapshot iteration, andlen/is_empty/contains/get_or/fill. Runtime invalid reads return the element default; invalid writes and mutable method calls leave the target unchanged.Vec<T>values reuse typed owned storage across State, records, arguments/returns and events, including recursive records through vectors. Indexing and mutable element methods use frozen addresses. Bounded push/pop/insert/remove/extend/clear/truncate, deep equality, array conversion, and snapshot iteration have native proofs. Strings can also be iterated by Unicode scalar character.stringvalues work in State, structs, arrays, constants, parameters, returns, and event payloads. Concatenation, equality, Unicode scalar indexing/slicing, substring methods, and scalar/enumto_stringshare the typed value/call/frame model. Runtime messages display plain text; styled formats may interpolate stored strings.EntityRefvalues use the canonical pack-owned runtime identity allocator. Explicit entity/player resolution skips absent entities; online players resolve across dimensions.damage(amount, by = reference)preserves attacker kill credit.Self, valueself/mut selfreceivers, State&self/&mut selfreceivers, visibility, method imports and executor inference. Read-only State receivers reject direct writes, mutable method calls, timer mutation and State detachment.start_timerticks/seconds, with positive range guards and checked seconds conversion. Invalid runtime durations leave the timer unchanged.matchwith constant alternatives, loops, counting ranges,.rev(),.step_by(n), and loop jumps. Range bounds and runtime command arguments evaluate once in source order.Tools
sand lang new|check|build|run|emit|zed;sand runrecognizes language projects.sand fmtandsand lang fmt, including--check.The guide, parity table, and remaining expansion checklist are in
book/src/language.mdandROADMAP.md.Remaining scope
Remaining expansions include enum payloads, executor-specific callable signatures, general borrowed slices, richer inventory and entity operations, broader event hooks, waits inside control flow, server continuations, world and gameplay resources beyond the shipped batch, higher-level Rust gameplay systems, and breakpoints. The roadmap records the remaining scope and the limits of the implemented features.
Validation
scripts/check.sh; the latest expansion checkpoint has focused compiler/LSP and portable-backend tests plus native proofs. The final full repository gate remains pending while the broader expansion continues.git diff --checkpasses.Latest expansion checkpoint: ten vanilla borrowed-receiver assertions pass. The two-player probe verifies identity across reload, cross-dimension player resolution, empty/dead reference handling, and separate vanilla kill credit. A maintained marked-combat example combines retained ownership, entity timers, recipes and mutable methods.
Fixed-array checkpoint: 40 assertions pass on vanilla 26.2, including nested records, independent copies, recursion, indexed mutable receivers, invalid indices, snapshot iteration, and loop jumps. The quest-board example builds without warnings. Array formatting, completions, signatures, and generated tree-sitter parsing have focused regression coverage. The final full repository check remains pending while the broader expansion continues.
Runtime-text checkpoint: 66 assertions pass on vanilla 26.2, including integer/fixed-point limits, Unicode, control characters, arbitrary literal macro-like text, recursive calls and borrowed methods, events, and entity attach/detach. The two-player probe verifies independent text values across reload and exercises runtime chat. All language/LSP tests, focused portable storage and ownership tests, API coverage guards, Python harness regressions, Clippy, formatting, schema generation checks, documentation links and
git diff --checkpass. The saved journal example builds without warnings; tree-sitter parses the text fixture without errors. The full repository gate must still run against the final expansion.Vector checkpoint: 95 assertions pass on vanilla 26.2, including recursive records, event copies, snapshots, loop jumps, capacity boundaries, and a reproduced stale-read regression after entity-State detachment. The two-player probe verifies independent vectors across reload and retains all entity-resolution/kill-credit checks. Array (40) and text (66) native regression fixtures pass. All language/LSP tests, Clippy, Python checks, schema checks, generated tree-sitter parsing, documentation links and whitespace checks pass; the exploration-log example builds without warnings. Expanded constant text and State defaults have checked allocation budgets. Indexed receivers now offer editor completion/signatures. The final full repository gate remains pending until the requested expansion is finished.
Pattern checkpoint: 29 native assertions pass on vanilla 26.2 with repeated invocations and reload, including selected-only evaluation, scrutinee snapshots, recursive owned results, deep destructuring copies and loop control. The existing 20-assertion control-flow native regression passes. Focused pattern/IDE/parser tests, Clippy, generated tree-sitter parsing, docs links and whitespace checks pass; the mining-streak example builds without warnings. The full final repository gate remains pending while the broader expansion continues.
Generic checkpoint: 38 assertions pass on vanilla 26.2, including recursive owned values, State defaults, event payloads, qualified constructors, borrowed generic methods and indexed receivers, with repeated invocation and reload. The 95-assertion vector native regression also passes on the current compiler. All language/LSP tests, Clippy, formatting, docs links, generated parser checks and whitespace checks pass. The mining-history example builds without warnings and demonstrates one generic library instantiated for strings and numbers. The full final repository gate remains pending while the remaining expansion continues.
Maps and sets checkpoint: the bundled generic collections pass 52 vanilla assertions, including a full 1,024-entry map lookup. The two-client probe verifies independent collections after reload.
Static traits checkpoint: eight vanilla assertions exercise required signatures and concrete dispatch through generic bounds.
Authored testing checkpoint:
sand lang testruns Sand tests in a disposable vanilla world and reports the source line of a failed assertion.sand lang source-maplinks source spans to portable operations and emitted function identities.Callable checkpoint: twelve vanilla assertions cover named function values, owned closures, recursive dispatch, and nested captures. Two clients retain different captures in player State after reload. The callbacks example builds without warnings.
Related entities checkpoint:
entity_ref(Relation::Vehicle)and the other single-entity relations retain pack-owned identities. Seven vanilla assertions cover vehicle retention across dismount, attacker capture, absent relations, and writes to the original entity State. The two-client identity and kill-credit regression passes.Generated source-map checkpoint: version 2 links final
.mcfunctionlines, generated branch and macro helpers, and player-initialized functions to authored spans. The portable test confirms mapped and ordinary compilation emit identical pack files.Vehicle checkpoint:
mount(vehicle)anddismount()use retained entity references. Eight vanilla assertions pass and the minecart shuttle example builds.Owned waits checkpoint: top-level
waitin entity or player functions keeps per-invocation locals and the original execution position and dimension.cancel_waits()is scoped to the executor. Two real clients verify three overlapping continuations, independent record and vector captures, owner-scoped cancellation, and a player changing dimensions before resumption. The bakery example builds.Live Zed opened a temporary Sand project with the worktree language server and received the expected diagnostic and execution-context inlay hints. Focused compiler, API-surface and schema checks pass. The full repository rerun is in progress.
World operations checkpoint:
dimension_is, dimension-scoped calls, andclone_blockswith masking, filtering, and overlap/move modes. Eleven vanilla 26.2 assertions pass across nested dimension scopes and two independent invocations. Compiler, API surface, schema generation, and example build checks pass for this checkpoint.Biome and block entity checkpoint:
biome_isvalidates against shared Mojang catalogs for 26.1–26.3. Numeric block entity data reads, literal/runtime writes, and removal use checked paths. Eighteen vanilla 26.2 assertions pass in repeated invocations with reload. A version-boundary regression verifies Dappled Forest is accepted on 26.3 and rejected on 26.2. The maintained checkpoint-room example builds without warnings.Equipment and query checkpoint: typed hand and armor checks, replacement and clearing pass eleven vanilla assertions. Entity selectors compose native NBT compounds and State score bounds with existing filters, passing eight native assertions. The encounters example demonstrates equipping guards.
Computed waits checkpoint: the two-client vanilla 26.2 fixture verifies independent elapsed intervals of 12, 18, and 23 ticks across overlapping frames, a 20-tick seconds conversion, synchronous fallback for invalid durations, player cancellation isolation, and resumption in the original dimension. The bakery example now computes how long each order takes.
Resource and library checkpoints: independently rolled loot pools with weather and chance pass seven vanilla assertions on repeated runs. Sand and Rust share 43 vanilla enchantment identities from five verified targets, and the equipment fixture confirms a declared Protection II item in native entity data. The bundled
timeandspatiallibraries pass thirteen vanilla assertions for duration bounds, timer integration, stored coordinates, and exact teleportation. The scout checkpoint example builds from the vendored modules.Native world and matching checkpoint: custom damage types share the Rust component model. Typed block-entity data supports structured writes and copies, entity motion supports atomic velocity updates, and named world predicates can be reused in functions and loot pools. Guarded statement and value matches preserve arm order and fall through when a guard fails. The vanilla 26.2 fixtures pass 3 damage, 23 block-data, 5 motion, 5 named-predicate, and 11 guarded-match assertions.
Smithing trim and localization checkpoint: Sand and Rust share a builder that emits the armor trim pattern required by vanilla. A real player client received the authored recipe on 26.2. Messages, names, lore, and boss bar titles accept client translation keys with ordered substitutions. The two-client probe confirmed that an item retains its translation key and that message substitution storage is cleared. The encounters and field journal examples build with these features.
Scoped expressions checkpoint: match arms can introduce owned local bindings and destructure nested records and fixed arrays. Block expressions run scoped statements and return their final expression. Nine match-binding assertions and ten block-expression assertions pass on vanilla 26.2, including recursive calls, guard fallthrough, local loop jumps, argument evaluation order, and copy isolation. The mining-streak example uses both features. The full language and LSP test suites passed at this checkpoint.
Presentation checkpoint: native chat supports tooltips, links, command suggestions, and clipboard actions. Written books use the shared item component and support fixed rich pages and page links. The two-client vanilla 26.2 probe confirmed receipt of the tooltip and clipboard action, two written-book pages and their page-link metadata, and the exact particle count, spread, and speed computed at runtime. The journal and encounters examples exercise these additions. The API inventory regression tests pass with the new contracted types.
Advancement and notice checkpoint: native milestones support named inventory, placement, and kill criteria, explicit all/any requirements, optional display and experience, and player-scoped queries for an advancement or one criterion. The vanilla probe confirms partial and completed progress, experience delivery, and kill-credit isolation across two players. Native notice dialogs support translated titles, text blocks, and a dismiss label. The connected client received both open and clear packets, and the journal example includes a first-join notice.
World authoring checkpoint:
dimensiondeclarations use the shared flat generator with typed layers, biomes and dimension types. Authored dimensions work with scoped calls, predicates and loaded entity waits. Eleven vanilla 26.2 assertions passed on two invocations, including exact terrain layers, biome, context restoration and two chained waits that resumed at the saved position. The pack reloaded successfully, the editor and portable decode tests passed, and the world operations example builds with a Workshop dimension.Custom biome checkpoint:
biomedeclarations provide rain or snow, temperature, humidity, and six RGB colors. Flat dimensions, biome tests, and named world predicates can refer to the declaration. The shared Rust biome builder emits the modern visual environment attributes. Five runtime assertions passed twice on vanilla 26.2, and a connected client received the exact climate values and all six colors in its biome registry before a successful reload.Structure template checkpoint:
structure_templatedeclarations import package-local gzip NBT, andplace_templateaccepts a typed absolute or relative position. Portable JSON includes the binary asset, and the compiler emits the original bytes. On vanilla 26.2, all four block checks across both placements passed on two invocations before a successful reload. The world operations example uses the same placement and a saved lantern marker.Advancement completion checkpoint:
#[on(advancement = Name)]attaches player handlers to a native reward function. On vanilla 26.2 two connected players confirmed that partial progress runs no handler, the two handlers run in declaration order exactly once for the completing player, experience still applies, and the other player remains unaffected. The encounters example includes a completion handler.Inventory reads checkpoint:
inventory_countqueries vanilla base stacks or an authored custom item, andentity_data_numberreads a checked native path as a number. The vanilla 26.2 probe counted 9 and 3 bread across separate players, counted exactly two custom items for the first player, and confirmed that no items were removed. The entity-path checks covered fractional health as its vanilla integer result, a list length, and a missing path returning zero.Inventory transfers checkpoint:
clear_itemaccepts computed nonnegative counts. Namedinventory_transferdeclarations reuse the Rust system for whole-stack and exact-amount moves with optional callbacks. Vanilla 26.2 confirmed computed removal, exact splitting and merging with custom components preserved, rejection when the source was short, success and rejection callbacks, and isolation across two connected players. The stand-alone camp supplies example shows how to author a transfer.Player HUD checkpoint:
huddeclarations use the shared Rust lifetime and HUD systems for rich actionbars and private boss bars backed by State or a constant. Two connected vanilla 26.2 players each received a private audience. One player’s State change refreshed their bar from 25 to 75, while the other remained at 25. Cancelling each HUD removed only its owner’s bar. The campsite example shows a timer-backed cooldown. The animated boss runtime report also matches its existing baseline after preserving established owner-position helper identities.Native menu checkpoint:
menudeclarations expose the shared player-owned native dialog system with optional pagination and typed callbacks. The two-player vanilla 26.2 probe confirmed per-player tokens, page invalidation, stale-action rejection, one-shot execution, explicit close, and a clean reload. The camp supplies example demonstrates a two-page inventory transfer menu. Exact biome JSON fixtures and API search intent coverage also pass with the updated runtime and catalogue.Conversation checkpoint: menus can branch to named views, start on a selected view, and authorize a button or an entire session against a boolean State field. The two-player vanilla 26.2 run confirmed that a false flag denies confirmation, enabling the flag admits a newly tokenized confirmation, changing it during a session invalidates stale input, and the second player remains eligible. The camp supplies example now asks for confirmation before moving inventory.
Biome population checkpoint: biome declarations accept weighted
spawnersgrouped by vanilla mob category, optional group sizes, and per-entityspawn_costs. The native 26.2 biome codec retained the exact creature and monster tables and density values on decode and re-encode. A fresh vanilla world loaded the authored biome and dimension, passed the fixture twice, and reloaded cleanly. The world operations example includes a rabbit spawn table.Conditional wait checkpoint:
waitcan suspend aniforelsearm, then continue through the shared suffix. The vanilla 26.2 two-player probe confirmed immediate nonwaiting paths, independent overlapping invocations, retained outer and shadowing locals, the delayed else-if route, and an early return that skips the suffix. The bakery example gives every third batch a longer bake.Match wait checkpoint: statement match arms can suspend while preserving pattern bindings and dispatch state. Alternatives and short-circuit guards share their authored wait sites. The two-player vanilla 26.2 probe confirmed the immediate fallback, independent overlapping waits, and no fallthrough into later arms after resumption.
Local loop wait checkpoint: numeric and collection loops resume the same invocation with its iteration values and jump state. The two-player vanilla 26.2 probe ran overlapping while and vector loops, demonstrated independent collection snapshots and correct continue/break behavior, and reloaded successfully.
Projectile checkpoint:
projectiledeclarations reuse the shared Rust flight runtime for player-owned launch, bound speed and sampling, typed target filters, impact callbacks, native damage and cancellation. Two connected players on vanilla 26.2 confirmed caster kill credit, a filtered entity remaining unharmed, a cancelled peer’s target surviving, and a block callback executing at the impact while retaining its player executor. The training sparks example builds.Progression checkpoint:
progressiondeclares guarded goals, forward branches and committed rewards over a player State number.sessionadvances that same track at an authored cadence and exposes start, cancel, reset and restart. Two players on vanilla 26.2 confirmed skipped rewards, reward reentry rejection, independent completion, preserve-on-cancel, exact cadence after restart and explicit reset. The full repository gate passed at the match-wait checkpoint, including all standalone Rust runtime baselines and external consumers.Ability checkpoint:
abilityreuses canonical admission with a player State balance, cooldown timer and boolean guard. It can use the flight of a named projectile under the same admission. Two-player vanilla 26.2 evidence confirms rejected admissions spend nothing, committed State precedes callbacks, reentry cannot double charge, cooldowns tick independently, and cancellation preserves both the charge and cooldown. The mana-powered spark example builds.Custom player combat
Sand combat declarations bind health and optional shields and immunity to player State. Damage and healing use the shared Combat resolver, including resistance, critical multipliers, health caps, and outcome callbacks. The two-player vanilla 26.2 probe passed with computed damage and isolated immunity and healing. The scout combat example builds, and the portable compiler and editor support the new declarations.
Bounded indexed jobs
Sand job declarations use the shared Job and Lifetime runtimes. A player callback receives the current zero-based index, with a per-instance execution budget and a loaded-tick deadline. The vanilla 26.2 probe verified ordered batches, capacity rejection, owner-scoped cancellation, and exactly one completion callback. The supply inspection example builds, and editor completion checks the step signature.
Owned native display scenes and example builds
Sand scenes group named block, item, and text displays with local poses and keyframes. The shared Scene and Lifetime runtimes handle interpolation, owner following, cancellation, and expiry. A two-player vanilla 26.2 probe verified independent ownership, interpolation, custom item components, and cleanup.
The repository gate builds all 21 Sand examples from a clean checkout. The checkpoint example now includes the Spatial and Time modules through Sand’s library installer.
The timed loot regression runs on a controlled platform so cleanup covers every drop regardless of world seed. It passed six invocations across three fresh vanilla worlds. The regenerated cooperative arena runtime report records the shared Session cadence guards; the diff is limited to the two paced round functions.