### Rune Workspace Manifest Example Source: https://rune-rs.github.io/book/print Provides an example of a `Rune.toml` manifest file for setting up a project workspace. It specifies the `members` which are directories containing other Rune packages. ```TOML [workspace] members = [ "package-a", "nested/package-b" ] ``` -------------------------------- ### Run Example Executing Rune Function from Rust Source: https://rune-rs.github.io/book/functions Shows the command to run an example that demonstrates calling a Rune function from Rust. This verifies the integration and execution flow between the two languages. ```bash $> cargo run --example minimal output: 43 ``` -------------------------------- ### Compiling and Running a Rune Script (Item Import Example) Source: https://rune-rs.github.io/book/items_imports Shows the command to compile and run a Rune script that demonstrates item imports, along with the expected output. ```bash > cargo run -- run scripts/book/items_imports/example_import.rn std::iter::Range ``` -------------------------------- ### Rune 'Hello World' Example Source: https://rune-rs.github.io/book/print A basic 'Hello World' program in Rune using the `println!` macro to output text to the console. This illustrates the simplest form of Rune script execution. ```rune __ println!("Hello World"); ``` -------------------------------- ### Running All Targets in a Rune Workspace Source: https://rune-rs.github.io/book/workspaces This command executes all available binaries and examples within the Rune workspace. It lists the targets being run, including their package origin. The output shows the default and named executables, as well as examples from different packages. ```shell rune run ``` -------------------------------- ### Rune Example: Custom Instance Function Execution Source: https://rune-rs.github.io/book/print This is an example of how to run the custom instance function example using cargo. It shows the expected output after executing the provided Rust code. ```Shell $> cargo run --example custom_instance_fn output: 11 ``` -------------------------------- ### Assemble Function Call in Rune Source: https://rune-rs.github.io/book/compiler_guide This example demonstrates how a closure is assembled and called in Rune. It shows the generated instructions for both the main function and the closure itself, illustrating the process of invoking a callable. ```rune let callable = || 42; dbg!(callable()); ``` ```text > cargo run -- run scripts/book/compiler_guide/closures.rn --emit-instructions --dump-functions # instructions fn main() (0x1c69d5964e831fc1): 0000 = load-fn hash=0xbef6d5f6276cd45e // closure `3` 0001 = copy offset=0 // var `callable` 0002 = call-fn args=0 0003 = pop 0004 = pop 0005 = return-unit fn main::$0::$0() (0xbef6d5f6276cd45e): 0006 = push value=42 0007 = return address=top, clean=0 ``` -------------------------------- ### Rune Tuple Example Source: https://rune-rs.github.io/book/print Demonstrates the usage of tuples in Rune, showing how they are represented and manipulated. It includes setting up the Rune context, compiling a script with a tuple function, and executing it within a virtual machine. ```rust use rune::sync::Arc; use rune::termcolor::{ColorChoice, StandardStream}; use rune::{Diagnostics, Vm}; fn main() -> rune::support::Result<()> { let context = rune_modules::default_context()?; let runtime = Arc::try_new(context.runtime()?)?; let mut sources = rune::sources! { entry => { pub fn calc(input) { (input.0 + 1, input.1 + 2) } } }; let mut diagnostics = Diagnostics::new(); let result = rune::prepare(&mut sources) .with_context(&context) .with_diagnostics(&mut diagnostics) .build(); if !diagnostics.is_empty() { let mut writer = StandardStream::stderr(ColorChoice::Always); diagnostics.emit(&mut writer, &sources)?; } let unit = result?; let unit = Arc::try_new(unit)?; let mut vm = Vm::new(runtime, unit); let output = vm.call(["calc"], ((1u32, 2u32),))?; let output: (i32, i32) = rune::from_value(output)?; println!("{output:?}"); Ok(()) } ``` -------------------------------- ### Rune Workspace Directory Structure Source: https://rune-rs.github.io/book/workspaces This example shows a standard Rune workspace layout. It includes a root `Rune.toml` for workspace configuration and nested packages (`package-a`, `package-b`) each with their own manifest and source code organized into `bin`, `lib`, `examples`, `tests`, and `benches` directories. This structure supports multi-file executables and libraries. ```text workspace ├── Rune.toml <-- Workspace manifest ├── package-a │   ├── Rune.toml <-- Package 'a' manifest │   ├── src │   │   ├── bin │   │   │   ├── multi-file-executable │   │   │   │   ├── main.rn │   │   │   │   └── module │   │   │   │   └── mod.rn │   │   │   └── named-executable.rn │   │   ├── lib.rn │   │   └── main.rn │   ├── benches │   │   ├── collatz.rn │   │   └── multi-file-bench │   │   ├── collatz.rn │   │   └── main.rn │   ├── examples │   │   ├── multi-file-example │   │   │   ├── lib.rn │   │   │   └── main.rn │   │   └── simple.rn │   └── tests │   ├── fire │   │   ├── lib.rn │   │   └── main.rn │   └── smoke.rn └── nested    └── package-b    ├── Rune.toml <-- Package 'b' manifest    ├── src    │   ├── bin    │   │   ├── multi-file-executable    │   │   │   ├── main.rn    │   │   │   └── module    │   │   │   └── mod.rn    │   │   └── named-executable.rn    │   ├── lib.rn    │   └── main.rn    ├── benches    │   ├── collatz.rn    │   └── multi-file-bench    │   ├── collatz.rn    │   └── main.rn    ├── examples    │   ├── multi-file-example    │   │   ├── lib.rn    │   │   └── main.rn    │   └── simple.rn    └── tests    ├── fire    │   ├── lib.rn    │   └── main.rn    └── smoke.rn ``` -------------------------------- ### Rune: Basic "Hello World" output Source: https://rune-rs.github.io/book/getting_started A simple "Hello World" program in Rune using the `println!` macro to output text to the standard output. This is a fundamental example for beginners. ```rune println!("Hello World"); ``` -------------------------------- ### Rune Script Execution Example Source: https://rune-rs.github.io/book/enums Shows the command to run a Rune script and its expected output. This example executes the `count_numbers.rn` script and displays the console output, illustrating the behavior of the `Option` enum. ```bash $> cargo run -- run scripts/book/enums/count_numbers.rn First count! Count: 0 Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Count: 6 Count: 7 Count: 8 Count: 9 Second count! Count: 0 Count: 1 ``` -------------------------------- ### Rune Function Hash Execution Example Source: https://rune-rs.github.io/book/print Shows the output of running the Rust example program that calculates function hashes. It prints two identical hexadecimal hashes, representing the deterministic hashes for the specified item path within Rune. ```bash $> cargo run --example function_hash 0xb5dc92ab43cb37d9 0xb5dc92ab43cb37d9 ``` -------------------------------- ### Run Rune Script with Main Function Source: https://rune-rs.github.io/book/functions Shows how to compile and run a Rune script that utilizes the 'main' function. This example demonstrates the command-line interface for executing Rune programs. ```bash $> cargo run -- run scripts/book/functions/main_function.rn Hello World ``` -------------------------------- ### Running All Targets with `rune run` Source: https://rune-rs.github.io/book/print Demonstrates the output of the `rune run` command when executed in the root of a Rune workspace. This command by default executes all available binaries and examples across all packages within the workspace, showing the entry point being run and its associated package. ```text __ Running bin `package-a/src/main.rn` (from a) Running bin `package-a/src/bin/named-executable.rn` (from a) Running bin `package-a/src/bin/multi-file-executable/main.rn` (from a) Running bin `nested/package-b/src/main.rn` (from b) Running bin `nested/package-b/src/bin/named-executable.rn` (from b) Running bin `nested/package-b/src/bin/multi-file-executable/main.rn` (from b) Running example `package-a/examples/simple.rn` (from a) Running example `package-a/examples/multi-file-example/main.rn` (from a) Running example `nested/package-b/examples/simple.rn` (from b) Running example `nested/package-b/examples/multi-file-example/main.rn` (from b) ... output from the various executables ``` -------------------------------- ### Rune Function Declaration (`fn`) Source: https://rune-rs.github.io/book/print Shows the basic syntax for declaring functions in Rune using the `fn` keyword. This example declares a public `main` function that prints 'Hello World' to the console. ```rune pub fn main() { println!("Hello World"); } ``` ```shell $> cargo run -- run scripts/book/functions/main_function.rn Hello World ``` -------------------------------- ### Rune Struct Example Source: https://rune-rs.github.io/book/print Demonstrates the definition and usage of structs in Rune, similar to objects with predefined structures. It covers creating a `User` struct, implementing instance functions like `set_active` and `describe` using `impl` blocks, and interacting with struct instances. ```rune struct User { username, active, } impl User { fn set_active(self, active) { self.active = active; } fn describe(self) { if self.active { println!("{} is active.", self.username); } else { println!("{} is inactive.", self.username); } } } let user = User { username: "setbac", active: false }; user.describe(); user.set_active(true); user.describe(); ``` -------------------------------- ### Call Rune Function from Rust Source: https://rune-rs.github.io/book/functions Provides an example of how to set up and call a Rune function from Rust code. It involves preparing the Rune context, compiling the script, and executing it within a virtual machine. ```rust use rune::sync::Arc; use rune::termcolor::{ColorChoice, StandardStream}; use rune::{Diagnostics, Vm}; fn main() -> rune::support::Result<()> { let context = rune_modules::default_context()?; let runtime = Arc::try_new(context.runtime()?) ; let mut sources = rune::sources!( entry => { pub fn main(number) { number + 10 } } ); let mut diagnostics = Diagnostics::new(); let result = rune::prepare(&mut sources) .with_context(&context) .with_diagnostics(&mut diagnostics) .build(); if !diagnostics.is_empty() { let mut writer = StandardStream::stderr(ColorChoice::Always); diagnostics.emit(&mut writer, &sources)?; } let unit = result?; let unit = Arc::try_new(unit)?; let mut vm = Vm::new(runtime, unit); let output = vm.execute(["main"], (33i64,))?.complete()?; let output: i64 = rune::from_value(output)?; println!("output: {output}"); Ok(()) } ``` -------------------------------- ### Rune Tuple Masquerade Example Source: https://rune-rs.github.io/book/print Illustrates how tuples in Rune can be modified in place, behaving like mutable structures for their elements. This example shows initial tuple creation, modification of elements by index, and printing the updated tuple. ```rune __ let values = ("Now", "You", "See", "Me"); dbg!(values); values.2 = "Don't"; values.3 = "!"; dbg!(values); ``` -------------------------------- ### Rune Pattern Matching: Basic Examples Source: https://rune-rs.github.io/book/pattern_matching Demonstrates basic pattern matching in Rune using literals, vectors, strings, and objects. It shows how to match on different data types and use a default case. ```rune fn match_input(n) { match n { 1 => println!("The number one."), n if n is i64 => println!("Another number: {}.", n), [1, 2, n, ..] => println!("A vector starting with one and two, followed by {}.", n), "one" => println!("One, but this time as a string."), _ => println!("Something else. Can I go eat now?"), } } match_input(1); match_input(2); match_input([1, 2, 42, 84]); match_input("one"); match_input(#{ field: 42 }); ``` -------------------------------- ### Rune VM Object Interaction Example Source: https://rune-rs.github.io/book/print Demonstrates how to interact with Rune's `Object` type using the Rune Virtual Machine (VM). It shows setting up the VM context, compiling a script that modifies an object, inserting data into an object, and retrieving modified data from the VM. ```rune __ use rune::alloc; use rune::runtime::Object; use rune::sync::Arc; use rune::termcolor::{ColorChoice, StandardStream}; use rune::{Diagnostics, Vm}; fn main() -> rune::support::Result<()> { let context = rune_modules::default_context()?; let runtime = Arc::try_new(context.runtime()?)?; let mut sources = rune::sources! { entry => { pub fn calc(input) { dbg(input["key"]); input["key"] = "World"; input } } }; let mut diagnostics = Diagnostics::new(); let result = rune::prepare(&mut sources) .with_context(&context) .with_diagnostics(&mut diagnostics) .build(); if !diagnostics.is_empty() { let mut writer = StandardStream::stderr(ColorChoice::Always); diagnostics.emit(&mut writer, &sources)?; } let unit = result?; let unit = Arc::try_new(unit)?; let mut vm = Vm::new(runtime, unit); let mut object = Object::new(); object.insert(alloc::String::try_from("key")?, rune::to_value(42i64)?)?; let output = vm.call(["calc"], (object,))?; let output: Object = rune::from_value(output)?; println!("{:?}", output.get("key")); Ok(()) } ``` -------------------------------- ### Rune: Running a script with cargo run Source: https://rune-rs.github.io/book/getting_started Shows how to execute a Rune script file using the `cargo run` command. This example specifically runs a script named `dbg.rn` and displays the output generated by the `dbg!` macro. ```bash $> cargo run -- run scripts/book/getting_started/dbg.rn [1, 2, 3] '今' dynamic function (at: 0x1a) native function (0x1bd03b8ee40) dynamic function (at: 0x17) ``` -------------------------------- ### Rune Generator Bootup Sequence Source: https://rune-rs.github.io/book/print Illustrates the initial execution phase of a Rune generator before the first `yield`. Calling `resume` once "warms up" the generator, executing code before the first suspension point. This example prints messages to show the order of execution and when the generator waits for input. ```rust fn printer() { loop { println!("waiting for value..."); let out = yield; println!("{out:?}"); } } let printer = printer(); println!("firing off the printer..."); printer.resume(()); println!("ready to go!"); printer.resume("John"); printer.resume((1, 2, 3)); ``` -------------------------------- ### Rune VM: Execute Addition Instruction Source: https://rune-rs.github.io/book/the_stack Demonstrates the execution of the 'add' instruction in the Rune virtual machine. It shows how integers are pushed onto the stack and then added together, with the result remaining on the stack. This example utilizes `--trace` and `--dump-stack` for detailed execution logging. ```rune 1 + 3 ``` ```bash $> cargo run -- run scripts/book/the_stack/add.rn --trace --dump-stack fn main() (0xe7fc1d6083100dcd): 0000 = integer 1 0+0 = 1 0001 = integer 3 0+0 = 1 0+1 = 3 0002 = add 0+0 = 4 0003 = return *empty* == 4 (7.7691ms) # stack dump after halting frame #0 (+0) *empty* ``` -------------------------------- ### Checking All Targets with `rune check` Source: https://rune-rs.github.io/book/print Illustrates the output of the `rune check` command, which provides a comprehensive list of all targets (binaries, libraries, tests, examples, benchmarks) that Rune detects within the workspace. This is useful for understanding the project's structure and entry points. ```text __ Checking bin `package-a/src/main.rn` (from a) Checking bin `package-a/src/bin/named-executable.rn` (from a) Checking bin `package-a/src/bin/multi-file-executable/main.rn` (from a) Checking bin `nested/package-b/src/main.rn` (from b) Checking bin `nested/package-b/src/bin/named-executable.rn` (from b) Checking bin `nested/package-b/src/bin/multi-file-executable/main.rn` (from b) Checking lib `package-a/src/lib.rn` (from a) Checking lib `nested/package-b/src/lib.rn` (from b) Checking test `package-a/tests/smoke.rn` (from a) Checking test `package-a/tests/fire/main.rn` (from a) Checking test `nested/package-b/tests/smoke.rn` (from b) Checking test `nested/package-b/tests/fire/main.rn` (from b) Checking example `package-a/examples/simple.rn` (from a) Checking example `package-a/examples/multi-file-example/main.rn` (from a) Checking example `nested/package-b/examples/simple.rn` (from b) Checking example `nested/package-b/examples/multi-file-example/main.rn` (from b) Checking bench `package-a/benches/collatz.rn` (from a) Checking bench `package-a/benches/multi-file-bench/main.rn` (from a) Checking bench `nested/package-b/benches/collatz.rn` (from b) Checking bench `nested/package-b/benches/multi-file-bench/main.rn` (from b) Checking: package-a/src/main.rn Checking: ... ... ``` -------------------------------- ### Running Rune Script for Type Checking Source: https://rune-rs.github.io/book/types Example command to execute a Rune script named 'types.rn' located in the 'scripts/book/types/' directory using the cargo run command. ```bash $> cargo run -- run scripts/book/types/types.rn ``` -------------------------------- ### Run Rune Script with Dynamic Return Type Source: https://rune-rs.github.io/book/functions Demonstrates executing a Rune script containing a function with a dynamic return type. This example highlights how Rune handles different return types at runtime. ```bash $> cargo run -- run scripts/book/functions/return_value.rn Hello 1 ``` -------------------------------- ### Rune - Running Basic Template Literal Example Source: https://rune-rs.github.io/book/template_literals Shows the command to compile and run a Rune script that uses a basic template literal. The output confirms the successful interpolation of the variable into the string. ```shell $> cargo run -- run scripts/book/template_literals/basic_template.rn ``` -------------------------------- ### Rune VM Tuple Operations Source: https://rune-rs.github.io/book/tuples An example of executing a Rune script within the Rune Virtual Machine (VM) that involves tuple operations. It demonstrates preparing sources, building a unit, and calling a function that manipulates a tuple. ```rust use rune::sync::Arc; use rune::termcolor::{ColorChoice, StandardStream}; use rune::{Diagnostics, Vm}; fn main() -> rune::support::Result<()> { let context = rune_modules::default_context()?; let runtime = Arc::try_new(context.runtime()?)?; let mut sources = rune::sources! { entry => { pub fn calc(input) { (input.0 + 1, input.1 + 2) } } }; let mut diagnostics = Diagnostics::new(); let result = rune::prepare(&mut sources) .with_context(&context) .with_diagnostics(&mut diagnostics) .build(); if !diagnostics.is_empty() { let mut writer = StandardStream::stderr(ColorChoice::Always); diagnostics.emit(&mut writer, &sources)?; } let unit = result?; let unit = Arc::try_new(unit)?; let mut vm = Vm::new(runtime, unit); let output = vm.call(["calc"], ((1u32, 2u32),))?; let output: (i32, i32) = rune::from_value(output)?; println!("{output:?}"); Ok(()) } ``` -------------------------------- ### Rune Tuple Pattern Matching Source: https://rune-rs.github.io/book/print Demonstrates pattern matching on tuples in Rune. The example shows a `match` expression that destructures a tuple and binds its elements to variables, allowing conditional logic based on tuple contents. ```rune __ match ("test", 1) { ("test", n) => { dbg!("the first part was a number:", n); } _ => { dbg!("matched something we did not understand"); } } ``` -------------------------------- ### Rune Struct Pattern Matching Source: https://rune-rs.github.io/book/print Shows how structs in Rune can be pattern matched, leveraging the compile-time knowledge of struct fields for safety. This example defines a `User` struct and implements a `describe` method that uses `match` to conditionally print output based on the `username` field. ```rune struct User { username, active, } impl User { fn describe(self) { match self { User { username: "setbac", .. } => { println!("Yep, it's setbac."); } User { username, .. } => { println!("Other user: {username}."); } } } } let user = User { username: "setbac", active: false }; user.describe(); user.username = "newt"; user.describe(); ``` -------------------------------- ### Async Closures for Futures in Rune Source: https://rune-rs.github.io/book/async Demonstrates the creation of futures using `async` closures in Rune. Calling an `async` closure produces a future that can be `.await`ed to get its result. ```rune fn do_request(url) { async || { Ok(http::get(url).await?.status()) } } let future = do_request("https://google.com"); let status = future().await?; println!("Status: {status}"); ``` -------------------------------- ### Rune Compiler: Dead Code Elimination Example Source: https://rune-rs.github.io/book/print Demonstrates how the Rune compiler performs dead code elimination by showing that the code for an uncalled local function (`bar`) is never generated. ```rune return foo(); fn foo() { 2 } fn bar() { 3 } ``` ```bash $> cargo run -- run scripts/book/compiler_guide/dead_code.rn --dump-functions --warnings # dynamic functions 0x0 = {root}() 0x481411c4bd0a5f6 = foo() --- ``` -------------------------------- ### Checking All Rune Targets in Workspace Source: https://rune-rs.github.io/book/workspaces This command checks the validity of all entry points within the Rune workspace, including binaries, libraries, tests, examples, and benches. The output lists each checked target, specifying its type, path, and originating package. This provides a comprehensive overview of all buildable and runnable components. ```shell rune check ``` -------------------------------- ### Concurrent HTTP Requests in Rune Source: https://rune-rs.github.io/book/async Demonstrates how to perform multiple HTTP GET requests concurrently using Rune's `select` block. It shows how to manage and process results from independent asynchronous operations. ```rune let a = http::get("https://google.com"); let b = http::get("https://amazon.com"); loop { let res = select { res = a => res?, res = b => res?, }; match res { () => break, result => { println!("{}", result.status()); } } } ``` -------------------------------- ### Rune VM: Integer Instruction Execution Source: https://rune-rs.github.io/book/the_stack Illustrates the execution of the 'integer' instruction in the Rune virtual machine. This instruction pushes an integer value onto the stack. The example shows the state of the stack after pushing the integer `1`. ```rune 0000 = integer 1 0+0 = 1 ``` -------------------------------- ### Rune Function Returning a Tuple Source: https://rune-rs.github.io/book/print A simple Rune function `foo` that returns a tuple containing an integer and a string. The example demonstrates function definition, tuple return type, and debugging the returned tuple. ```rune __ fn foo() { (1, "test") } dbg!(foo()); ``` -------------------------------- ### Load and Call Function Pointer (Rune) Source: https://rune-rs.github.io/book/compiler_guide Demonstrates loading a function pointer onto the stack using `load-fn`, copying it, and then invoking it with zero arguments. This is a fundamental operation for dynamic function execution in Rune. ```rune 0xbef6d5f6276cd45e = main::$0::$0() 0x1c69d5964e831fc1 = main() // A function pointer is pushed on the stack `load-fn 0xca35663d3c51a903`, // then copied and called with zero arguments. ``` -------------------------------- ### Rune Closure Compilation Output (Instructions) Source: https://rune-rs.github.io/book/print This output shows the compiled instructions for a Rune program that defines and calls a closure. It details the 'load-fn' operation to get the closure, copying it, and then calling it. The closure itself is compiled into a separate function. ```Assembly fn main() (0x1c69d5964e831fc1): 0000 = load-fn hash=0xbef6d5f6276cd45e // closure `3` 0001 = copy offset=0 // var `callable` 0002 = call-fn args=0 0003 = pop 0004 = pop 0005 = return-unit fn main::$0::$0() (0xbef6d5f6276cd45e): 0006 = push value=42 0007 = return address=top, clean=0 ``` -------------------------------- ### Rune VM Vector Sum Calculation Source: https://rune-rs.github.io/book/print Illustrates executing a Rune script within a Rust program to calculate the sum of elements in a vector. This example uses `rune::prepare` to compile the script and `Vm::call` to invoke a function, demonstrating interop between Rust and Rune. ```rust use rune::sync::Arc; use rune::termcolor::{ColorChoice, StandardStream}; use rune::{Diagnostics, Vm}; fn main() -> rune::support::Result<()> { let context = rune_modules::default_context()?; let runtime = Arc::try_new(context.runtime()?)?; let mut sources = rune::sources! { entry => { pub fn calc(input) { let output = 0; for value in input { output += value; } [output] } } }; let mut diagnostics = Diagnostics::new(); let result = rune::prepare(&mut sources) .with_context(&context) .with_diagnostics(&mut diagnostics) .build(); if !diagnostics.is_empty() { let mut writer = StandardStream::stderr(ColorChoice::Always); diagnostics.emit(&mut writer, &sources)?; } let unit = result?; let unit = Arc::try_new(unit)?; let mut vm = Vm::new(runtime, unit); let input = vec![1, 2, 3, 4]; let output = vm.call(["calc"], (input,))?; let output: Vec = rune::from_value(output)?; println!("{output:?}"); Ok(()) } ``` -------------------------------- ### Rune Template Literal Execution Example Source: https://rune-rs.github.io/book/print Shows the expected output when a Rune script using template literals is executed via 'cargo run'. This confirms the successful interpolation of the variable within the string. ```bash $> cargo run -- run scripts/book/template_literals/basic_template.rn "I am 30 years old!" ``` -------------------------------- ### Rune Generators for Fibonacci Sequence Source: https://rune-rs.github.io/book/print Shows how to implement generators in Rune to create efficient iterators. This example demonstrates building a Fibonacci number generator, where the generator function suspends its state between calls to `next()`. ```rune fn fib() { let a = 0; let b = 1; loop { yield a; let c = a + b; a = b; b = c; } } let g = fib(); while let Some(n) = g.next() { println!("{n}"); if n > 100 { break; } } ``` -------------------------------- ### Rune: Runtime Object Manipulation and Execution Source: https://rune-rs.github.io/book/objects Demonstrates how to use the Rune virtual machine to execute a script that manipulates an object. It shows the setup of the VM, context, and sources, then inserts a value into an object, calls a function within the VM to modify it, and retrieves the result. This highlights Rune's runtime capabilities and dynamic type handling. ```rune use rune::alloc; use rune::runtime::Object; use rune::sync::Arc; use rune::termcolor::{ColorChoice, StandardStream}; use rune::{Diagnostics, Vm}; fn main() -> rune::support::Result<()> { let context = rune_modules::default_context()?; let runtime = Arc::try_new(context.runtime()?)?; let mut sources = rune::sources! { entry => { pub fn calc(input) { dbg(input["key"]); input["key"] = "World"; input } } }; let mut diagnostics = Diagnostics::new(); let result = rune::prepare(&mut sources) .with_context(&context) .with_diagnostics(&mut diagnostics) .build(); if !diagnostics.is_empty() { let mut writer = StandardStream::stderr(ColorChoice::Always); diagnostics.emit(&mut writer, &sources)?; } let unit = result?; let unit = Arc::try_new(unit)?; let mut vm = Vm::new(runtime, unit); let mut object = Object::new(); object.insert(alloc::String::try_from("key")?, rune::to_value(42i64)?)?; let output = vm.call(["calc"], (object,))?; let output: Object = rune::from_value(output)?; println!("{:?}", output.get("key")); Ok(()) } ``` -------------------------------- ### Rune Pattern Matching with `match` statement Source: https://rune-rs.github.io/book/print Demonstrates various pattern matching scenarios in Rune using a `match` statement. It covers matching integers, type checks with guards, vector destructuring, string matching, and a default case. The examples show how to call the `match_input` function with different data types. ```rune fn match_input(n) { match n { 1 => println!("The number one."), n if n is i64 => println!("Another number: {}.", n), [1, 2, n, ..] => println!("A vector starting with one and two, followed by {}.", n), "one" => println!("One, but this time as a string."), _ => println!("Something else. Can I go eat now?"), } } match_input(1); match_input(2); match_input([1, 2, 42, 84]); match_input("one"); match_input(#{{ field: 42 }}); ``` -------------------------------- ### Implementing DISPLAY_FMT Protocol in Rune Source: https://rune-rs.github.io/book/print Provides an example of implementing the `DISPLAY_FMT` protocol for a custom struct `StatusCode` in Rune. This allows instances of `StatusCode` to be formatted within template strings. It involves defining a `display_fmt` method that writes to a `Formatter`. ```rust use rune::{ContextError, Module}; use rune::runtime::{Protocol, Formatter}; use std::fmt::Write as _; use std::fmt; #[derive(Debug)] pub struct StatusCode { inner: u32, } impl StatusCode { #[rune::function(protocol = DISPLAY_FMT)] fn display_fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", self.inner) } } pub fn module() -> Result { let mut module = Module::new(["http"]) module.function_meta(StatusCode::display_fmt)?; Ok(module) } ``` -------------------------------- ### Rune Dead Code Elimination Example Source: https://rune-rs.github.io/book/compiler_guide This example illustrates Rune's dead code elimination. It shows a script where a function `bar` is defined but never called, and consequently, its code is not generated by the compiler. The output demonstrates that only the called function `foo` has its code generated. ```rune return foo(); fn foo() { 2 } fn bar() { 3 } ``` ```text > cargo run -- run scripts/book/compiler_guide/dead_code.rn --dump-functions --warnings # dynamic functions 0x0 = {root}() 0x481411c4bd0a5f6 = foo() --- == 2 (59.8µs) ``` -------------------------------- ### Create Enum Instance Using Constructor Source: https://rune-rs.github.io/book/external_types Demonstrates creating an instance of the `External::First` enum variant using its generated constructor. This relies on the `#[rune(constructor)]` and `#[rune(get)]` annotations applied in the enum definition. ```rune pub fn main() { External::First(1, 2) } ``` -------------------------------- ### Inline Modules in Rune Source: https://rune-rs.github.io/book/print Demonstrates how to define modules directly within a Rune source file using the `mod` keyword. Each module can contain its own functions. This example shows the `foo` and `bar` modules and a `main` function that uses them. ```rune mod foo { pub fn number() { 1 } } mod bar { pub fn number() { 2 } } pub fn main() { dbg!(foo::number() + bar::number()); } ``` ```shell $> cargo run -- run scripts/book/items_imports/inline_modules.rn 3 ``` -------------------------------- ### Rune: Execute a Script Demonstrating Dynamic Types Source: https://rune-rs.github.io/book/dynamic_types This snippet shows the command-line execution of a Rune script that utilizes dynamic types, specifically the 'Person' struct example. It demonstrates how to run a Rune script using the cargo runtime. ```bash $> cargo run -- run scripts/book/dynamic_types/greeting.rn ``` -------------------------------- ### Rune VM: Calculate Sum of Vector Elements Source: https://rune-rs.github.io/book/vectors This example demonstrates using the Rune Virtual Machine (VM) to execute a script that calculates the sum of elements in a vector. It involves preparing Rune sources, building a unit, and calling a function within the VM. ```rune use rune::sync::Arc; use rune::termcolor::{ColorChoice, StandardStream}; use rune::{Diagnostics, Vm}; fn main() -> rune::support::Result<()> { let context = rune_modules::default_context()?; let runtime = Arc::try_new(context.runtime()?)?; let mut sources = rune::sources! { entry => { pub fn calc(input) { let output = 0; for value in input { output += value; } [output] } } }; let mut diagnostics = Diagnostics::new(); let result = rune::prepare(&mut sources) .with_context(&context) .with_diagnostics(&mut diagnostics) .build(); if !diagnostics.is_empty() { let mut writer = StandardStream::stderr(ColorChoice::Always); diagnostics.emit(&mut writer, &sources)?; } let unit = result?; let unit = Arc::try_new(unit)?; let mut vm = Vm::new(runtime, unit); let input = vec![1, 2, 3, 4]; let output = vm.call(["calc"], (input,))?; let output: Vec = rune::from_value(output)?; println!("{output:?}"); Ok(()) } ``` ```shell $> cargo run --example vector [10] ``` -------------------------------- ### Rune Dynamic Type Example Source: https://rune-rs.github.io/book/print Illustrates the use of dynamic types in Rune with a `Person` struct. It shows how to define a struct, implement methods on it, instantiate it, and call its methods. This is useful for structuring data and associating functions with it within Rune scripts. ```rune struct Person { name, } impl Person { fn greet(self) { println!("Greetings from {}, and good luck with this section!", self.name); } } let person = Person { name: "John-John Tedro" }; person.greet(); ``` -------------------------------- ### Rune Function with Dynamic Return Type Source: https://rune-rs.github.io/book/functions Illustrates Rune's dynamic typing by defining a function 'foo' that can return different types based on a condition. The example shows calling this function and printing its output. ```rune fn foo(condition) { if condition { "Hello" } else { 1 } } pub fn main() { println!("{}", foo(true)); println!("{}", foo(false)); } ``` -------------------------------- ### Function Returning a Tuple in Rune Source: https://rune-rs.github.io/book/tuples Illustrates how to define a function in Rune that returns a tuple. The example shows a function `foo` returning a tuple containing an integer and a string, and how to capture and print the returned tuple. ```rune fn foo() { (1, "test") } dbg!(foo()); ``` -------------------------------- ### Rune Enum Constructors and Field Annotations Source: https://rune-rs.github.io/book/print Demonstrates how to create enums with constructors in Rune using `#[rune(constructor)]`. It highlights the necessity of annotating fields with `#[rune(get)]` to allow constructor access and field visibility. ```rune enum External { #[rune(constructor)] First(#[rune(get)] u32, #[rune(get)] u32), #[rune(constructor)] Second(#[rune(get)] u32), Third { a: u32, b: u32, #[rune(get)] c: u32, }, } pub fn main() { External::First(1, 2) } ``` -------------------------------- ### Item Path Keywords (`self`, `crate`, `super`) in Rune Source: https://rune-rs.github.io/book/print Explains and demonstrates Rune's keywords for referencing items relative to the current module: `self` (current module root), `crate` (project entrypoint), and `super` (parent module). This example shows how `super::first::number()` is used. ```rune mod first { pub fn number() { crate::number() + 2 } } mod second { pub fn number() { super::first::number() + 4 } } pub fn number() { 1 } dbg!(self::second::number()); ``` ```shell $> cargo run -- run scripts/book/items_imports/item_keywords.rn 7 ``` -------------------------------- ### Read Struct Field in Rune (Rune Script) Source: https://rune-rs.github.io/book/print Illustrates how to access a readable field of an external struct within a Rune script. This example assumes the 'value' field has been exposed using `#[rune(get)]`. ```rune pub fn main(external) { println!("{}", external.value); } ``` -------------------------------- ### Define and Use Structs with Instance Functions in Rune Source: https://rune-rs.github.io/book/structs Demonstrates defining a `User` struct with `username` and `active` fields, and an `impl` block to associate instance functions `set_active` and `describe`. The `describe` function prints the user's status, and `set_active` modifies it. The example shows instantiation and calling these methods. ```rune struct User { username, active, } impl User { fn set_active(self, active) { self.active = active; } fn describe(self) { if self.active { println!("{} is active.", self.username); } else { println!("{} is inactive.", self.username); } } } let user = User { username: "setbac", active: false }; user.describe(); user.set_active(true); user.describe(); ``` ```bash $> cargo run -- run scripts/book/structs/user_database.rn setbac is inactive setbac is active ``` -------------------------------- ### Rune - Running Example with Non-Implemented Protocol Source: https://rune-rs.github.io/book/template_literals Shows the command to execute a Rune script that attempts to use a template literal with a type lacking the `DISPLAY_FMT` protocol. The output displays the specific runtime error encountered, indicating the missing protocol implementation. ```shell $> cargo run -- run scripts/book/template_literals/not_a_template.rn ``` -------------------------------- ### Expose Struct Field for Reading and Writing in Rune Source: https://rune-rs.github.io/book/external_types Demonstrates how to make a field of an external Rust struct both readable and writable from Rune using `#[rune(get, set)]`. The example shows modifying the field's value within Rune. ```rust #[derive(Debug, Any)] struct External { #[rune(get, set)] value: u32, } ``` ```rune pub fn main(external) { external.value = external.value + 1; } ``` -------------------------------- ### Send Values Into a Rune Generator Source: https://rune-rs.github.io/book/generators This example illustrates how to send values into a Rune generator using the `yield` keyword and the `resume()` method. The generator can receive external data, process it, and collect it. It also highlights that generators require an initial `resume()` call to start execution before they can receive subsequent values. ```rune fn printer() { let collected = []; for _ in 0..2 { let out = yield; println!("{:?}", out); collected.push(out); } assert_eq!(collected, ["John", (1, 2, 3)]); } let printer = printer(); printer.resume(()); printer.resume("John"); printer.resume((1, 2, 3)); ``` ```shell $> cargo run -- run scripts/book/generators/send_values.rn "John" (1, 2, 3) ``` -------------------------------- ### Rune: Example Usage of Derived Field Functions Source: https://rune-rs.github.io/book/field_functions This Rune code snippet shows how to interact with a Rust struct (`External`) that has field functions automatically generated via `#[rune(...)]` attributes. It demonstrates incrementing a numeric field and appending to a string field, reflecting the capabilities enabled by Rust's `#[rune(get, set, add_assign)]`. ```rune pub fn main(external) { external.number = external.number + 1; external.number += 1; external.string = `${external.string} World`; } ``` -------------------------------- ### Using the Rune stringy_math! Macro Source: https://rune-rs.github.io/book/print This Rust code shows how to invoke the `stringy_math!` macro. After importing the macro, it's called with a sequence of operations and arguments, demonstrating its ability to expand into a complex expression. This example assumes the `stringy_math` macro has been defined and registered. ```rust use ::test::macros::stringy_math; pub fn main() { stringy_math!(add 10 sub 2 div 3 mul 100) } ``` -------------------------------- ### Rune: Executing the "Hello World" script Source: https://rune-rs.github.io/book/getting_started Demonstrates how to compile and run a Rune script containing the "Hello World" program using `cargo run`. The output confirms that the "Hello World" message is printed to the console. ```bash $> cargo run -- run scripts/book/getting_started/hello_world.rn Hello World ```