### Install Editor Extensions Source: https://github.com/helgesverre/lira/blob/main/README.md Use the just command to install editor-specific support. ```bash just -install ``` -------------------------------- ### Install Lira LSP Source: https://github.com/helgesverre/lira/blob/main/editors/intellij-lira/README.md Install the Lira language server using Cargo. ```bash cargo install --path crates/lira-lsp ``` -------------------------------- ### Install Tree-sitter Parser Source: https://github.com/helgesverre/lira/blob/main/editors/vim-lira/README.md Run the installation command within Neovim. ```vim :TSInstall lira ``` -------------------------------- ### String Literal Examples Source: https://github.com/helgesverre/lira/blob/main/docs/01-lexical-structure.md Examples demonstrating string interpolation, raw strings, and multi-line string formatting. ```li // Simple strings let s1 = "Hello, World!" let s2 = "Line 1\nLine 2" let s3 = "Tab:\tvalue" // String interpolation let name = "Alice" let greeting = "Hello, ${name}!" let expr = "2 + 2 = ${2 + 2}" // Raw strings (no escape processing) let path = r"C:\Users\helge\file.txt" let regex = r"\d+\.\d+" // Multi-line strings let poem = """ Roses are red, Violets are blue, Lira is great, And so are you! """ // Multi-line preserves indentation relative to closing quotes let code = """ fn main() { print("Hello!") } """ ``` -------------------------------- ### Install Lira language server Source: https://github.com/helgesverre/lira/blob/main/editors/helix-lira/README.md Command to install the Lira LSP for IDE features. ```bash # From the lira repository cargo install --path crates/lira-lsp ``` -------------------------------- ### Install Lira extension manually Source: https://github.com/helgesverre/lira/blob/main/editors/zed-lira/README.md Commands to clone the repository and install the extension for development purposes. ```bash # Clone the lira repository git clone https://github.com/lira-lang/lira.git cd lira # Install as dev extension just zed-install ``` -------------------------------- ### Install Lira extension from VSIX Source: https://github.com/helgesverre/lira/blob/main/editors/vscode-lira/README.md Builds the extension package and installs it into VS Code using the command line. ```bash # Build the extension cd editors/vscode-lira npm install npm run package # Install in VS Code code --install-extension lira-lang-0.1.0.vsix ``` -------------------------------- ### Install and Generate Parser Source: https://github.com/helgesverre/lira/blob/main/editors/tree-sitter-lira/README.md Commands to install dependencies and generate the parser from the grammar definition. ```bash npm install npx tree-sitter generate ``` -------------------------------- ### Build command usage Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Options and examples for compiling Lira projects. ```bash lirac build [OPTIONS] [FILES...] OPTIONS: -o, --output Output file or directory --release Build with optimizations --debug Include debug information (default) --target Target platform (macos-x86_64, linux-x86_64) --lib Build as library --features Comma-separated feature flags -j, --jobs Number of parallel jobs EXAMPLES: # Build project in release mode lirac build --release # Build with specific features lirac build --features gui,network # Build specific file lirac build src/main.li -o app.lic ``` -------------------------------- ### Setup and Build Lira Source: https://github.com/helgesverre/lira/blob/main/README.md Commands to clone the repository and build the compiler and VM using the just command runner. ```bash git clone https://github.com/HelgeSverre/lira.git cd lira # Build the compiler and VM just build # Run the hello world example just run examples/hello.li ``` -------------------------------- ### Configure Vim/Neovim for Lira Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Plugin installation and auto-format configuration for .vimrc. ```vim " .vimrc Plug 'lira/lira.vim' " Format on save autocmd BufWritePre *.li :LiFormat ``` -------------------------------- ### Manual Installation of vim-lira Source: https://github.com/helgesverre/lira/blob/main/editors/vim-lira/README.md Copy the syntax and filetype files to your local Vim configuration directory. ```bash mkdir -p ~/.vim/ftdetect ~/.vim/ftplugin ~/.vim/syntax cp ftdetect/lira.vim ~/.vim/ftdetect/ cp ftplugin/lira.vim ~/.vim/ftplugin/ cp syntax/lira.vim ~/.vim/syntax/ ``` -------------------------------- ### Lira REPL session example Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Demonstration of defining variables, functions, and inspecting types within the REPL. ```text $ lir Lira REPL v1.0.0 Type :help for help, :quit to exit. >>> let x = 42 >>> x * 2 84 >>> fn greet(name: string) -> string { ... return "Hello, " + name + "!" ... } >>> greet("World") "Hello, World!" >>> :type greet fn(string) -> string >>> :quit ``` -------------------------------- ### Initialize and run the Lira frontend Source: https://github.com/helgesverre/lira/blob/main/lira-playground/README.md Commands to install dependencies and manage the React/TypeScript development and production builds. ```bash cd lira-playground/frontend # Install dependencies pnpm install # Development mode (uses localhost:3001 by default) pnpm dev # Build for production pnpm build ``` -------------------------------- ### Install vim-lira via Pathogen Source: https://github.com/helgesverre/lira/blob/main/editors/vim-lira/README.md Clone the repository directly into your bundle directory. ```bash cd ~/.vim/bundle git clone https://github.com/lira-lang/vim-lira.git ``` -------------------------------- ### Integer Literal Examples Source: https://github.com/helgesverre/lira/blob/main/docs/01-lexical-structure.md Examples of integer literals in Lira, demonstrating base prefixes, underscores for readability, and type suffixes. ```li // Decimal let a = 42 let b = 1_000_000 // Underscores for readability let c = 0 // Zero // Hexadecimal let d = 0xFF let e = 0xDEAD_BEEF // Octal let f = 0o755 let g = 0o177 // Binary let h = 0b1010_1100 let i = 0b11111111 // With type suffix let j = 255u8 // uint8 let k = -128i8 // int8 let l = 1_000_000i64 // int64 ``` -------------------------------- ### Run command usage Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Options and examples for executing Lira programs. ```bash lirac run [OPTIONS] [-- ARGS...] OPTIONS: --release Run with optimizations --example Run an example --bin Run a specific binary EXAMPLES: # Run main.li lirac run # Run with arguments lirac run -- arg1 arg2 # Run an example lirac run --example counter ``` -------------------------------- ### Start the LSP server Source: https://github.com/helgesverre/lira/blob/main/crates/lira-lsp/README.md Commands to launch the Lira LSP server via stdio or cargo. ```bash # Start the LSP server (stdio) lira-lsp # Or run directly with cargo cargo run -p lira-lsp ``` -------------------------------- ### Generated project structure Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Example file tree for a newly initialized Lira project. ```text my_app/ ├── li.toml ├── src/ │ └── main.li ├── ui/ │ └── main.liui └── .gitignore ``` -------------------------------- ### Start Lira Language Server Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Commands to launch the language server with standard or custom transport options. ```bash # Start language server li-lsp # With specific options li-lsp --stdio li-lsp --tcp --port 9999 ``` -------------------------------- ### Accessing Standard Library Help in REPL Source: https://github.com/helgesverre/lira/blob/main/docs/60-lira-repl.md Use the :help command followed by a module name to view available functions and usage examples. ```text >>> :help std.io std.io - Input/Output Module Functions: print(value: any) Print without newline println(value: any) Print with newline eprint(value: any) Print to stderr eprintln(value: any) Print to stderr with newline read_line() -> string Read line from stdin Examples: import std.io println("Enter your name:") let name = read_line() println("Hello, " + name) ``` -------------------------------- ### Lira Tool Installation Paths Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md List of binary paths for Lira tools after the build process is complete. ```bash # All tools available in /usr/bin /usr/bin/lic /usr/bin/livm /usr/bin/lir /usr/bin/lifmt /usr/bin/lidoc /usr/bin/lipkg ``` -------------------------------- ### Setup and Teardown Source: https://github.com/helgesverre/lira/blob/main/docs/51-testing.md Lifecycle hooks for managing test state within modules. ```APIDOC ## Setup and Teardown ### Description Lifecycle hooks to manage resources before and after tests. - `#[before_each]`: Runs before every test in the module. - `#[after_each]`: Runs after every test in the module. - `#[before_all]`: Runs once before all tests in the module. - `#[after_all]`: Runs once after all tests in the module. ``` -------------------------------- ### Example Lira Source File Source: https://github.com/helgesverre/lira/blob/main/docs/03-syntax-constructs.md Demonstrates a standard Lira file structure including module declaration, imports, constants, and the main function. ```li // Optional module declaration mod my_module // Imports import std.io import std.collections.{List, Map} // Declarations const VERSION = "1.0.0" fn main() { print("Hello!") } ``` -------------------------------- ### Use comment directives Source: https://github.com/helgesverre/lira/blob/main/docs/01-lexical-structure.md Examples of module-level documentation and various compiler hints. ```li //! Module-level documentation (first comment in file) // TODO: Implement this feature // FIXME: This is a known bug // HACK: Temporary workaround // NOTE: Important information // @deprecated Use newFunction() instead fn oldFunction() { } ``` -------------------------------- ### Build and run the Lira backend Source: https://github.com/helgesverre/lira/blob/main/lira-playground/README.md Commands to compile the Rust backend and start the server on the default or a custom port. ```bash # From the project root cargo build --release --package lira-playground # Start the server (default port 3001) ./target/release/lira-playground # Or with a custom port PORT=3010 ./target/release/lira-playground ``` -------------------------------- ### Basic Test Usage Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/test.md Example of importing the test module and executing a simple test case with a summary. ```lira import std.test test("my test", assert_eq(2 + 2, 4)) summary(1, 1, 0) // total, passed, failed ``` -------------------------------- ### Start Lira Debug Adapter Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Commands to launch the debug adapter using stdio or a specific TCP port. ```bash # Start debug adapter li-dap # Options li-dap --stdio li-dap --port 9998 ``` -------------------------------- ### Lira code formatting transformation Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Example showing code before and after applying the Lira formatter. ```li fn calculate(x:int,y:int)->int{ let result=x+y return result} ``` ```li fn calculate(x: int, y: int) -> int { let result = x + y return result } ``` -------------------------------- ### StringMutex Usage Source: https://github.com/helgesverre/lira/blob/main/docs/04-concurrency.md Example of using a StringMutex with the with helper. ```li let name = new_string_mutex("") name.with(|s: string| s + "!") ``` -------------------------------- ### Configure Neovim for Lira Source: https://github.com/helgesverre/lira/blob/main/crates/lira-lsp/README.md Setup configuration for the Lira LSP using nvim-lspconfig. ```lua -- lua/lspconfig.lua local lspconfig = require('lspconfig') local configs = require('lspconfig.configs') configs.lira = { default_config = { cmd = { 'lira-lsp' }, filetypes = { 'lira' }, root_dir = lspconfig.util.root_pattern('*.li', '.git'), }, } lspconfig.lira.setup{} ``` -------------------------------- ### Verify LSP installation Source: https://github.com/helgesverre/lira/blob/main/editors/zed-lira/README.md Commands to check if the language server binary is accessible and correctly versioned. ```bash which lira-lsp lira-lsp --version ``` -------------------------------- ### Help Data Format Example Source: https://github.com/helgesverre/lira/blob/main/docs/60-lira-repl.md Structured TOML format used for storing help documentation entries. ```toml # help/keywords/fn.toml [keyword] name = "fn" category = "declaration" brief = "Function Declaration" description = """ Declares a named function with typed parameters and return type. """ [syntax] grammar = "fn name(param: Type, ...) -> ReturnType { body }" [[examples]] code = """ fn add(a: int, b: int) -> int { return a + b } """ description = "Simple function with return value" [see_also] keywords = ["return", "closure"] ``` -------------------------------- ### Initialize Lira Application Entry Point Source: https://github.com/helgesverre/lira/blob/main/docs/20-liui-format.md Sets up the main application loop and loads the primary UI file. ```li // src/main.li import gui.core.App import gui.window.Window fn main() { let app = App.new("MyApp") // Load and run Lira UI file let window = Window.fromLiui("ui/main.liui") window.show() app.run() } ``` -------------------------------- ### Host-Mode Command Line Usage Source: https://github.com/helgesverre/lira/blob/main/docs/51-testing.md Examples of running the Lira VM in host mode with various configuration flags for filesystems, events, and headless execution. ```bash # Run application in host mode liravm --host app.lic # Run with mock filesystem initialized from directory liravm --host --mock-fs ./test-data app.lic # Run with event file (pre-recorded input events) liravm --host --events events.json app.lic # Run headless (no window creation) liravm --host --headless app.lic # Run with mock time starting at specific timestamp liravm --host --mock-time "2024-01-01T00:00:00Z" app.lic # Combine options liravm --host --headless --mock-fs ./fixtures app.lic ``` -------------------------------- ### get Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/http.md Performs a simple GET request and returns the response body. ```APIDOC ## fn get(url: string) -> string ### Description Simple GET request that returns just the body (or empty string on error). ### Parameters - **url** (string) - Required - The URL to request. ### Returns - **string** - The response body. ``` -------------------------------- ### Lira Language Server Startup Source: https://github.com/helgesverre/lira/blob/main/README.md Command to initialize the Lira language server via standard I/O. ```bash lira-lsp # Start LSP server (stdio) ``` -------------------------------- ### Implement Setup and Teardown Hooks Source: https://github.com/helgesverre/lira/blob/main/docs/51-testing.md Use lifecycle attributes to manage test environment state before and after individual tests or entire modules. ```li import testing mod database_tests { var db: Database? /// Called before each test in this module #[before_each] fn setup() { db = Database.in_memory() db!.execute("CREATE TABLE users (id INT, name TEXT)") } /// Called after each test in this module #[after_each] fn teardown() { db!.close() db = null } /// Called once before all tests in this module #[before_all] fn global_setup() { // Initialize test environment } /// Called once after all tests in this module #[after_all] fn global_teardown() { // Cleanup test environment } #[test] fn test_insert() { db!.execute("INSERT INTO users VALUES (1, 'Alice')") let count = db!.query_one("SELECT COUNT(*) FROM users") assert_eq(count, 1) } } ``` -------------------------------- ### Run Hello World Source: https://github.com/helgesverre/lira/blob/main/lira-playground/frontend/specs/playground-core.md Standard output test using the println function. ```lira println("Hello, World!") ``` -------------------------------- ### Basic Lira REPL usage Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Start the interactive REPL, run scripts, or evaluate single expressions. ```bash # Start interactive REPL lir # Run a file lir run script.li # Evaluate expression lir eval "1 + 2 * 3" ``` -------------------------------- ### Install query files Source: https://github.com/helgesverre/lira/blob/main/editors/helix-lira/README.md Commands to copy Lira query files into the Helix runtime directory. ```bash # Create query directory mkdir -p ~/.config/helix/runtime/queries/lira # Copy query files cp runtime/queries/lira/*.scm ~/.config/helix/runtime/queries/lira/ ``` -------------------------------- ### Check command usage Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Options and examples for verifying Lira code without compilation. ```bash lirac check [OPTIONS] [FILES...] OPTIONS: --all-targets Check all targets (lib, bin, tests, examples) --tests Check test files --lib Check library only EXAMPLES: # Check entire project lirac check # Check including tests lirac check --tests ``` -------------------------------- ### Identifier Examples and Constraints Source: https://github.com/helgesverre/lira/blob/main/docs/01-lexical-structure.md Examples of valid and invalid identifier declarations in Lira. ```li // Valid identifiers let foo = 1 let _private = 2 let camelCase = 3 let PascalCase = 4 let snake_case = 5 let with123numbers = 6 let _ = ignored // Discard binding // Invalid identifiers // let 123abc = 1 // Cannot start with digit // let my-var = 2 // Hyphens not allowed // let my var = 3 // Spaces not allowed ``` -------------------------------- ### lifmt command reference Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Summary of available command-line options and usage examples for the Lira formatter. ```text lifmt - Lira Formatter USAGE: lifmt [OPTIONS] [FILES...] OPTIONS: -h, --help Print help information -w, --write Write changes to files --check Check if files are formatted --diff Show diff of changes --config Use custom config file --stdin Read from stdin --stdin-filepath Path to use for stdin EXAMPLES: lifmt src/main.li # Print formatted output lifmt -w src/ # Format all files in src/ lifmt --check . # Check all files lifmt --diff src/main.li # Show diff ``` -------------------------------- ### Tokenization Example Source: https://github.com/helgesverre/lira/blob/main/docs/01-lexical-structure.md Input source code and the resulting token stream produced by the lexer. ```li let x = 42 + 3.14 ``` ```text [ Token(LET, "let", line=1, col=1), Token(IDENTIFIER, "x", line=1, col=5), Token(EQUALS, "=", line=1, col=7), Token(INTEGER, "42", line=1, col=9), Token(PLUS, "+", line=1, col=12), Token(FLOAT, "3.14", line=1, col=14), Token(EOF, "", line=1, col=18) ] ``` -------------------------------- ### Configure package manifest Source: https://github.com/helgesverre/lira/blob/main/docs/00-lira-overview.md Example of a li.toml configuration file for project dependencies and build settings. ```toml [package] name = "my_app" version = "1.0.0" entry = "src/main.li" [dependencies] std = "1.0" gui = "1.0" [build] optimization = "release" debug_info = true ``` -------------------------------- ### Project initialization commands Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Commands for scaffolding new Lira projects and libraries. ```bash # Create new project in current directory lirac init # Create new project in new directory lirac new my_app # Create library project lirac new my_lib --lib # Create GUI application lirac new my_gui --template gui ``` -------------------------------- ### Install vim-lira with Plugin Managers Source: https://github.com/helgesverre/lira/blob/main/editors/vim-lira/README.md Add the plugin to your Vim configuration using popular plugin managers. ```vim Plug 'lira-lang/vim-lira' ``` ```vim Plugin 'lira-lang/vim-lira' ``` -------------------------------- ### Current REPL Behavior Example Source: https://github.com/helgesverre/lira/blob/main/docs/60-lira-repl.md Demonstrates the current limitation where variables do not persist between input lines. ```text $ lira repl Lira REPL v0.1.0 Type :quit to exit, :help for help > let a = 3 > a Error: 2:1: Undefined variable: a // Variables don't persist! ``` -------------------------------- ### Accessing Keyword Help in REPL Source: https://github.com/helgesverre/lira/blob/main/docs/60-lira-repl.md Use the :help command followed by a keyword to view its declaration syntax and usage examples. ```text >>> :help fn fn - Function Declaration Declares a named function with typed parameters and return type. Syntax: fn name(param: Type, ...) -> ReturnType { body } Examples: fn add(a: int, b: int) -> int { return a + b } fn greet(name: string) { println("Hello, " + name) } See also: return, closure ``` -------------------------------- ### Boolean Literal Grammar and Examples Source: https://github.com/helgesverre/lira/blob/main/docs/01-lexical-structure.md Syntax for boolean literals and basic assignment examples. ```ebnf BooleanLiteral ::= 'true' | 'false' ``` ```li let active = true let disabled = false ``` -------------------------------- ### Layout Property Values Source: https://github.com/helgesverre/lira/blob/main/docs/21-liui-widgets.md Examples of valid values for size, flex, and alignment properties. ```liui // Size values width: 100 // Pixels width: "50%" // Percentage of parent width: "auto" // Automatic width: "fit-content" // Fit to content // Flex values flex: 1 // Grow factor flex: "1 0 auto" // grow shrink basis // Alignment values align: "start" // start, center, end, stretch justify: "space-between" // start, center, end, space-between, space-around, space-evenly ``` -------------------------------- ### Method Resolution Example Source: https://github.com/helgesverre/lira/blob/main/docs/03-syntax-constructs.md Demonstrates priority between inherent methods and trait methods. ```li impl Foo { fn bar(self) { print("inherent") } } trait T { fn bar(self) } impl T for Foo { fn bar(self) { print("trait") } } let f = Foo {} f.bar() // Prints "inherent" (inherent methods have priority) T.bar(f) // Prints "trait" (explicit trait method call) ``` -------------------------------- ### Character Literal Examples Source: https://github.com/helgesverre/lira/blob/main/docs/01-lexical-structure.md Examples of character literals using standard and Unicode escape sequences. ```li let a = 'A' let newline = '\n' let tab = '\t' let quote = '\'' let backslash = '\\' let emoji = '\u{1F600}' // Emoji let null_char = '\0' ``` -------------------------------- ### Build the Lira Plugin from Source Source: https://github.com/helgesverre/lira/blob/main/editors/intellij-lira/README.md Use these commands to build the plugin locally from the project directory. ```bash cd editors/intellij-lira ./gradlew buildPlugin # Plugin will be in build/distributions/ ``` -------------------------------- ### Playwright E2E Test Examples Source: https://github.com/helgesverre/lira/blob/main/lira-playground/README.md Examples demonstrating how to interact with the UI and debug state using Playwright. ```typescript import { test, expect } from '@playwright/test'; test('run program and check output', async ({ page }) => { await page.goto('/'); // Click run button await page.click('[data-testid="run-button"]'); // Wait for output await expect(page.locator('[data-testid="output-console"]')) .toContainText('Hello, World!'); // Check status await expect(page.locator('[data-testid="status-indicator"]')) .toHaveAttribute('data-status', 'finished'); }); test('debug with breakpoint', async ({ page }) => { await page.goto('/'); // Set breakpoint via store await page.evaluate(() => { (window as any).__EDITOR_STORE__.getState().toggleBreakpoint(2); }); // Run - should pause at breakpoint await page.click('[data-testid="run-button"]'); // Wait for continue button to be enabled await page.waitForFunction(() => { const btn = document.querySelector('[data-testid="debug-continue"]'); return btn && !btn.disabled; }); // Continue execution await page.click('[data-testid="debug-continue"]'); }); ``` -------------------------------- ### Accessing Type Help in REPL Source: https://github.com/helgesverre/lira/blob/main/docs/60-lira-repl.md Use the :help command followed by a type name to view its methods and usage examples. ```text >>> :help string string - String Type An immutable sequence of UTF-8 characters. Methods: len() -> int Length in characters is_empty() -> bool Check if empty contains(s: string) -> bool starts_with(s: string) -> bool ends_with(s: string) -> bool to_upper() -> string to_lower() -> string trim() -> string split(sep: string) -> [string] ... Examples: let s = "Hello, World!" println(s.len()) // 13 println(s.to_upper()) // "HELLO, WORLD!" See also: char, std.strings ``` -------------------------------- ### Implement MPMC Pattern Source: https://github.com/helgesverre/lira/blob/main/docs/04-concurrency.md Example of using multiple producers and consumers with buffered channels. ```li let work = Channel.buffered(100) let results = Channel.buffered(100) // Multiple producers for i in 0..3 { spawn { for task in get_tasks() { work.send(task) } } } // Multiple consumers for i in 0..5 { spawn { for task in work { let result = process(task) results.send(result) } } } ``` -------------------------------- ### SELECT Instruction Source: https://github.com/helgesverre/lira/blob/main/docs/11-instruction-set.md Waits on multiple channels and executes the first ready case. ```text Opcode: 0xDE Operands: case_count: u8 cases: [ op: u8 (0=recv, 1=send) target_offset: i16 ][case_count] default_offset: i16 (0 if no default) Stack: ( channels... values... -- index result_or_null ) Effect: Wait on multiple channels, execute ready case ``` -------------------------------- ### Floating-Point Literal Examples Source: https://github.com/helgesverre/lira/blob/main/docs/01-lexical-structure.md Examples of floating-point literals, including scientific notation, underscores, and type suffixes. ```li // Basic decimals let a = 3.14159 let b = 0.5 let c = 10.0 // Scientific notation let d = 6.022e23 // 6.022 × 10^23 let e = 1.6e-19 // 1.6 × 10^-19 let f = 1E10 // 1 × 10^10 // With underscores let g = 1_234.567_890 // With type suffix let h = 3.14f32 // float32 let i = 2.718f64 // float64 // Integer with float suffix let j = 42f64 // 42.0 as float64 ``` -------------------------------- ### Function Call Debugging Example Source: https://github.com/helgesverre/lira/blob/main/lira-playground/frontend/specs/playground-debug.md Sample code used to demonstrate stepping operations like Step Into and Step Over. ```text fn double(n: int) -> int { return n * 2 } let x = double(5) println(x) ``` -------------------------------- ### HTTP GET Request Functions Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/http.md Functions for performing GET requests, with variations for handling response status codes. ```lira fn get(url: string) -> string ``` ```lira fn get_ok(url: string) -> string ``` -------------------------------- ### Example Coverage Report Output Source: https://github.com/helgesverre/lira/blob/main/docs/51-testing.md Sample output showing detailed file-level coverage statistics and identified uncovered lines. ```text $ lirac test --coverage --summary Code Coverage Report ==================== File Lines Covered Percent ──────────────────────────────────────────────────────── src/lib.li 150 142 94.7% src/parser/lexer.li 320 298 93.1% src/parser/parser.li 450 387 86.0% src/vm/executor.li 280 195 69.6% src/vm/gc.li 120 89 74.2% src/gui/widgets/button.li 85 82 96.5% src/gui/widgets/label.li 45 45 100.0% ──────────────────────────────────────────────────────── Total 1450 1238 85.4% Uncovered lines: src/vm/executor.li:142-148 - Error handling branch src/vm/executor.li:201-210 - Rare opcode path src/vm/gc.li:89-95 - Cycle detection edge case ``` -------------------------------- ### Define System Tests Source: https://github.com/helgesverre/lira/blob/main/docs/51-testing.md Examples of system tests for window management and filesystem persistence using the testing framework. ```li // tests/system/full_app_test.li import testing #[test(system)] fn test_window_creation() { // This runs in system test mode let window = Window.new( title: "System Test", width: 640, height: 480, ) assert(window.is_visible()) // Draw something window.fill_rect(Rect { x: 10, y: 10, width: 100, height: 100 }, Color.RED) window.present() // Wait for vsync window.wait_vsync() window.close() } #[test(system)] fn test_file_persistence() { // Write to real filesystem let file = File.create("/tmp/test_output.txt").unwrap() file.write_string("Hello from system test!") file.close() // Read back let content = File.read_string("/tmp/test_output.txt").unwrap() assert_eq(content, "Hello from system test!") // Cleanup File.delete("/tmp/test_output.txt") } ``` -------------------------------- ### get_second Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/time.md Get the second from a timestamp. ```APIDOC ## fn get_second(timestamp_ms: int) -> int ### Description Get second from timestamp (0-59). ### Parameters - **timestamp_ms** (int) - The timestamp to extract the second from. ### Returns - **int** - The second (0-59). ``` -------------------------------- ### Get URL path and query Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/url.md Retrieves the path, query, and fragment components from a URL struct. ```lira fn url_path_query(url: URL) -> string ``` -------------------------------- ### Integrate Rustyline for REPL input Source: https://github.com/helgesverre/lira/blob/main/docs/60-lira-repl.md Setup for the interactive loop using Rustyline, including history loading and saving. ```rust use rustyline::{Editor, Result}; use rustyline::error::ReadlineError; fn repl() -> Result<()> { let mut rl = Editor::<()>::new()?; rl.load_history(".lira_history").ok(); let mut state = ReplState::new(); loop { let prompt = if state.continuation { "... " } else { ">>> " }; match rl.readline(prompt) { Ok(line) => { rl.add_history_entry(&line); // Process line... } Err(ReadlineError::Interrupted) => { println!("^C"); state.cancel_continuation(); } Err(ReadlineError::Eof) => break, Err(err) => { eprintln!("Error: {:?}", err); break; } } } rl.save_history(".lira_history")?; Ok(()) } ``` -------------------------------- ### Use documentation comments Source: https://github.com/helgesverre/lira/blob/main/docs/01-lexical-structure.md Examples of using line-based and block-based documentation comments for functions and structures. ```li /// Calculates the factorial of a number. /// /// # Arguments /// * `n` - The input number (must be non-negative) /// /// # Returns /// The factorial of `n` /// /// # Examples /// ``` /// let result = factorial(5) /// assert(result == 120) /// ``` fn factorial(n: int) -> int { if n <= 1 { return 1 } return n * factorial(n - 1) } /** * Represents a 2D point. * * @field x The x-coordinate * @field y The y-coordinate */ struct Point { x: float y: float } ``` -------------------------------- ### get_minute Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/time.md Get the minute from a timestamp. ```APIDOC ## fn get_minute(timestamp_ms: int) -> int ### Description Get minute from timestamp (0-59). ### Parameters - **timestamp_ms** (int) - The timestamp to extract the minute from. ### Returns - **int** - The minute (0-59). ``` -------------------------------- ### Build and install Tree-sitter grammar Source: https://github.com/helgesverre/lira/blob/main/editors/helix-lira/README.md Steps to generate and build the Lira tree-sitter grammar for use within Helix. ```bash # From the lira repository root cd editors/tree-sitter-lira npm install npx tree-sitter generate # Build the grammar for Helix hx --grammar fetch hx --grammar build ``` -------------------------------- ### get_hour Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/time.md Get the hour from a timestamp. ```APIDOC ## fn get_hour(timestamp_ms: int) -> int ### Description Get hour from timestamp (0-23). ### Parameters - **timestamp_ms** (int) - The timestamp to extract the hour from. ### Returns - **int** - The hour (0-23). ``` -------------------------------- ### Create Channels Source: https://github.com/helgesverre/lira/blob/main/docs/04-concurrency.md Demonstrates initializing unbuffered, buffered, and typed channels. ```li // Unbuffered channel (rendezvous) let ch = Channel.new() // Buffered channel let ch = Channel.buffered(10) // Buffer size 10 // Typed channel let messages: Channel = Channel.new() ``` -------------------------------- ### get_day Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/time.md Get the day from a timestamp. ```APIDOC ## fn get_day(timestamp_ms: int) -> int ### Description Get day from timestamp (1-31). ### Parameters - **timestamp_ms** (int) - The timestamp to extract the day from. ### Returns - **int** - The day (1-31). ``` -------------------------------- ### Running Lira Tests Source: https://github.com/helgesverre/lira/blob/main/docs/51-testing.md Example output from the lirac test command showing test execution results and failures. ```text $ lirac test Running tests in my_project Compiling my_project v0.1.0 Running tests/math_test.li running 6 tests test math_tests::test_add ... ok test math_tests::test_multiply ... ok test math_tests::edge_cases::test_add_zero ... ok test math_tests::edge_cases::test_add_negative ... ok test string_tests::test_concat ... ok test string_tests::test_split ... FAILED failures: ---- string_tests::test_split ---- thread 'test' panicked at 'assertion failed: `(left == right)` left: `["a", "b", "c"]`, right: `["a", "b"]`', tests/string_test.li:15:5 failures: string_tests::test_split test result: FAILED. 5 passed; 1 failed; 0 ignored; 0 measured error: test failed ``` -------------------------------- ### Breakpoint in Loop Example Source: https://github.com/helgesverre/lira/blob/main/lira-playground/frontend/specs/playground-debug.md Demonstrates setting a breakpoint within a loop to observe variable updates across iterations. ```text let nums = [0, 1, 2] for i in nums { println(i) } ``` -------------------------------- ### get_month Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/time.md Get the month from a timestamp. ```APIDOC ## fn get_month(timestamp_ms: int) -> int ### Description Get month from timestamp (1-12). ### Parameters - **timestamp_ms** (int) - The timestamp to extract the month from. ### Returns - **int** - The month (1-12). ``` -------------------------------- ### get_year Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/time.md Get the year from a timestamp. ```APIDOC ## fn get_year(timestamp_ms: int) -> int ### Description Get year from timestamp. ### Parameters - **timestamp_ms** (int) - The timestamp to extract the year from. ### Returns - **int** - The year. ``` -------------------------------- ### Lira UI Counter Component Example Source: https://github.com/helgesverre/lira/blob/main/docs/20-liui-format.md A basic counter component demonstrating imports, layout containers, data binding, and event handling. ```liui // ui/counter.liui import state from "../src/counter_state.li" Window { title: "Counter" width: 300 height: 200 VBox { spacing: 16 padding: 24 align: "center" Label { text: ${"Count: " + state.count} style: { fontSize: 24 fontWeight: "bold" } } HBox { spacing: 8 Button { text: "-" onClick: () => state.count -= 1 } Button { text: "+" primary: true onClick: () => state.count += 1 } } } } ``` -------------------------------- ### Import and Instantiate Lira UI Widgets Source: https://github.com/helgesverre/lira/blob/main/docs/21-liui-widgets.md Demonstrates the direct usage of widgets and the optional explicit import syntax. ```liui // Direct usage VBox { Label { text: "Hello" } Button { text: "Click" } } // Explicit import (optional) import { VBox, Label, Button } from "liui:widgets" ``` -------------------------------- ### trim_start Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/strings.md Trims whitespace from the start of a string. ```APIDOC ## fn trim_start(s: string) -> string ### Description Trim whitespace from start. ### Parameters - **s** (string) - The string to trim. ``` -------------------------------- ### starts_with Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/strings.md Checks if a string starts with a prefix. ```APIDOC ## fn starts_with(s: string, prefix: string) -> bool ### Description Check if string starts with prefix. ### Parameters - **s** (string) - The source string. - **prefix** (string) - The prefix to check. ``` -------------------------------- ### Mocking Filesystem Operations with MockFS Source: https://github.com/helgesverre/lira/blob/main/docs/51-testing.md Use MockFS to simulate filesystem interactions. Ensure the mock is installed before performing file operations and removed afterward. ```li import testing.mock.MockFS #[test] fn test_file_read() { // Create mock filesystem let fs = MockFS.new() // Pre-populate with test data fs.write_file("/test.txt", "Hello, World!") fs.create_dir("/data") fs.write_file("/data/config.json", "{\"key\": \"value\"}") // Install mock (replaces syscalls for this test) testing.install_mock(fs) defer { testing.remove_mock(fs) } // Now std.fs operations use the mock let content = File.read_string("/test.txt") assert_eq(content, Ok("Hello, World!")) let files = Directory.list("/data") assert_eq(files.unwrap().len(), 1) } #[test] fn test_file_write() { let fs = MockFS.new() testing.install_mock(fs) defer { testing.remove_mock(fs) } // Write file let file = File.create("/output.txt").unwrap() file.write("Test output") file.close() // Verify using mock assert_eq(fs.read_file("/output.txt"), "Test output") } ``` -------------------------------- ### Create Objects Source: https://github.com/helgesverre/lira/blob/main/docs/03-syntax-constructs.md Instantiating classes and structs, including field shorthand syntax. ```li // Class instantiation let person = Person.new("Alice", 30) let person2 = Person { name: "Bob", age: 25, } // Struct instantiation let point = Point { x: 10.0, y: 20.0 } let point2 = Point.new(10.0, 20.0) // With field shorthand let x = 10.0 let y = 20.0 let point3 = Point { x, y } // Same as { x: x, y: y } ``` -------------------------------- ### char_code Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/strings.md Gets the character code at a specific index. ```APIDOC ## fn char_code(s: string, index: int) -> int ### Description Get character code at index. Returns -1 if index is out of bounds. ### Parameters - **s** (string) - The source string. - **index** (int) - The position of the character. ``` -------------------------------- ### query_get Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/url.md Get a query parameter value by key. ```APIDOC ## query_get(query: string, key: string) -> string ### Description Retrieve the value of a specific query parameter. ### Parameters - **query** (string) - The query string. - **key** (string) - The key to look up. ### Returns - (string) - The value associated with the key. ``` -------------------------------- ### STR_STARTS_WITH (0xC8) Source: https://github.com/helgesverre/lira/blob/main/docs/11-instruction-set.md Checks if a string starts with a specific prefix. ```text Opcode: 0xC8 Operands: None Stack: ( str prefix -- result:bool ) ``` -------------------------------- ### range Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/collections.md Generates a range of integers from start to end (exclusive). ```APIDOC ## fn range(start: int, end: int) -> [int] ### Description Generate a range [start, end). ### Parameters - **start** (int) - Required - Start value. - **end** (int) - Required - End value (exclusive). ### Returns - **[int]** - The generated range. ``` -------------------------------- ### slice Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/collections.md Returns a slice of the array from start to end (exclusive). ```APIDOC ## fn slice(arr: [int], start: int, end: int) -> [int] ### Description Slice array from start to end (exclusive). ### Parameters - **arr** ([int]) - Required - The input array. - **start** (int) - Required - Start index. - **end** (int) - Required - End index (exclusive). ### Returns - **[int]** - The sliced array. ``` -------------------------------- ### GET /ws Source: https://github.com/helgesverre/lira/blob/main/lira-playground/README.md WebSocket endpoint for real-time debugging of Lira programs. ```APIDOC ## GET /ws ### Description WebSocket endpoint for real-time debugging. ### Method GET ### Endpoint /ws ### Client Messages - **debug**: Start debug session with source and breakpoints - **continue**: Continue execution to next breakpoint - **stepInto**: Step into function call - **stepOver**: Step over function call - **stepOut**: Step out of current function - **stepLine**: Step to next source line - **stepInstruction**: Step single bytecode instruction - **pause**: Pause running execution - **stop**: Stop debug session - **setBreakpoints**: Update breakpoint locations ### Server Messages - **compileSuccess**: Compilation succeeded, includes AST - **compileError**: Compilation failed with errors - **breakpointHit**: Execution paused at breakpoint - **stepCompleted**: Step operation completed - **output**: Program output line - **finished**: Execution completed - **runtimeError**: Runtime error occurred - **vmStateUpdate**: Debug state update (locals, stack) - **fiberEvent**: Fiber lifecycle event (spawn, state change) - **timeoutWarning**: Execution approaching timeout ``` -------------------------------- ### Profile Lira execution Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Run the virtual machine with profiling enabled to analyze function execution time. ```bash # Run with profiler liravm --profile app.lic # Output: # Total time: 1.234s # Functions: # process_data 45.2% 0.557s # parse_input 32.1% 0.396s # main 12.3% 0.152s # ... ``` -------------------------------- ### GET /health Source: https://github.com/helgesverre/lira/blob/main/lira-playground/README.md Health check endpoint to verify if the server is running. ```APIDOC ## GET /health ### Description Health check endpoint. Returns OK if the server is running. ### Method GET ### Endpoint /health ``` -------------------------------- ### Get UUID Version Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/uuid.md Extracts the version integer from a UUID string. ```lira fn version(uuid: string) -> int ``` -------------------------------- ### Lira Virtual Machine command reference Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Overview of available options for the liravm executable. ```text liravm - Lira Virtual Machine USAGE: liravm [OPTIONS] [-- ARGS...] OPTIONS: -h, --help Print help information -V, --version Print version information --debug Enable debug mode --trace Trace execution --profile Enable profiling --heap-size Set heap size (e.g., 256M) --stack-size Set stack size (e.g., 1M) EXAMPLES: liravm app.lic liravm --heap-size 512M app.lic liravm --debug app.lic ``` -------------------------------- ### Get query parameter Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/url.md Retrieves the value of a query parameter by its key. ```lira fn query_get(query: string, key: string) -> string ``` -------------------------------- ### Get URL substring Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/url.md Wrapper for str_substring to extract a portion of a string. ```lira fn url_substring(s: string, start: int, end: int) -> string ``` -------------------------------- ### get_ok Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/http.md Performs a GET request and returns the body only if the status is 2xx. ```APIDOC ## fn get_ok(url: string) -> string ### Description GET request that only returns body if status is 2xx, empty string otherwise. ### Parameters - **url** (string) - Required - The URL to request. ### Returns - **string** - The response body or an empty string. ``` -------------------------------- ### Hello World in Lira Source: https://github.com/helgesverre/lira/blob/main/README.md A basic entry point function for a Lira program. ```lira // hello.li fn main() { println("Hello, Lira!") } ``` -------------------------------- ### Get current user Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/env.md Retrieves the username of the current system user. ```lira fn user() -> string ``` -------------------------------- ### Manual Build and Execution Source: https://github.com/helgesverre/lira/blob/main/README.md Commands to build and run Lira components using cargo directly instead of the just runner. ```bash # Build cargo build --package lirac --package liravm # Compile a file cargo run --package lirac -- compile examples/hello.li -o /tmp/hello.lic # Run bytecode cargo run --package liravm -- run /tmp/hello.lic # Run tests cargo test --workspace ``` -------------------------------- ### Use multi-line comments Source: https://github.com/helgesverre/lira/blob/main/docs/01-lexical-structure.md Example of a decorated multi-line comment block. ```li /* * Multi-line comment * with asterisk decoration */ fn example() { } ``` -------------------------------- ### Use single-line comments Source: https://github.com/helgesverre/lira/blob/main/docs/01-lexical-structure.md Examples of standard and inline single-line comments. ```li // This is a single-line comment let x = 42 // Inline comment ``` -------------------------------- ### Configure Emacs for Lira Source: https://github.com/helgesverre/lira/blob/main/docs/50-tooling.md Basic mode requirement and LSP hook configuration for init.el. ```elisp ;; init.el (require 'li-mode) (add-hook 'li-mode-hook 'lsp) ``` -------------------------------- ### Parse range from expression Source: https://github.com/helgesverre/lira/blob/main/editors/tree-sitter-lira/test/corpus/expressions.txt Represents a range starting from a specific integer. ```lira 5.. ``` ```sexp (source_file (range_expression start: (integer_literal))) ``` -------------------------------- ### Implement Tooltips Source: https://github.com/helgesverre/lira/blob/main/docs/21-liui-widgets.md Demonstrates basic text tooltips and rich content tooltips with custom positioning and triggers. ```liui Tooltip { content: "This is a helpful tooltip" // Position position: "top" // top, bottom, left, right // Delay showDelay: 500 // ms hideDelay: 100 // Trigger trigger: "hover" // hover, click, focus // Wrapped element Button { text: "Hover me" } } // Rich tooltip Tooltip { position: "bottom" content: { VBox { Label { text: "Title", fontWeight: "bold" } Label { text: "Description text" } } } IconButton { icon: "info" } } ``` -------------------------------- ### Get current timestamp Source: https://github.com/helgesverre/lira/blob/main/docs/stdlib/io.md Returns the current system time in milliseconds as an integer. ```lira fn now_ms() -> int ```