### State Example with Option String Source: https://github.com/ecto/loon/blob/main/src/eff/NOTES.md An example demonstrating the use of `Env.lookup` with `Option String` in the `eff.oo` file. ```Loon eff.oo ``` -------------------------------- ### Loon Basic Syntax and Pipe Example Source: https://github.com/ecto/loon/blob/main/README.md Demonstrates basic function definition and the use of pipes for data transformation. No specific setup is required to run this example. ```loon [fn greet [name] [println "Hello, {name}!"]] [pipe [range 1 10] [filter [fn [n] [> n 4]]] [map [fn [n] [* n n]]] [each println]] ``` -------------------------------- ### Loon WASI Integration Example Source: https://github.com/ecto/loon/blob/main/DESIGN.md Example demonstrating the use of WASI interfaces for file system and environment access in Loon. This snippet shows how to import and use functions like `read-file`, `args`, and `println`. ```loon [use wasi.fs {read-file write-file}] [use wasi.env {args vars}] [defn main [] [let name [nth [args] 1 "world"]] [println [str "hello, " name]]] ``` -------------------------------- ### Loon Development Setup Source: https://github.com/ecto/loon/blob/main/README.md Commands for setting up the Loon development environment, including running tests, building WASM, and compiling the language server. ```bash # Run tests cargo test --workspace # Build WASM + dev server cd web && npm run dev # Build language server cargo build -p loon-lsp --release ``` -------------------------------- ### Channel and Concurrency Example Source: https://github.com/ecto/loon/blob/main/DESIGN.md Demonstrates creating a channel, spawning a task to send a message, and awaiting a message on the receiving end. This showcases basic concurrency patterns. ```loon [let [tx rx] [channel]] [spawn [fn [] [send tx "hello from task"]]] [let msg [Async.await [recv rx]]] [println msg] ``` -------------------------------- ### State Example Source: https://github.com/ecto/loon/blob/main/src/eff/NOTES.md This example demonstrates the functionality of state management within the Loon language, now with corrected type checking for escaping handlers. ```Loon samples/state.oo ``` -------------------------------- ### Install Loon Language Source: https://github.com/ecto/loon/blob/main/README.md Installs the Loon language using a curl command. Ensure you have curl installed and internet access. ```bash curl -fsSL https://loonlang.com/install.sh | sh ``` -------------------------------- ### Loon CLI Commands Source: https://github.com/ecto/loon/blob/main/README.md Provides examples of common Loon command-line interface commands for running programs, using the REPL, formatting code, and explaining errors. ```bash loon run hello.oo # Run a program loon repl # Interactive REPL with time-travel loon fmt hello.oo # Format source loon explain E0201 # Interactive error tutorial ``` -------------------------------- ### Search Built-in Package Index Source: https://github.com/ecto/loon/blob/main/docs/packages.md Use the `loon search` command to find packages in the official index. This example searches for packages related to JSON. ```bash loon search json # github.com/loon-lang/json v0.1.0 (MIT) — JSON parser and serializer for Loon ``` -------------------------------- ### Loon REPL: Natural Language Interaction Source: https://github.com/ecto/loon/blob/main/DESIGN.md Shows how Loon's REPL seamlessly blends code execution with natural language queries and AI-assisted code generation. Input starting with `[` is code; all other text is interpreted as natural language. ```loon loon> [+ 1 2] 3 loon> what does the greet function do? greet takes a String and returns "hello, {name}!" Defined at src/main.oo:3. Last modified 2 minutes ago. loon> add a test for greet that checks empty strings ✓ Generated test: [test defn test-greet-empty [] [assert-eq [greet ""] "hello, !"]] Apply? [y/n/edit] loon> refactor fib to use tail recursion ✓ Proposed change to fib: [defn fib [n] [fib-iter n 0 1]] [defn fib-iter [n a b] [match n 0 => a n => [fib-iter [- n 1] b [+ a b]]]] Apply? [y/n/edit] loon> show me everything that depends on Config 3 functions reference Config: load-config (src/config.oo:12) — constructs Config validate (src/config.oo:28) — borrows Config main (src/main.oo:5) — owns Config ``` -------------------------------- ### Line Comment in Loon Source: https://github.com/ecto/loon/blob/main/tree-sitter-loon/test/corpus/comments.txt Demonstrates a basic line comment starting with a semicolon. This syntax is used for single-line comments. ```Loon ; this is a comment ``` -------------------------------- ### Define Custom Package Indices in pkg.oo Source: https://github.com/ecto/loon/blob/main/docs/packages.md Configure custom package indices within the `pkg.oo` file to include private or alternative package sources. This example shows how to add a 'company' index. ```loon {:name "my-app" :version "0.1.0" :indices { "company" "https://git.internal.co/loon-packages/index.loon" } :deps {}} ``` -------------------------------- ### Exporting Loon Functions via Extern Source: https://github.com/ecto/loon/blob/main/DESIGN.md Exporting Loon functions to the host environment using `[pub extern defn]`. This example exports a `handle-request` function that takes a `Request` and returns a `Response`. ```loon [sig handle-request : Request → Response] [pub extern defn handle-request [req] [Response.ok "hello from loon"]] ``` -------------------------------- ### Structural Editing Example Source: https://github.com/ecto/loon/blob/main/DESIGN.md Loon's AST-based editing allows the cursor to move between nodes, enabling structural transformations like wrapping code. ```loon ; Cursor is on the [+ x 1] node: [defn inc [x] «[+ x 1]»] ; Press "w" to wrap in a new form: [defn inc [x] [«▮» [+ x 1]]] ; Type "if [> x 0]": [defn inc [x] [if [> x 0] [+ x 1] «▮»]] ``` -------------------------------- ### Loon Browser/JS Interop via Extern Source: https://github.com/ecto/loon/blob/main/DESIGN.md Accessing browser APIs like DOM manipulation through extern declarations. This example shows how to declare `query-selector` and `set-text-content` functions imported from the environment. ```loon [extern "env" [sig query-selector : &str → Element] [fn query-selector [sel]] [sig set-text-content : Element → &str → void] [fn set-text-content [el text]]] ``` -------------------------------- ### Run a Sample Program Source: https://github.com/ecto/loon/blob/main/CLAUDE.md Execute a specific sample program using the Loon CLI. Ensure the path to the sample file is correct. ```bash cargo run -p loon-cli -- run samples/hello.oo ``` -------------------------------- ### Transparent Persistence with Store.open Source: https://github.com/ecto/loon/blob/main/DESIGN.md Demonstrates opening a database store and associating data with it. The data persists across process restarts. ```loon [let db [Store.open "./app.db"]] [let db [assoc db :users #[ {:name "alice" :role :admin} {:name "bob" :role :user}]]] ; Survives process restarts: [let db [Store.open "./app.db"]] [get db :users] ; still there ``` -------------------------------- ### Create New Project Source: https://github.com/ecto/loon/blob/main/CLAUDE.md Initialize a new Loon project with default manifest and main file structures. The command creates `pkg.oo` and `src/main.oo`. ```bash cargo run -p loon-cli -- new test-proj ``` -------------------------------- ### Initialize Loon in Current Directory Source: https://github.com/ecto/loon/blob/main/docs/packages.md Use `loon init` to initialize `pkg.oo` in the current directory. ```bash loon init ``` -------------------------------- ### Multiple Line Comments in Loon Source: https://github.com/ecto/loon/blob/main/tree-sitter-loon/test/corpus/comments.txt Illustrates the use of multiple consecutive line comments. Each comment starts with a semicolon on its own line. ```Loon ; first comment ; second comment ``` -------------------------------- ### Comment Within Code Block in Loon Source: https://github.com/ecto/loon/blob/main/tree-sitter-loon/test/corpus/comments.txt Example of a line comment placed within a function definition. This comment is ignored during code execution. ```Loon [defn foo [] ; compute result 42] ``` -------------------------------- ### Creating and Running a New Loon Project Source: https://github.com/ecto/loon/blob/main/DESIGN.md Illustrates the command-line interface for creating a new Loon project and running it. ```shell $ loon new my-project ✓ Created my-project/ ✓ Created my-project/src/main.oo ✓ Created my-project/pkg.oo → cd my-project && loon run $ loon run Compiling my-project (847 bytes) hello, world! ``` -------------------------------- ### Create a New Loon Project Source: https://github.com/ecto/loon/blob/main/docs/packages.md Use `loon new` to create a new project with a default `pkg.oo` configuration. ```bash loon new ``` -------------------------------- ### Create and Add Dependencies with Loon CLI Source: https://github.com/ecto/loon/blob/main/docs/packages.md Use `loon new` to create a new project, `cd` into it, `loon add` to include external packages with version constraints, and `loon run` to execute your application. ```bash loon new my-app # Create project with pkg.oo cd my-app loon add github.com/cam/json --version "^1.0" loon run src/main.oo ``` -------------------------------- ### HTTP Server Implementation in Loon Source: https://github.com/ecto/loon/blob/main/DESIGN.md Sets up a basic HTTP server that handles different routes and returns responses. Requires `std.http` and `Async` modules. ```loon [use std.http {Server Response}] [defn handle [req] [match req.path "/" => [Response.ok "welcome to loon!"] "/ping" => [Response.ok "pong"] _ => [Response.not-found "404"]]] [defn main [] / {Async IO} [let server [Server.bind "0.0.0.0:8080"]] [println "listening on :8080"] [Async.await [server.serve handle]]] ``` -------------------------------- ### Loon Component Model Import/Export Source: https://github.com/ecto/loon/blob/main/DESIGN.md Example of using the WASM Component Model in Loon for module composition. This snippet shows how to import a handler from `wasi:http/handler` and export a `handle` function. ```loon [import "wasi:http/handler" {handle}] [export "wasi:http/handler" [fn handle [req] ...]] ``` -------------------------------- ### Publish a Package with Loon Source: https://github.com/ecto/loon/blob/main/docs/packages.md Use the `loon publish` command to prepare a package for distribution. It creates a `.tar.gz` archive and prints the BLAKE3 hash for verification. Ensure `pkg.oo` has name and version, and the library entry point exists. ```bash $ loon publish Package: my-lib v1.0.0 Entry: src/lib.oo Hash: 7f3a2b1c4d5e6f... Size: 2.3 KB (4 files) Archive: target/my-lib-1.0.0.tar.gz Ready to publish. (Use `loon add` with git repos to share packages) ``` -------------------------------- ### Hello World in Loon Source: https://github.com/ecto/loon/blob/main/DESIGN.md A basic 'hello, world!' program to demonstrate Loon's syntax for printing output. ```loon [defn main [] [println "hello, world!"]] ``` -------------------------------- ### Define Functions and Use Pipe Operator in Loon Source: https://github.com/ecto/loon/blob/main/DESIGN.md Demonstrates defining functions like 'greet' and 'greet-all', and using the 'pipe' operator for sequential function application. Type annotations are inferred. ```loon [defn greet [name] [str "hello, " name "!"]] [defn greet-all [names] [pipe names [map greet] [collect]]] [defn main [] [let users #["alice" "bob" "carol"]] [pipe [greet-all users] [each println]]] ``` -------------------------------- ### Loon FFI Extern Declaration Source: https://github.com/ecto/loon/blob/main/DESIGN.md Declaring external functions (FFI) in Loon. The `[sig]` keyword is required for type inference across language boundaries. This example shows how to declare a `log` function imported from the environment. ```loon [extern "env" [sig log : &str → void] [fn log [msg]]] ``` -------------------------------- ### Loon Build: Minimal Binary Size Source: https://github.com/ecto/loon/blob/main/DESIGN.md Illustrates the result of building a Loon project with release optimizations, highlighting the significant reduction in binary size due to type-level dead-code elimination. ```sh $ loon build --release Compiled main.wasm (847 bytes) Type-level DCE removed 14 types, 89 functions ``` -------------------------------- ### Importing modules and specific items Source: https://github.com/ecto/loon/blob/main/DESIGN.md Use the `use` keyword to bring definitions from other modules into the current scope. Aliases can be provided for clarity. ```loon [use std.io] ; use as std.io.read, etc. [use std.io :as io] ; alias: io.read, etc. [use std.collections {HashMap HashSet}] ; import specific items ``` -------------------------------- ### Globally Unique Constructor Tags Source: https://github.com/ecto/loon/blob/main/docs/elegance-notes.md Explains the fix for constructor tag collisions. Previously, constructor tags were assigned per-type starting from 0, causing `match` statements to incorrectly match patterns across different types. Tags are now globally unique. ```Loon [match value [Some n] ...] ``` -------------------------------- ### Import Dependencies with [use] Macro Source: https://github.com/ecto/loon/blob/main/docs/packages.md Demonstrates different ways to import dependencies using the `[use]` macro in Loon. This includes qualified imports, aliased imports, and selective imports. ```loon [use github.com/cam/json] ; qualified: json.parse, json.stringify [use github.com/cam/json :as j] ; aliased: j.parse, j.stringify [use github.com/cam/json {parse stringify}] ; selective: parse, stringify ``` -------------------------------- ### Define a basic function Source: https://github.com/ecto/loon/blob/main/tree-sitter-loon/test/corpus/definitions.txt Defines a simple function named 'main' that prints 'hello'. ```Loon [defn main [] [println "hello"]] ``` -------------------------------- ### Use a let binding Source: https://github.com/ecto/loon/blob/main/tree-sitter-loon/test/corpus/definitions.txt Introduces a local variable 'x' with the value 42 and then uses it. ```Loon [let [x 42] x] ``` -------------------------------- ### Create and Manipulate Persistent Maps Source: https://github.com/ecto/loon/blob/main/DESIGN.md Shows how to create a persistent map with key-value pairs and update it using `assoc`. Map keys are symbols. ```loon [let m {:name "loon" :version "0.1" :cool true}] [get m :name] ; "loon" [let m2 [assoc m :version "0.2"]] ``` -------------------------------- ### Run Tests Command Source: https://github.com/ecto/loon/blob/main/DESIGN.md Demonstrates the command-line interface for running tests in Loon. Shows output including passed, failed, and timing information. ```sh $ loon test Running 4 tests... ✓ test-greet .................. 0.1ms ✓ test-fib .................... 0.2ms ✓ test-parse .................. 0.3ms ✗ test-edge-case .............. 0.1ms assert-eq failed: expected: 42 actual: 41 at: src/math.oo:28 3 passed, 1 failed (0.7ms) ``` -------------------------------- ### Insertion-Ordered Maps Source: https://github.com/ecto/loon/blob/main/docs/elegance-notes.md Demonstrates the deterministic output of maps due to insertion order. Previously, maps were iterated in hash order, leading to non-deterministic output. The EIR VM now uses an insertion-ordered map. ```Loon [assoc [assoc {:x 1} :y 2] :z 3] ``` -------------------------------- ### Typical Loon Package Structure Source: https://github.com/ecto/loon/blob/main/docs/packages.md Illustrates the standard directory and file layout for a Loon package. Includes the manifest (`pkg.oo`), lockfile (`lock.oo`), and source code directories. ```text my-package/ pkg.oo # Manifest lock.oo # Lockfile (auto-generated) src/ lib.oo # Library entry point (pub exports) main.oo # Executable entry point (optional) utils.oo # Internal module ``` -------------------------------- ### Publish Loon Package Source: https://github.com/ecto/loon/blob/main/docs/packages.md Validate the manifest, hash the source tree, and create a tarball for publishing. ```bash loon publish ``` -------------------------------- ### Dependency Formats in pkg.oo Source: https://github.com/ecto/loon/blob/main/docs/packages.md Loon's `pkg.oo` supports multiple dependency formats: version string shorthand for simple version constraints, map form for detailed control over source and effects, and path dependency for local development. ```loon "github.com/cam/json" "^1.2" ``` ```loon "github.com/cam/std#http" { :version "^2.0" :grant #["Net" "IO"] :git "https://github.com/cam/std.git" :rev "v2.0.1" :hash "abc123..." } ``` ```loon "my-lib" {:path "../my-lib"} ``` -------------------------------- ### Loon Project Manifest (pkg.oo) Source: https://github.com/ecto/loon/blob/main/docs/packages.md The `pkg.oo` file defines project metadata and dependencies. It supports direct dependencies, dependencies with specified versions and granted capabilities, and local path dependencies. ```loon { :name "my-app" :version "0.1.0" :deps { "github.com/cam/json" "^1.0" "github.com/cam/std#http" {:version "^2.0" :grant #["Net" "IO"]} "my-lib" {:path "../my-lib"} } } ``` -------------------------------- ### Search Loon Packages Source: https://github.com/ecto/loon/blob/main/docs/packages.md Search the package index, including built-in and custom sources. ```bash loon search ``` -------------------------------- ### Notebooks as First-Class Programs Source: https://github.com/ecto/loon/blob/main/DESIGN.md Shows how to use the `std.csv` library within a Loon notebook to read and process CSV data. ```loon [use std.csv {read-csv}] [let data [read-csv "./sales.csv"]?] [println [str "Mean: $" [mean [map data :revenue]]]] ``` -------------------------------- ### Define a function with parameters Source: https://github.com/ecto/loon/blob/main/tree-sitter-loon/test/corpus/definitions.txt Defines a function 'add' that takes two parameters, 'x' and 'y', and returns their sum. ```Loon [defn add [x y] [+ x y]] ``` -------------------------------- ### Auditing Dependency Capabilities Source: https://github.com/ecto/loon/blob/main/docs/packages.md Use `loon audit --capabilities` to list the required capabilities for each dependency. This helps in understanding the effects a dependency might perform. ```bash $ loon audit --capabilities Dependency Capabilities ────────────────────────────────────────────────── github.com/cam/json -> pure (no effects) github.com/cam/http -> Net, IO ``` -------------------------------- ### Map/Set Equality Comparison Source: https://github.com/ecto/loon/blob/main/docs/elegance-notes.md Demonstrates content-based equality comparison for strings, vectors, tuples, ADTs, sets, and maps in the EIR VM. Previously, only heap identity was compared for strings and aggregates. ```Loon [= [str "ab"] [str "a" "b"]] ``` -------------------------------- ### HTTP Handler Comparison: Loon vs. Rust Source: https://github.com/ecto/loon/blob/main/DESIGN.md Compares HTTP request handling logic between Loon and Rust (axum), emphasizing Loon's conciseness and lack of type annotations. ```loon [defn handle [req] [match req.method :GET => [Response.ok [get-page req.path]] :POST => [Response.ok [create-item [req.json]?]] _ => [Response.method-not-allowed]]] ``` ```rust async fn handle(req: Request) -> Response { match req.method() { Method::GET => Response::ok(get_page(req.path())), Method::POST => Response::ok(create_item(req.json().await?)), _ => Response::method_not_allowed(), } } ``` -------------------------------- ### Loon Build Process with AI Generation Source: https://github.com/ecto/loon/blob/main/DESIGN.md This command demonstrates the output of `loon build` when AI code generation is involved, showing successful generation and compilation. The `--offline` flag ensures reproducible builds by using cached AI generations. ```sh $ loon build [ai] Generating celsius-to-fahrenheit... ✓ (type-checked, 1 attempt) Compiled main.wasm (1.2KB) ``` -------------------------------- ### Macro for Defining Element Constructors Source: https://github.com/ecto/loon/blob/main/docs/plans/2026-02-20-language-features.md Demonstrates using a macro to define multiple element constructors, eliminating repetitive code. This is a usage pattern rather than a language change. ```loon ; before (27 lines) [fn div [first & rest] [make-element "div" first rest]] [fn span [first & rest] [make-element "span" first rest]] [fn p [first & rest] [make-element "p" first rest]] ... ; after (1 macro + invocations) [macro def-el [name tag] [fn ~name [first & rest] [make-element ~tag first rest]]] [def-el div "div"] [def-el span "span"] [def-el p "p"] [def-el a-el "a"] [def-el button-el "button"] ... ``` -------------------------------- ### Pond Package Manager Commands Source: https://github.com/ecto/loon/blob/main/DESIGN.md Common commands for managing dependencies, auditing, verifying, and publishing packages. ```sh pond add io.github.alice/http # resolve name → hash, add to loon.toml pond audit # type-check all deps against their interfaces pond audit --capabilities # report what each dep requires pond verify # verify all dep hashes match content pond publish # hash source, push to IPFS + index ``` -------------------------------- ### Create and Manipulate Persistent Sets Source: https://github.com/ecto/loon/blob/main/DESIGN.md Illustrates creating a persistent set, checking for element containment with `contains?`, and adding elements using `conj`. Sets store unique elements. ```loon [let s #{1 2 3}] [contains? s 2] ; true [let s2 [conj s 4]] ; #{1 2 3 4} ``` -------------------------------- ### Fibonacci Comparison: Loon vs. Clojure vs. Rust Source: https://github.com/ecto/loon/blob/main/DESIGN.md Compares the implementation of the Fibonacci sequence in Loon, Clojure, and Rust, highlighting syntactic differences. ```loon [defn fib [n] [match n 0 => 0 1 => 1 n => [+ [fib [- n 1]] [fib [- n 2]]]]] ``` ```clojure (defn fib [n] (case n 0 0 1 1 (+ (fib (- n 1)) (fib (- n 2))))) ``` ```rust fn fib(n: u64) -> u64 { match n { 0 => 0, 1 => 1, n => fib(n - 1) + fib(n - 2), } } ``` -------------------------------- ### Run All Tests Source: https://github.com/ecto/loon/blob/main/CLAUDE.md Execute all tests within the entire workspace. This command is essential for verifying the integrity of the project after changes. ```bash cargo test --workspace ``` -------------------------------- ### String Literals vs. Owned Strings Source: https://github.com/ecto/loon/blob/main/DESIGN.md Shows the distinction between borrowed string literals (from static data) and heap-allocated, owned strings created with `String.from`. ```loon [let s "hello"] ; string literal — borrowed from static data [let s2 [String.from "hello"]] ; heap-allocated, owned ``` -------------------------------- ### Show Dependency Reason in Loon Source: https://github.com/ecto/loon/blob/main/docs/packages.md Use `loon why` to trace why a specific dependency is included in the project. ```bash loon why ``` -------------------------------- ### Define and Extend Type with Methods Source: https://github.com/ecto/loon/blob/main/docs/plans/2026-02-20-language-features.md Demonstrates how to declare a type with variants and associated methods, and how to extend an existing type with new variants and methods. The type declaration automatically generates dispatch functions for methods. ```loon ; shape.loon [type Shape [Circle f64 [fn area [r] [* 3.14159 r r]] [fn describe [r] "circle r={r}"]] [Rect f64 f64 [fn area [w h] [* w h]] [fn describe [w h] "rect {w}x{h}"]] Point [fn area [] 0.0] [fn describe [] "point"]] ; triangle.loon — same keyword, extends Shape [type Shape [Triangle f64 f64 [fn area [b h] [* 0.5 b h]] [fn describe [b h] "triangle {b}x{h}"]]] ; usage — area and describe are regular functions with automatic dispatch [area [Circle 5.0]] ; => 78.539... [describe [Rect 3.0 4.0]] ; => "rect 3x4" [area [Triangle 6.0 3.0]] ; => 9.0 ``` -------------------------------- ### Define and use anonymous functions (closures) Source: https://github.com/ecto/loon/blob/main/DESIGN.md Use `fn` to create anonymous functions, which can be assigned to variables or passed as arguments. These can capture their lexical environment. ```loon [fn [x] [+ x 1]] ; anonymous function [let inc [fn [x] [+ x 1]]] [map inc #[1 2 3]] ; #[2 3 4] ``` -------------------------------- ### Loon Package Manifest (loon.toml) Source: https://github.com/ecto/loon/blob/main/DESIGN.md Defines package name, version, dependencies with content hashes and sources, and required capabilities. ```toml [package] name = "my-app" version = "0.1.0" [dependencies] http = { hash = "sha256:a1b2c3d4...", source = "ipfs" } json = { hash = "sha256:e5f6g7h8..." } [capabilities] net = true fs.read = ["./data/*"] ``` -------------------------------- ### Map Destructuring with Defaults in Function Parameters Source: https://github.com/ecto/loon/blob/main/docs/plans/2026-02-20-language-features.md Demonstrates a concise way to destructure map arguments with default values directly in function signatures, reducing boilerplate code for component definitions. ```loon ; before (5 lines of boilerplate per component) [fn card [first & rest] [let props [if [map? first] first {}]] [let children [if [map? first] rest [cons first rest]]] [let accent [get props :accent false]] [let cls [get props :class ""]] ...] ; after (one signature line) [fn card [{accent false, class ""} & children] [div {:class [cx "card" class]} children]] ``` -------------------------------- ### Create and Manipulate Persistent Vectors Source: https://github.com/ecto/loon/blob/main/DESIGN.md Demonstrates creating a persistent vector, adding an element using `conj`, and accessing elements by index or length. Persistent vectors share structure internally. ```loon [let v #[1 2 3 4 5]] [let v2 [conj v 6]] ; #[1 2 3 4 5 6] — v is unchanged [nth v 0] ; 1 [len v] ; 5 ``` -------------------------------- ### Format Files Source: https://github.com/ecto/loon/blob/main/CLAUDE.md Apply code formatting to files within a specified directory using the Loon CLI. This helps maintain consistent code style. ```bash cargo run -p loon-cli -- fmt samples/ ``` -------------------------------- ### Control visibility with `pub` Source: https://github.com/ecto/loon/blob/main/DESIGN.md By default, all definitions (functions, types) are private. Use the `pub` keyword to export them from the module. ```loon [pub defn serve [port] ...] [pub type Config [port u16] [host String]] [defn parse-header [raw] ; private ...] ``` -------------------------------- ### Verify Loon Packages Source: https://github.com/ecto/loon/blob/main/docs/packages.md Re-hash all cached packages against the lockfile to ensure integrity. ```bash loon verify ``` -------------------------------- ### Loon REPL: Time Travel and Forking Source: https://github.com/ecto/loon/blob/main/DESIGN.md Demonstrates the persistent state, time travel (`rewind`), and session forking capabilities of the Loon REPL. Use `rewind` to undo evaluations and `fork` to experiment without affecting the main session. ```loon loon> [let x 42] loon> [let y [+ x 8]] loon> y 50 loon> [rewind 2] ; undo last 2 evaluations loon> x 42 loon> y ; error: unbound symbol 'y' loon> [fork] ; branch this session loon (fork-1)> [let y 999] loon (fork-1)> [exit-fork] loon> y ; error: unbound symbol 'y' (fork was discarded) ``` -------------------------------- ### Testing Effects with Handlers Source: https://github.com/ecto/loon/blob/main/DESIGN.md Illustrates how to test functions with side effects using Loon's effect handling system. IO operations are handled with test data, eliminating the need for mocks. ```loon [test defn test-load-config [] [let result [handle [load-config "app.toml"] [IO.read-file _] => [resume "name = \"test\""] [Fail.fail msg] => [Err msg]]] [assert-eq result.name "test"]] ``` -------------------------------- ### Performing a Full Dependency Audit Source: https://github.com/ecto/loon/blob/main/docs/packages.md Run `loon audit` for a comprehensive check, including capabilities, transitive grants, cache integrity, and lockfile status. This ensures overall project health and security. ```bash $ loon audit Dependency Audit ────────────────────────────────────────────────── Capabilities github.com/cam/json -> pure (no effects) github.com/cam/http -> Net, IO Transitive Grants ✓ All transitive dependencies have required grants Cache Integrity ✓ 2/2 packages verified Lockfile ✓ All dependencies locked ``` -------------------------------- ### Declare Module Capabilities Source: https://github.com/ecto/loon/blob/main/DESIGN.md Modules declare their required capabilities for security and sandboxing. Callers explicitly grant these capabilities. ```loon [capabilities :net ; network access :fs.read ["./data/*"] ; read files in ./data/ :fs.write ["./out/*"] ; write files in ./out/ :env ["API_KEY"]]" ; read one env var ``` ```loon [use untrusted-dep :grant [:net :fs.read ["./cache/*"]]] ``` -------------------------------- ### String Interpolation with \(expr) Source: https://github.com/ecto/loon/blob/main/docs/elegance-notes.md Illustrates the new string interpolation syntax \(expr), similar to Swift and Roc. This replaces the older {expr} syntax, which caused issues with literal braces and brace-heavy data structures. Literal braces can now be represented by bare { and }. ```Loon [str "Hello \(name)! You have \(count) messages."] ``` -------------------------------- ### Integer Literals in Loon Source: https://github.com/ecto/loon/blob/main/tree-sitter-loon/test/corpus/literals.txt Demonstrates basic integer literals. These are fundamental numeric types used for whole numbers. ```loon 42 ``` ```loon -7 ``` ```loon 0 ``` -------------------------------- ### Add a Dependency to Loon Project Source: https://github.com/ecto/loon/blob/main/docs/packages.md Add a dependency from a source. You can specify version constraints and effect grants. ```bash loon add ``` ```bash loon add --version "^1.0" ``` ```bash loon add --grant "Net,IO" ``` -------------------------------- ### Warm Loon Cache Source: https://github.com/ecto/loon/blob/main/docs/packages.md Resolve and fetch all dependencies, including transitive ones, to ensure the cache is up-to-date. ```bash loon cache warm ``` -------------------------------- ### Define Test Functions Source: https://github.com/ecto/loon/blob/main/DESIGN.md Marks functions with '[test defn ...]' to designate them as tests. These are regular functions without requiring special imports. ```loon [test defn test-greet [] [assert-eq [greet "world"] "hello, world!"]] [test defn test-fib [] [assert-eq [fib 0] 0] [assert-eq [fib 10] 55]] ``` -------------------------------- ### Loon Ownership and Borrowing - Inferred Mutation and Move Source: https://github.com/ecto/loon/blob/main/DESIGN.md Shows Loon's inference for mutable borrows and ownership transfers. Functions modifying parameters are inferred to take mutable borrows, while functions storing parameters are inferred to take ownership. ```loon ; Mutation — the compiler infers mutable borrow: [defn add-world [s] [push! s " world"]] ; push! requires mutation → compiler infers &mut ; Ownership transfer — the compiler infers move: [defn take [s] [store-in-db s]] ; s escapes into a struct → compiler infers move ``` -------------------------------- ### Nested Lists in Loon Source: https://github.com/ecto/loon/blob/main/tree-sitter-loon/test/corpus/forms.txt Illustrates nested list structures with conditional logic. Shows how lists can contain other lists. ```Loon [if true [println "yes"] [println "no"]] ``` -------------------------------- ### Namespace Access with Dot Notation Source: https://github.com/ecto/loon/blob/main/docs/blog/2026-02-21-syntax-refresh.md All namespace access, including modules and effects, now consistently uses dot notation (e.g., `dom.`, `math.add`). ```loon dom/ -> dom. All namespace access now uses `.` consistently, matching modules (`math.add`) and effects (`IO.read-file`) ``` -------------------------------- ### Loon Physics Type System - Algebraic Effects Source: https://github.com/ecto/loon/blob/main/DESIGN.md Illustrates how physical properties can be treated as algebraic effects in Loon, allowing assumptions to be swapped by changing handlers. ```loon [fn analyze [load span] [let sigma_y [Physics.yield-strength]] [< [/ [* load span] [* span span]] sigma_y]] [handle [analyze 10.0kN 5.0m] [Physics.yield-strength] [resume 250.0MPa]] ``` -------------------------------- ### Universal String Interpolation Source: https://github.com/ecto/loon/blob/main/docs/plans/2026-02-20-language-features.md Shows how to use universal string interpolation with `{expr}` syntax for embedding expressions directly within strings. Literal braces can be escaped using `\{`. ```loon ; before [str "1px solid " [color :border]] [str greeting ", " name "!"] [str "cube " x "x" y "x" z] ; after "1px solid {[color :border]}" "{greeting}, {name}!" "cube {x}x{y}x{z}" ``` -------------------------------- ### Loon AI Model Configuration Source: https://github.com/ecto/loon/blob/main/DESIGN.md Configure AI model settings for different purposes (default, compile-time, agent loops) and enable/disable caching and offline mode within the `loon.toml` file. ```toml # loon.toml [ai] default-model = "claude-sonnet" compile-model = "claude-haiku" # fast model for [ai defn] blocks agent-model = "claude-opus" # capable model for [agent] blocks cache = true offline = false ``` -------------------------------- ### Loon Build Commands Source: https://github.com/ecto/loon/blob/main/DESIGN.md Commands for building and running Loon projects. `loon build` produces WASM bytecode, `loon build --release` creates optimized builds, and `loon run` builds and executes the WASM module using Wasmtime. ```sh loon build # produces target/main.wasm loon build --release # optimized, tree-shaken loon run # build + execute via Wasmtime ``` -------------------------------- ### Loon Primitive Types Source: https://github.com/ecto/loon/blob/main/DESIGN.md Illustrates the syntax for defining various primitive data types in Loon, including integers, floats, booleans, strings, and keywords, with optional explicit type suffixes. ```loon 42 ; i64 (default integer) 42i32 ; i32 (suffix for non-default) 3.14 ; f64 (default float) 3.14f32 ; f32 true ; Bool "hello" ; String :keyword ; Keyword (interned symbol) ``` -------------------------------- ### Module naming convention Source: https://github.com/ecto/loon/blob/main/DESIGN.md Each `.oo` or `.loon` file represents a module. The module name is derived from its relative path within the `src/` directory. ```text src/ main.oo ; module: main http/ server.oo ; module: http.server client.oo ; module: http.client ``` -------------------------------- ### Shadowing Built-in Functions with User Functions Source: https://github.com/ecto/loon/blob/main/docs/elegance-notes.md Shows how user-defined functions now shadow built-in functions. Previously, built-in functions took precedence, leading to silent ignoring of user definitions. This change affects function resolution in `lower_call`. ```Loon [fn sum [x y] [+ x y]] ``` -------------------------------- ### Let Statement as Expression Source: https://github.com/ecto/loon/blob/main/docs/elegance-notes.md Discusses the potential change for `let` to be an expression rather than a body statement. This would allow `let` to be used in sub-expressions, improving composability, similar to Clojure's `let` form. ```Loon [let x v body] ``` -------------------------------- ### Simple List in Loon Source: https://github.com/ecto/loon/blob/main/tree-sitter-loon/test/corpus/forms.txt A basic list containing a symbol and a string. Demonstrates list structure. ```Loon [println "hello"] ``` -------------------------------- ### Handle Effects at the Call Site Source: https://github.com/ecto/loon/blob/main/DESIGN.md Use the `handle` construct to specify how declared effects should be resolved. This allows for different implementations, like mocking or actual operations. ```loon [handle [load-config "app.toml"] [IO.read-file path] => [resume [mock-fs.read path]] [IO.write-file _ _] => [resume] [Fail.fail msg] => [Config.default]] ```