### Run C FFI example Source: https://github.com/archangeljtw/lust-lang/blob/master/examples/c-ffi/README.md Runs the compiled example. Expected output is '20 + 22 = 42' and 'stored main.answer = 42'. ```bash ./lust_ffi_example ``` -------------------------------- ### Install lust-analyzer with cargo Source: https://github.com/archangeljtw/lust-lang/blob/master/crates/lust-analyzer/README.md Install the Lust Analyzer language server from crates.io. After installation, point your editor's LSP client at the spawned process to explore the current feature set. ```bash cargo install lust-analyzer ``` -------------------------------- ### Example directory structure Source: https://github.com/archangeljtw/lust-lang/blob/master/examples/rust-extension/README.md Directory layout for the Rust extension example, showing the extension crates, configuration file, and main Lust script. ```text examples/rust-extension/ ├── extensions/ │ ├── double/ │ │ ├── Cargo.toml │ │ └── src/lib.rs │ └── triple/ │ ├── Cargo.toml │ └── src/lib.rs ├── lust-config.toml └── main.lust ``` -------------------------------- ### Install Lust CLI and package commands Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Installs the Lust CLI and shows common package management commands: help, add, remove, login, publish, and logout. ```bash cargo install lust-rs lust --help lust pkg add example-package lust pkg remove example-package lust pkg login lust pkg publish lust pkg logout ``` -------------------------------- ### Install Lust parser with :TSInstall Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Installs the Lust parser in Neovim after manual setup. ```vim :TSInstall lust ``` -------------------------------- ### Manually install tree-sitter-lust in Neovim Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Manual installation steps: create the parser directory, copy the parser files, and register the parser in init.lua with filetype detection. ```bash mkdir -p ~/.local/share/nvim/site/pack/tree-sitter/start/tree-sitter-lust ``` ```bash cp -r tree-sitter-lust/* ~/.local/share/nvim/site/pack/tree-sitter/start/tree-sitter-lust/ ``` ```lua -- Register the parser local parser_config = require("nvim-treesitter.parsers").get_parser_configs() parser_config.lust = { install_info = { url = "~/.local/share/nvim/site/pack/tree-sitter/start/tree-sitter-lust", files = {"src/parser.c", "src/scanner.c"} }, filetype = "lust", } -- Set up filetype detection vim.filetype.add({ extension = { lust = "lust", }, }) ``` -------------------------------- ### Install tree-sitter-cli globally Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Installs the tree-sitter CLI globally, which is required to generate and test the parser. ```bash npm install -g tree-sitter-cli ``` -------------------------------- ### Compile C FFI example Source: https://github.com/archangeljtw/lust-lang/blob/master/examples/c-ffi/README.md Compiles the C example against the Lust library. On Linux and macOS you may need to add an rpath so the loader can find liblust at runtime; on Windows link against lust.lib and ensure lust.dll is alongside the executable. ```bash cc main.c -I../../include -L../../target/release -llust -o lust_ffi_example ``` -------------------------------- ### Embed Lust code in C using lust_ffi.h Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Minimal C ABI example for compiling and calling Lust code from a native host. Requires the `include/lust_ffi.h` header and linking against `liblust` built with `cargo build --release --lib`. A complete example is in `examples/c-ffi`. ```c #include "lust_ffi.h" int main(void) { EmbeddedBuilder *builder = lust_builder_new(); lust_builder_add_module(builder, "main", "function answer(): int\n return 42\nend\n"); lust_builder_set_entry_module(builder, "main"); EmbeddedProgram *program = lust_builder_compile(builder); LustFfiValue result = {0}; lust_program_call(program, "main.answer", NULL, 0, &result); /* ... */ } ``` -------------------------------- ### Build the tree-sitter-lust parser Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Builds the parser by entering the project directory, installing dependencies, and generating the parser code. ```bash cd tree-sitter-lust npm install tree-sitter generate ``` -------------------------------- ### Configure lust-config.toml for modules and settings Source: https://github.com/archangeljtw/lust-lang/blob/master/skills/coding-lust/SKILL.md Place this file in the project root to configure modules and settings. The [settings] section enables optional standard library modules and toggles the JIT compiler (default: true). The [dependencies] section is for package dependencies, with commented examples for a versioned package and a local path package. ```toml [settings] stdlib_modules = ["io", "os"] # Enable optional standard library modules jit = true # Enable JIT compiler (default: true) [dependencies] # Dependencies when using packages # my-lib = "0.1.0" # local-pkg = { path = "../local-pkg" } ``` -------------------------------- ### Build Lust shared library Source: https://github.com/archangeljtw/lust-lang/blob/master/examples/c-ffi/README.md Builds the Lust shared library in release mode, producing the C ABI artifacts required by the example. ```bash cargo build --release --lib ``` -------------------------------- ### Test the parser with tree-sitter Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Tests the parser by parsing an example file and running the test suite if test cases exist. ```bash # Parse a file tree-sitter parse ../examples/hello.lust # Run tests (if you create test cases) tree-sitter test ``` -------------------------------- ### Configure nvim-treesitter with lazy.nvim for Lust Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Configures nvim-treesitter with lazy.nvim to install and use the Lust parser. Points to a local path and disables npm generation. ```lua { "nvim-treesitter/nvim-treesitter", build = ":TSUpdate", config = function() -- Add lust parser local parser_config = require("nvim-treesitter.parsers").get_parser_configs() parser_config.lust = { install_info = { url = "~/Desktop/Code/rs/lust-lang/tree-sitter-lust", -- local path files = {"src/parser.c", "src/scanner.c"}, branch = "main", generate_requires_npm = false, requires_generate_from_grammar = false, }, filetype = "lust", } require("nvim-treesitter.configs").setup({ highlight = { enable = true, }, }) end, } ``` -------------------------------- ### Test case format for corpus Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Shows the format for adding test cases in test/corpus/. The example includes a function declaration and its expected syntax tree. ```text ================================================================================ Function declaration ================================================================================ function add(a: int, b: int): int return a + b end -------------------------------------------------------------------------------- (source_file (function_declaration name: (identifier) parameters: (parameter_list (parameter name: (identifier) type: (primitive_type)) (parameter name: (identifier) type: (primitive_type))) return_type: (primitive_type) (return_statement (binary_expression)))) ``` -------------------------------- ### Project file structure Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Shows the directory layout of the tree-sitter-lust project, including grammar.js, package.json, src/, queries/, and test/ directories. ```text tree-sitter-lust/ ├── grammar.js # Grammar definition ├── package.json # NPM package config ├── binding.gyp # Node.js binding config ├── src/ │ ├── parser.c # Generated parser (after tree-sitter generate) │ ├── scanner.c # Custom scanner (if needed) │ └── tree_sitter/ ├── queries/ │ ├── highlights.scm # Syntax highlighting queries │ ├── injections.scm # (optional) Language injections │ └── locals.scm # (optional) Local scope tracking └── test/ └── corpus/ # Test cases (optional) ``` -------------------------------- ### Run the Lust program Source: https://github.com/archangeljtw/lust-lang/blob/master/examples/rust-extension/README.md Executes the Lust program, loading the compiled shared libraries and invoking their register hooks so the script can use the native bindings. ```bash lust examples/rust-extension/main.lust ``` -------------------------------- ### Run numeric microbenchmarks Source: https://github.com/archangeljtw/lust-lang/blob/master/benchmarks/README.md Run the numeric VM/x86_64 JIT microbenchmarks with this command. The harness compiles typed Lust functions, warms each function with 1,000 iterations, and reports the median of seven calls. Parsing, typechecking, and initial trace compilation are outside the timer. The VM runs 250,000 iterations per call and the JIT runs 100,000,000. ```sh cargo run --release --example numeric ``` -------------------------------- ### Run tree-sitter tests Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Command to run the tree-sitter test suite. ```bash tree-sitter test ``` -------------------------------- ### Generate extern stubs with lust --dump-externs Source: https://github.com/archangeljtw/lust-lang/blob/master/examples/rust-extension/README.md Builds the extension crates, executes their lust_extension_register hooks, and emits extern stubs under examples/rust-extension/externs//. ```bash lust --dump-externs examples/rust-extension/main.lust ``` -------------------------------- ### Variable Declarations and Assignments in Lust Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/test/corpus/statements.txt Shows Lust syntax for local variable declarations with and without type annotations, multiple bindings, and assignment operators. The parse tree demonstrates the grammar structure for these constructs. ```lust local x: int = 42 local a, b = 1, 2 x += 10 y: string = "hello" ``` ```tree-sitter (source_file (local_declaration bindings: (binding_list (binding name: (identifier) type: (type_annotation (primitive_type)))) values: (expression_list (literal (number)))) (local_declaration bindings: (binding_list (binding name: (identifier)) (binding name: (identifier))) values: (expression_list (literal (number)) (literal (number)))) (assignment target: (assignment_target (identifier)) value: (literal (number))) (assignment bindings: (binding_list (binding name: (identifier) type: (type_annotation (primitive_type)))) values: (expression_list (literal (string))))) ``` -------------------------------- ### Create VS Code extension for Lust Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Creates a VS Code extension directory and package.json that declares the Lust language and grammar contributions. ```bash mkdir vscode-lust cd vscode-lust npm init -y ``` ```json { "name": "lust-language-support", "displayName": "Lust Language Support", "description": "Syntax highlighting for Lust programming language", "version": "0.1.0", "engines": { "vscode": "^1.70.0" }, "contributes": { "languages": [{ "id": "lust", "extensions": [".lust"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "lust", "scopeName": "source.lust", "path": "./syntaxes/lust.tmLanguage.json" }] } } ``` -------------------------------- ### Generic functions, structs, impls, and enums in Lust Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/test/corpus/generics.txt Defines generic functions, a generic struct with an impl block, and a generic enum, then exercises them with concrete type arguments and pattern matching. Shows generic type parameters in angle brackets, the impl syntax for methods, and the `is Data(text)` pattern match on a generic enum variant. ```lust function first(values: Array): Element return values[0]:unwrap() end function default_value(value: int): int return value end struct Box value: Item end impl Box function get(self): Item return self.value end end enum Message Data(Payload) Empty end local numbers: Array = [10, 20, 30] local number_box: Box = Box { value = first(numbers) } local message: Message = Message.Data("hello") println(number_box:get()) println(default_value(7)) if message is Data(text) then println(text) end ``` -------------------------------- ### Parse a file with tree-sitter Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Command to parse a Lust file and display its syntax tree for debugging. ```bash tree-sitter parse examples/hello.lust ``` -------------------------------- ### Inspect JIT stats with program.jit_stats() Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Inspect cumulative JIT activation counters after calling Lust code. The `JitStats` value exposes `root_traces_compiled`, `native_trace_entries`, and `recursive_calls`. `VM::jit_stats()` returns the same value. ```rust let stats = program.jit_stats(); println!("compiled roots: {}", stats.root_traces_compiled); println!("native entries: {}", stats.native_trace_entries); println!("recursive calls: {}", stats.recursive_calls); ``` -------------------------------- ### Configure tree-sitter extension in VS Code settings.json Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/README.md Adds the Lust grammar to VS Code's tree-sitter extension settings, pointing to the local parser path. ```json { "treesitter.grammars": [ { "language": "lust", "path": "/full/path/to/tree-sitter-lust" } ] } ``` -------------------------------- ### Add lust-rs crate with rename Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Adds the lust-rs crate to a Rust project, renaming it to 'lust' for ergonomic imports. ```bash cargo add lust-rs --rename lust ``` -------------------------------- ### While and For Loops in Lust Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/test/corpus/statements.txt Illustrates Lust loop constructs: a while loop with a decrementing assignment, a numeric for loop with a step, and an iterator-based for-in loop. The parse tree shows the grammar for each loop type. ```lust while x > 0 do x -= 1 end for i = 1, 10, 2 do println(i) end for k, v in map:iter() do println(k) end ``` ```tree-sitter (source_file (while_statement condition: (binary_expression left: (identifier) right: (literal (number))) (assignment target: (assignment_target (identifier)) value: (literal (number)))) (for_statement (for_numeric_statement variable: (identifier) start: (literal (number)) end: (literal (number)) step: (literal (number)) (expression_statement (call_expression function: (identifier) arguments: (argument_list (identifier)))))) (for_statement (for_in_statement variables: (identifier) variables: (identifier) iterator: (method_call_expression object: (identifier) method: (identifier) arguments: (argument_list)) (expression_statement (call_expression function: (identifier) arguments: (argument_list (identifier))))))) ``` -------------------------------- ### Declare Rust extension crates in lust-config.toml Source: https://github.com/archangeljtw/lust-lang/blob/master/examples/rust-extension/README.md Declares the Rust extension crates in lust-config.toml using the new dependency table with kind = "rust". ```toml [dependencies] lust-double = { path = "extensions/double", kind = "rust" } lust-triple = { path = "extensions/triple", kind = "rust" } ``` -------------------------------- ### Dump externs to directory Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Writes Lust-readable extern stubs to disk from an embedder, useful when native APIs are registered with export metadata. ```rust let _ = program.dump_externs_to_dir("externs"); ``` -------------------------------- ### Generic struct with universal impl Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Generic struct with a universal impl. Specialized impls such as impl Box are rejected; use one universal impl Box. ```lust struct Box value: Item end impl Box function get(self): Item return self.value end end ``` -------------------------------- ### Global Built-in Functions Source: https://github.com/archangeljtw/lust-lang/blob/master/skills/coding-lust/SKILL.md Global built-in functions available in the Lust language standard library. ```APIDOC ## print(...) ### Description Prints values separated by tabs without a trailing newline. ### Method Function ### Signature `print(...)` ### Parameters - `...` (any) - Required - Values to print. ### Returns None. ``` ```APIDOC ## println(...) ### Description Prints values separated by tabs with a trailing newline. ### Method Function ### Signature `println(...)` ### Parameters - `...` (any) - Required - Values to print. ### Returns None. ``` ```APIDOC ## type(val) ### Description Returns the runtime type name as a string. ### Method Function ### Signature `type(val)` ### Parameters - `val` (any) - Required - Value to inspect. ### Returns - `string` - The runtime type name (e.g., "int", "float", "string", "bool", "array", "map", "struct", "enum", "function"). ``` ```APIDOC ## tostring(val) ### Description Converts any value to a string. ### Method Function ### Signature `tostring(val)` ### Parameters - `val` (any) - Required - Value to convert. ### Returns - `string` - The string representation of the value. ``` ```APIDOC ## tonumber(val [, base]) ### Description Converts a string, int, float, or bool to a number. ### Method Function ### Signature `tonumber(val [, base])` ### Parameters - `val` (string|int|float|bool) - Required - Value to convert. - `base` (int) - Optional - Base for string conversion. ### Returns - `number` - The numeric value. ``` ```APIDOC ## error(message) ### Description Raises a runtime error with the given message. ### Method Function ### Signature `error(message)` ### Parameters - `message` (string) - Required - Error message. ### Returns Never returns (raises error). ``` ```APIDOC ## assert(cond [, message]) ### Description Asserts that a condition is truthy; raises an error otherwise. ### Method Function ### Signature `assert(cond [, message])` ### Parameters - `cond` (any) - Required - Condition to check. - `message` (string) - Optional - Error message if assertion fails. ### Returns None (raises error if condition is falsy). ``` ```APIDOC ## select(index_or_hash, ...) ### Description Returns argument count for "#" or returns a slice starting at a 1-based index. ### Method Function ### Signature `select(index_or_hash, ...)` ### Parameters - `index_or_hash` (string|int) - Required - Either "#" to get count or a 1-based index. - `...` (any) - Required - Arguments to select from. ### Returns - `int` - If index_or_hash is "#", returns the number of arguments. - `any...` - Otherwise, returns the slice of arguments starting at the given index. ``` ```APIDOC ## random([m [, n]]) ### Description Generates a random float in [0, 1), or an integer in [1, m] or [m, n]. ### Method Function ### Signature `random([m [, n]])` ### Parameters - `m` (int) - Optional - Upper bound for integer range. - `n` (int) - Optional - Upper bound for integer range when m is provided. ### Returns - `float` - If no arguments, a random float in [0, 1). - `int` - If m or m and n are provided, a random integer in the specified range. ``` ```APIDOC ## randomseed(seed) ### Description Seeds the random number generator. ### Method Function ### Signature `randomseed(seed)` ### Parameters - `seed` (int) - Required - Seed value. ### Returns None. ``` ```APIDOC ## unpack(arr [, i [, j]]) ### Description Unpacks array elements into multiple return values. ### Method Function ### Signature `unpack(arr [, i [, j]])` ### Parameters - `arr` (Array) - Required - Array to unpack. - `i` (int) - Optional - Starting index (1-based). - `j` (int) - Optional - Ending index (inclusive). ### Returns - `any...` - The unpacked elements. ``` ```APIDOC ## pairs(map_or_table) ### Description Returns an iterator over key/value pairs. ### Method Function ### Signature `pairs(map_or_table)` ### Parameters - `map_or_table` (Map|Table) - Required - Map or table to iterate. ### Returns - `Iterator` - Iterator yielding key/value pairs. ``` ```APIDOC ## ipairs(arr_or_table) ### Description Returns an iterator over index/value pairs. ### Method Function ### Signature `ipairs(arr_or_table)` ### Parameters - `arr_or_table` (Array|Table) - Required - Array or table to iterate. ### Returns - `Iterator` - Iterator yielding index/value pairs. ``` -------------------------------- ### Trait and impl declaration with parse tree Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/test/corpus/declarations.txt Shows the Lust syntax for a trait declaration and a generic impl block, along with the corresponding tree-sitter parse tree. The trait `Drawable` declares a method `draw` returning unit, and the impl provides that method for `Box` returning `true`. ```lust local trait Drawable function draw(self): () end impl Drawable for Box function draw(self): () return true end end ``` ```sexp (source_file (trait_declaration (visibility) name: (identifier) (trait_method name: (identifier) parameters: (parameter_list (parameter name: (identifier))) return_type: (type_annotation (unit_type)))) (impl_block (type_parameters (type_parameter name: (identifier))) trait: (type_annotation (identifier)) type: (type_annotation (generic_type name: (identifier) (type_annotation (identifier)))) (function_declaration name: (identifier) parameters: (parameter_list (parameter name: (identifier))) return_type: (type_annotation (unit_type)) (return_statement (expression_list (literal (boolean))))))) ``` -------------------------------- ### Fallible extraction with as and is Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Shows fallible extraction from `unknown` using `as` and pattern matching with `is`, returning Option. Casts and patterns associate left-to-right. ```lust if value as int is Some(x) and x > 0 then print(x) end ``` -------------------------------- ### Option Methods Source: https://github.com/archangeljtw/lust-lang/blob/master/skills/coding-lust/SKILL.md Built-in methods for the Option type. ```APIDOC ## opt:is_some(): bool ### Description Returns true if the Option contains a value. ### Method Method ### Signature `opt:is_some(): bool` ### Parameters None. ### Returns - `bool` - True if the Option is Some. ``` ```APIDOC ## opt:is_none(): bool ### Description Returns true if the Option is None. ### Method Method ### Signature `opt:is_none(): bool` ### Parameters None. ### Returns - `bool` - True if the Option is None. ``` ```APIDOC ## opt:unwrap(): T ### Description Returns the contained value, panicking if the Option is None. ### Method Method ### Signature `opt:unwrap(): T` ### Parameters None. ### Returns - `T` - The contained value. ### Errors Panics if the Option is None. ``` ```APIDOC ## opt:unwrap_or(default: T): T ### Description Returns the contained value or a default if None. ### Method Method ### Signature `opt:unwrap_or(default: T): T` ### Parameters - `default` (T) - Required - Default value to return if None. ### Returns - `T` - The contained value or the default. ``` -------------------------------- ### Function declaration with generic type bounds and parse tree Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/test/corpus/declarations.txt Shows the Lust syntax for a generic function declaration with type bounds and the corresponding tree-sitter parse tree. The function `add` takes two parameters of the same type `T` bounded by `Display` and `Clone`, returns `T`, and returns the sum of its arguments. ```lust local function add(a: T, b: T): T return a + b end ``` ```sexp (source_file (function_declaration (visibility) name: (identifier) (type_parameters (type_parameter name: (identifier) bound: (identifier) bound: (identifier))) parameters: (parameter_list (parameter name: (identifier) type: (type_annotation (identifier))) (parameter name: (identifier) type: (type_annotation (identifier)))) return_type: (type_annotation (identifier)) (return_statement (expression_list (binary_expression left: (identifier) right: (identifier)))))) ``` -------------------------------- ### Handle array index errors with Result Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Demonstrates non-trapping array bracket reads that return Result, with IndexError exposing index and length. ```lust local values: Array = ["first", "second"] if values[2] is Ok(value) then print(value) elseif values[2] is Err(error) then print("index " .. error.index .. " exceeds length " .. error.length) end ``` -------------------------------- ### Pattern match with is operator Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Uses the `is` operator to test and bind a pattern, printing the bound value. ```lust if status is Complete(value) then print("done(" .. value .. ")") end ``` -------------------------------- ### Struct declaration with reference and generic fields and parse tree Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/test/corpus/declarations.txt Shows the Lust syntax for a struct declaration with fields of primitive, reference, and generic types, along with its tree-sitter parse tree. The struct `Node` has a `name` field of type `string`, a `parent` field of type `ref Node`, and a `children` field of type `Array`. ```lust local struct Node name: string, parent: ref Node, children: Array end ``` ```sexp (source_file (struct_declaration (visibility) name: (identifier) (struct_field name: (identifier) type: (type_annotation (primitive_type))) (struct_field name: (identifier) type: (type_annotation (identifier))) (struct_field name: (identifier) type: (type_annotation (generic_type name: (identifier) (type_annotation (identifier))))))) ``` -------------------------------- ### string Module Source: https://github.com/archangeljtw/lust-lang/blob/master/skills/coding-lust/SKILL.md Functions in the string module for string manipulation. ```APIDOC ## string.len(s: string): int ### Description Returns the length of the string. ### Method Function ### Signature `string.len(s: string): int` ### Parameters - `s` (string) - Required - The string. ### Returns - `int` - Number of characters. ``` ```APIDOC ## string.sub(s: string, i: int [, j: int]): string ### Description Returns a substring using 1-based indices; negative counts from the end. ### Method Function ### Signature `string.sub(s: string, i: int [, j: int]): string` ### Parameters - `s` (string) - Required - The string. - `i` (int) - Required - Start index (1-based). - `j` (int) - Optional - End index (inclusive). ### Returns - `string` - The substring. ``` ```APIDOC ## string.lower(s: string): string ### Description Converts the string to lowercase. ### Method Function ### Signature `string.lower(s: string): string` ### Parameters - `s` (string) - Required - The string. ### Returns - `string` - Lowercase string. ``` ```APIDOC ## string.upper(s: string): string ### Description Converts the string to uppercase. ### Method Function ### Signature `string.upper(s: string): string` ### Parameters - `s` (string) - Required - The string. ### Returns - `string` - Uppercase string. ``` ```APIDOC ## string.byte(s: string [, i [, j]]): unknown ### Description Returns byte values of the string. ### Method Function ### Signature `string.byte(s: string [, i [, j]]): unknown` ### Parameters - `s` (string) - Required - The string. - `i` (int) - Optional - Start index. - `j` (int) - Optional - End index. ### Returns - `unknown` - Byte values. ``` ```APIDOC ## string.char(byte: int...): string ### Description Converts byte values to a string. ### Method Function ### Signature `string.char(byte: int...): string` ### Parameters - `byte` (int...) - Required - Byte values. ### Returns - `string` - The resulting string. ``` ```APIDOC ## string.find(s: string, pattern: string [, init [, plain]]): unknown ### Description Finds the first occurrence of a pattern in the string. ### Method Function ### Signature `string.find(s: string, pattern: string [, init [, plain]]): unknown` ### Parameters - `s` (string) - Required - The string. - `pattern` (string) - Required - Pattern to search. - `init` (int) - Optional - Starting index. - `plain` (bool) - Optional - If true, treat pattern as plain text. ### Returns - `unknown` - Match information. ``` ```APIDOC ## string.match(s: string, pattern: string [, init]): unknown ### Description Matches a pattern against the string. ### Method Function ### Signature `string.match(s: string, pattern: string [, init]): unknown` ### Parameters - `s` (string) - Required - The string. - `pattern` (string) - Required - Pattern to match. - `init` (int) - Optional - Starting index. ### Returns - `unknown` - Match results. ``` ```APIDOC ## string.gsub(s: string, pattern: string, repl: unknown [, n]): unknown ### Description Replaces occurrences of a pattern with a replacement. ### Method Function ### Signature `string.gsub(s: string, pattern: string, repl: unknown [, n]): unknown` ### Parameters - `s` (string) - Required - The string. - `pattern` (string) - Required - Pattern to replace. - `repl` (unknown) - Required - Replacement. - `n` (int) - Optional - Maximum number of replacements. ### Returns - `unknown` - Result string and count. ``` ```APIDOC ## string.format(fmt: string, ...): string ### Description Formats a string using the given format and arguments. ### Method Function ### Signature `string.format(fmt: string, ...): string` ### Parameters - `fmt` (string) - Required - Format string. - `...` (any) - Required - Values to format. ### Returns - `string` - Formatted string. ``` ```APIDOC ## string.rep(s: string, n: int [, sep: string]): string ### Description Repeats the string n times, optionally with a separator. ### Method Function ### Signature `string.rep(s: string, n: int [, sep: string]): string` ### Parameters - `s` (string) - Required - The string. - `n` (int) - Required - Number of repetitions. - `sep` (string) - Optional - Separator. ### Returns - `string` - Repeated string. ``` ```APIDOC ## string.reverse(s: string): string ### Description Reverses the string. ### Method Function ### Signature `string.reverse(s: string): string` ### Parameters - `s` (string) - Required - The string. ### Returns - `string` - Reversed string. ``` ```APIDOC ## string.split(s: string, delimiter: string): Array ### Description Splits the string by a delimiter into an array. ### Method Function ### Signature `string.split(s: string, delimiter: string): Array` ### Parameters - `s` (string) - Required - The string. - `delimiter` (string) - Required - Delimiter. ### Returns - `Array` - Array of substrings. ``` ```APIDOC ## string.trim(s: string): string ### Description Removes leading and trailing whitespace. ### Method Function ### Signature `string.trim(s: string): string` ### Parameters - `s` (string) - Required - The string. ### Returns - `string` - Trimmed string. ``` ```APIDOC ## string.trim_start(s: string): string ### Description Removes leading whitespace. ### Method Function ### Signature `string.trim_start(s: string): string` ### Parameters - `s` (string) - Required - The string. ### Returns - `string` - Trimmed string. ``` ```APIDOC ## string.trim_end(s: string): string ### Description Removes trailing whitespace. ### Method Function ### Signature `string.trim_end(s: string): string` ### Parameters - `s` (string) - Required - The string. ### Returns - `string` - Trimmed string. ``` ```APIDOC ## string.replace(s: string, from: string, to: string): string ### Description Replaces all occurrences of a substring with another. ### Method Function ### Signature `string.replace(s: string, from: string, to: string): string` ### Parameters - `s` (string) - Required - The string. - `from` (string) - Required - Substring to replace. - `to` (string) - Required - Replacement. ### Returns - `string` - Resulting string. ``` ```APIDOC ## string.starts_with(s: string, prefix: string): bool ### Description Returns true if the string starts with the given prefix. ### Method Function ### Signature `string.starts_with(s: string, prefix: string): bool` ### Parameters - `s` (string) - Required - The string. - `prefix` (string) - Required - Prefix to check. ### Returns - `bool` - True if starts with prefix. ``` ```APIDOC ## string.ends_with(s: string, suffix: string): bool ### Description Returns true if the string ends with the given suffix. ### Method Function ### Signature `string.ends_with(s: string, suffix: string): bool` ### Parameters - `s` (string) - Required - The string. - `suffix` (string) - Required - Suffix to check. ### Returns - `bool` - True if ends with suffix. ``` ```APIDOC ## string.contains(s: string, substring: string): bool ### Description Returns true if the string contains the given substring. ### Method Function ### Signature `string.contains(s: string, substring: string): bool` ### Parameters - `s` (string) - Required - The string. - `substring` (string) - Required - Substring to search. ### Returns - `bool` - True if found. ``` ```APIDOC ## string.is_empty(s: string): bool ### Description Returns true if the string is empty. ### Method Function ### Signature `string.is_empty(s: string): bool` ### Parameters - `s` (string) - Required - The string. ### Returns - `bool` - True if empty. ``` ```APIDOC ## string.chars(s: string): Array ### Description Returns an array of individual characters. ### Method Function ### Signature `string.chars(s: string): Array` ### Parameters - `s` (string) - Required - The string. ### Returns - `Array` - Array of characters. ``` ```APIDOC ## string.lines(s: string): Array ### Description Splits the string into lines. ### Method Function ### Signature `string.lines(s: string): Array` ### Parameters - `s` (string) - Required - The string. ### Returns - `Array` - Array of lines. ``` -------------------------------- ### Embed Lust program in Rust Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Embeds a Lust program in Rust using EmbeddedProgram, compiles a module, and calls a typed function. ```rust use lust::EmbeddedProgram; fn main() -> lust::Result<()> { let mut program = EmbeddedProgram::builder() .module("main", r#" function greet(name: string): string return "hi, " .. name end "#) .entry_module("main") .compile()?; let greeting: String = program.call_typed("main.greet", "Lust")?; println!("{greeting}"); Ok(()) } ``` -------------------------------- ### Pattern Matching with is Expression in Lust Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/test/corpus/statements.txt Demonstrates the is expression for type pattern matching, checking if a variable is of type string or int. The parse tree shows the union type annotation in the condition. ```lust if x is string | int then println("matched") end ``` ```tree-sitter (source_file (if_statement condition: (is_expression value: (identifier) pattern: (type_annotation (union_type (type_annotation (primitive_type)) (type_annotation (primitive_type))))) (expression_statement (call_expression function: (identifier) arguments: (argument_list (literal (string))))))) ``` -------------------------------- ### Result Methods Source: https://github.com/archangeljtw/lust-lang/blob/master/skills/coding-lust/SKILL.md Built-in methods for the Result type. ```APIDOC ## res:is_ok(): bool ### Description Returns true if the Result is Ok. ### Method Method ### Signature `res:is_ok(): bool` ### Parameters None. ### Returns - `bool` - True if the Result is Ok. ``` ```APIDOC ## res:is_err(): bool ### Description Returns true if the Result is Err. ### Method Method ### Signature `res:is_err(): bool` ### Parameters None. ### Returns - `bool` - True if the Result is Err. ``` ```APIDOC ## res:unwrap(): T ### Description Returns the contained Ok value, panicking if the Result is Err. ### Method Method ### Signature `res:unwrap(): T` ### Parameters None. ### Returns - `T` - The contained Ok value. ### Errors Panics if the Result is Err. ``` ```APIDOC ## res:unwrap_or(default: T): T ### Description Returns the contained Ok value or a default if Err. ### Method Method ### Signature `res:unwrap_or(default: T): T` ### Parameters - `default` (T) - Required - Default value to return if Err. ### Returns - `T` - The contained Ok value or the default. ``` -------------------------------- ### map Module Source: https://github.com/archangeljtw/lust-lang/blob/master/skills/coding-lust/SKILL.md Functions in the map module for map manipulation. ```APIDOC ## map.len(m: Map): int ### Description Returns the number of key-value pairs in the map. ### Method Function ### Signature `map.len(m: Map): int` ### Parameters - `m` (Map) - Required - The map. ### Returns - `int` - Number of entries. ``` ```APIDOC ## map.is_empty(m: Map): bool ### Description Returns true if the map is empty. ### Method Function ### Signature `map.is_empty(m: Map): bool` ### Parameters - `m` (Map) - Required - The map. ### Returns - `bool` - True if empty. ``` ```APIDOC ## map.get(m: Map, key: K): Option ### Description Returns the value associated with the key as an Option. ### Method Function ### Signature `map.get(m: Map, key: K): Option` ### Parameters - `m` (Map) - Required - The map. - `key` (K) - Required - Key to look up. ### Returns - `Option` - The value or None if key not found. ``` ```APIDOC ## map.set(m: Map, key: K, val: V): () ### Description Sets the value for the given key. ### Method Function ### Signature `map.set(m: Map, key: K, val: V): ()` ### Parameters - `m` (Map) - Required - The map. - `key` (K) - Required - Key. - `val` (V) - Required - Value. ### Returns None. ``` ```APIDOC ## map.has(m: Map, key: K): bool ### Description Returns true if the map contains the given key. ### Method Function ### Signature `map.has(m: Map, key: K): bool` ### Parameters - `m` (Map) - Required - The map. - `key` (K) - Required - Key to check. ### Returns - `bool` - True if key exists. ``` ```APIDOC ## map.delete(m: Map, key: K): Option ### Description Removes the entry for the given key and returns the value. ### Method Function ### Signature `map.delete(m: Map, key: K): Option` ### Parameters - `m` (Map) - Required - The map. - `key` (K) - Required - Key to delete. ### Returns - `Option` - The removed value or None if key not found. ``` ```APIDOC ## map.clear(m: Map): () ### Description Removes all entries from the map. ### Method Function ### Signature `map.clear(m: Map): ()` ### Parameters - `m` (Map) - Required - The map. ### Returns None. ``` ```APIDOC ## map.keys(m: Map): Array ### Description Returns an array of all keys in the map. ### Method Function ### Signature `map.keys(m: Map): Array` ### Parameters - `m` (Map) - Required - The map. ### Returns - `Array` - Array of keys. ``` ```APIDOC ## map.values(m: Map): Array ### Description Returns an array of all values in the map. ### Method Function ### Signature `map.values(m: Map): Array` ### Parameters - `m` (Map) - Required - The map. ### Returns - `Array` - Array of values. ``` ```APIDOC ## map.iter(m: Map): Iterator ### Description Returns an iterator that yields key-value pairs. ### Method Function ### Signature `map.iter(m: Map): Iterator` ### Parameters - `m` (Map) - Required - The map. ### Returns - `Iterator` - Iterator yielding key, value pairs. ``` -------------------------------- ### Generic functions with inference and explicit type arguments Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Generic functions with type parameters and recursive inference. Explicit type arguments use function_name(...) and are required when a parameter cannot be inferred. The '<' must directly follow the function name; spaced 'a < b' remains a comparison. ```lust function identity(value: Item): Item return value end function first(values: Array): Item return values[0]:unwrap() end local number: int = identity(42) local text: string = identity("hello") local first_number: int = first([1, 2, 3]) ``` -------------------------------- ### Enum declaration with generic type and parse tree Source: https://github.com/archangeljtw/lust-lang/blob/master/tree-sitter-lust/test/corpus/declarations.txt Shows the Lust syntax for a generic enum declaration with a variant that carries a value and a unit variant, along with its tree-sitter parse tree. The enum `Option` has variants `Some(T)` and `None`. ```lust local enum Option Some(T), None end ``` ```sexp (source_file (enum_declaration (visibility) name: (identifier) (type_parameters (type_parameter name: (identifier))) (enum_variant name: (identifier) (type_annotation (identifier))) (enum_variant name: (identifier)))) ``` -------------------------------- ### Iterator Methods Source: https://github.com/archangeljtw/lust-lang/blob/master/skills/coding-lust/SKILL.md Built-in methods for the Iterator type. ```APIDOC ## iter:iter(): Iterator ### Description Returns the iterator itself. ### Method Method ### Signature `iter:iter(): Iterator` ### Parameters None. ### Returns - `Iterator` - The iterator itself. ``` ```APIDOC ## iter:next(): Option ### Description Returns the next element in the iteration, or None if exhausted. ### Method Method ### Signature `iter:next(): Option` ### Parameters None. ### Returns - `Option` - The next element or None. ``` -------------------------------- ### Trait with generic bound and dynamic dispatch Source: https://github.com/archangeljtw/lust-lang/blob/master/README.md Trait definition with a generic bound and a dynamic trait type. A bare trait name is the dynamic constraint type, so no 'dyn' or 'interface' keyword is needed. Trait methods currently require one unannotated leading 'self'. ```lust trait Drawable function draw(self): string end function render(item: Item): string return item:draw() end function render_dynamic(item: Drawable): string return item:draw() end ```