### Build and Run Ace Editor Example Source: https://github.com/rune-rs/rune/blob/main/examples/ace/README.md Use these commands to build the Ace editor example with Rune CLI and serve it locally. ```sh cargo run -p rune-cli -- ace --output . python -m http.server ``` -------------------------------- ### Running all binaries and examples in a workspace Source: https://github.com/rune-rs/rune/blob/main/book/src/workspaces.md Execute `rune run` in the workspace root to build and run all default and named binaries, as well as examples, from all packages within the workspace. ```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 Big Match Example Source: https://github.com/rune-rs/rune/blob/main/book/src/pattern_matching.md Demonstrates a comprehensive example of pattern matching with various data types and structures in Rune. ```rune fn main() { let data = vec![1, 2, 42]; let data2 = vec!["one", "two", "three"]; let data3 = vec![1, 2, 42]; let data4 = vec!["hello", "world"]; match data { [1] => println!("The number one."), [1, 2, x] => println!("Another number: {}.", x), [1, 2, ..] => println!("A vector starting with one and two, followed by 42."), _ => println!("Something else."), } match data2 { ["one", "two", ..] => println!("One, but this time as a string."), _ => println!("Something else. Can I go eat now?"), } match data3 { [1, 2, x] => println!("Another number: {}.", x), _ => println!("Something else."), } match data4 { ["hello", "world"] => println!("Hello world."), _ => println!("Something else. Can I go eat now?"), } } ``` -------------------------------- ### Rune Project Directory Structure Source: https://context7.com/rune-rs/rune/llms.txt Example directory structure for a Rune package, including source files, tests, benchmarks, and examples. ```text package-a/ ├── src/ │ ├── main.rn # default binary (rune run) │ ├── lib.rn # default library │ └── bin/ │ └── server.rn # named binary (rune run --bin server) ├── tests/ │ └── smoke.rn ├── benches/ │ └── perf.rn └── examples/ └── demo.rn ``` -------------------------------- ### Build the Rune Book Source: https://github.com/rune-rs/rune/blob/main/book/README.md Installs mdbook and builds the book. Use this to generate the documentation locally. ```bash cargo install mdbook mdbook build --open ``` -------------------------------- ### Rune 'Hello World' Example Source: https://github.com/rune-rs/rune/blob/main/book/src/getting_started.md A basic 'Hello World' program in Rune, demonstrating the fundamental syntax for printing output. ```rune println!("Hello World"); ``` -------------------------------- ### Rust println! macro example Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2020-10-19-tmir1.md Demonstrates basic string formatting using the println! macro in Rust. ```rust println!("Hello {:>12}", "World"); ``` -------------------------------- ### Build rune-wasm Source: https://github.com/rune-rs/rune/blob/main/site/README.md Navigate to the rune-wasm directory and install dependencies, then build the project. This is a prerequisite for serving the site. ```bash cd crates/rune-wasm npm i npm run build ``` -------------------------------- ### Rune Fast Cars Example Source: https://github.com/rune-rs/rune/blob/main/book/src/pattern_matching.md An example showcasing pattern matching with object destructuring and binding in Rune. ```rune struct Car { make: String, model: String, year: u32, } fn main() { let car = Car { make: "Ford".to_string(), model: "Mustang".to_string(), year: 1969, }; match car { Car { model, year } if year > 1960 => { println!("This {} is pretty fast!", model); } Car { model, .. } => { println!("Can't tell 😞"); } _ => { println!("What, where did you get that?"); } } } ``` -------------------------------- ### Hot Reloading Example with PathReloader Source: https://github.com/rune-rs/rune/blob/main/book/src/hot_reloading.md This example demonstrates how to set up hot reloading for Rune scripts by watching a directory for changes using `PathReloader`. It recompiles the script when modifications are detected. ```rust use rune::runtime::ContextError; use rune::Context; use rune::Module; use rune::Source; use std::collections::HashMap; use std::path::Path; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; mod path_reloader; use path_reloader::PathReloader; #[derive(Default)] struct App { context: Context, unit: rune::runtime::Unit, vars: HashMap, } impl App { fn compile(&mut self, path: &Path) -> Result<(), ContextError> { let mut context = Context::new(); context.install(Module::with_item("std")?) .install(Module::with_item("mod")?) .install(Module::with_item("io")?) .install(Module::with_item("time")?); let mut source = Source::from_path(path)?; let unit = context.compile(source)?; self.context = context; self.unit = unit; Ok(()) } fn call(&self, name: &str, args: &[rune::runtime::Value]) -> Result { let mut scope = rune::runtime::Scope::new(); for (name, value) in &self.vars { scope.insert(name, value.clone()); } let output = self.context.call(&self.unit, name, args, scope)?; Ok(output) } } fn main() -> Result<(), Box> { let path = Path::new("examples/examples/hot_reloading.rune"); let reloader = PathReloader::new(path)?; let app = Arc::new(Mutex::new(App::default())); let handle = thread::spawn(move || { let mut last_hash = None; loop { match reloader.poll(last_hash) { Ok(Some(hash)) => { println!("Script changed, recompiling..."); let mut app = app.lock().unwrap(); if let Err(e) = app.compile(path) { eprintln!("Compilation error: {}", e); } else { last_hash = Some(hash); println!("Recompiled successfully."); } } Ok(None) => (), // No change Err(e) => { eprintln!("Error polling file: {}", e); break; } } thread::sleep(Duration::from_millis(100)); } }); // Give the reloader thread time to compile the initial script. thread::sleep(Duration::from_millis(500)); loop { let mut app = app.lock().unwrap(); match app.call("main", &[]) { Ok(value) => { println!("Output: {}", value); } Err(e) => { eprintln!("Runtime error: {}", e); } } thread::sleep(Duration::from_secs(1)); } // #[allow(unreachable_code)] // handle.join().unwrap(); // Ok(()) } ``` -------------------------------- ### Run Rune Script with Diagnostics in Rust Source: https://github.com/rune-rs/rune/blob/main/README.md Execute a Rune script from Rust, demonstrating how to integrate rich diagnostics using `termcolor`. This example includes context setup, source loading, compilation, error reporting, and VM execution. ```rust use rune::{Context, Diagnostics, Source, Sources, Vm}; use rune::termcolor::{ColorChoice, StandardStream}; use rune::sync::Arc; let context = Context::with_default_modules()?; let mut sources = Sources::new(); sources.insert(Source::memory("pub fn add(a, b) { a + b }")?); let mut diagnostics = Diagnostics::new(); let result = rune::prepare(&mut sources) .with_context(&context) .with_diagnostics(&mut diagnostics) .build_vm(); if !diagnostics.is_empty() { let mut writer = StandardStream::stderr(ColorChoice::Always); diagnostics.emit(&mut writer, &sources)?; } let mut vm = result?; let output = vm.call(["add"], (10i64, 20i64))?; let output: i64 = rune::from_value(output)?; println!("{}", output); ``` -------------------------------- ### Rune Code Formatting Example Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2023-10-10-rune-0.13.0.md Illustrates the output of `rune fmt` showing code changes between two versions of a file. ```diff == scripts\arrays.rn ++ scripts\async.rn 5 let timeout = time::sleep(time::Duration::from_secs(2)); 6 7 let result = select { 8 - _ = timeout => Err(Timeout ), + _ = timeout => Err(Timeout), 9 res = request => res, 10 }?; 11 ``` -------------------------------- ### Basic Stream Example in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/streams.md Demonstrates the basic usage of a stream in Rune. Requires `.await` for stream operations. ```rune use rune::Context; fn main() { let mut context = Context::new(); let mut stream = context.stream( "async fn stream() -> u8 { yield 200; yield 200; }" ); let mut iter = stream.iter(); while let Some(value) = iter.next().await { println!("{}", value); } } ``` ```text $> cargo run -- run scripts/book/streams/basic_stream.rn 200 OK 200 OK ``` -------------------------------- ### Install cargo-profile Source: https://github.com/rune-rs/rune/blob/main/benches/README.md Install the `cargo-profile` tool, which is necessary for generating flamegraphs. This tool extends `cargo`'s capabilities for profiling. ```sh cargo install cargo-profile ``` -------------------------------- ### Use HTTP and JSON Modules in Rune Source: https://context7.com/rune-rs/rune/llms.txt Example of making an HTTP GET request and a POST request with a JSON body using the `http` and `json` modules within a Rune script. ```rune // HTTP + JSON module usage in Rune use http; use json; pub async fn main() { let client = http::Client::new(); // GET request let response = client.get("https://httpstat.us/200").send().await; println!("status: {}", response.status()); // POST JSON body let body = json::to_bytes(#{"key": "value", "number": 42})?; let response = client.post("https://postman-echo.com/post") .body_bytes(body) .send() .await; let parsed = json::from_string(response.text().await?)?; dbg!(parsed["json"]); } ``` -------------------------------- ### Rune FizzBuzz Example Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2023-10-10-rune-0.13.0.md Demonstrates a basic FizzBuzz implementation in Rune, showcasing loops, modulo operations, and pattern matching. ```rune fn fizzbuzz(up) { for n in 1..=up { match (n % 3, n % 5) { (0, 0) => yield "FizzBuzz", (0, _) => yield "Fizz", (_, 0) => yield "Buzz", _ => yield n, } } } pub fn main() { fizzbuzz(15).iter().collect::() } ``` -------------------------------- ### Run Rune in Script Mode Source: https://github.com/rune-rs/rune/blob/main/book/src/scripts.md Example demonstrating how to run Rune in script mode. Ensure `Options::script` is set and arguments are provided via `Prepare::with_args`. ```rust use rune::Options; use rune::Build; fn main() -> rune::Result<()> { let mut context = rune::Context::new(); let mut options = Options::new(); options.set_script(true); let mut build = Build::with_context(context)?; build.with_options(options)?; build.with_args(vec![ "hello", "world" ])?; let rune = build.build()?; let output = rune.get_output()?; println!("{}", output); Ok(()) } ``` -------------------------------- ### Rune while loop example Source: https://github.com/rune-rs/rune/blob/main/book/src/loops.md Demonstrates the usage of a while loop in Rune. This loop continues as long as the condition is true. ```rune let mut count = 0; while count < 50 { count += 1; } println!("The value is {}", count); ``` -------------------------------- ### Define and Use a User Database Struct Source: https://github.com/rune-rs/rune/blob/main/book/src/structs.md Demonstrates defining a struct for a user database and implementing associated functions to manage user activity. This example shows how to create, update, and check user statuses. ```rune use std::collections::HashMap; struct UserDatabase { users: HashMap, } impl UserDatabase { fn new() -> Self { Self { users: HashMap::new(), } } fn add_user(&mut self, name: &str) { self.users.insert(name.to_string(), true); } fn set_active(&mut self, name: &str, active: bool) { if let Some(user) = self.users.get_mut(name) { *user = active; } } fn is_active(&self, name: &str) -> bool { self.users.get(name).copied().unwrap_or(false) } } fn main() { let mut db = UserDatabase::new(); db.add_user("setbac"); db.add_user("newt"); println!("setbac is {}", if db.is_active("setbac") { "active" } else { "inactive" }); db.set_active("setbac", false); println!("setbac is {}", if db.is_active("setbac") { "active" } else { "inactive" }); } ``` -------------------------------- ### Example Test File Structure Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2020-12-07-faster-tests.md Define your test files within a 'tests' directory. Each file should be a valid Rust module that can be discovered and included by the `build.rs` script. ```toml [[test]] name = "test" path = "test.rs" ``` -------------------------------- ### Tuple Masquerade Example in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/tuples.md Demonstrates how tuples can be used to represent changing states or sequences. This example shows two different tuple states printed to the console. ```rune fn main() { let tuple = ("Now", "You", "See", "Me"); println!("{:?}", tuple); let tuple = ("Now", "You", "Don't", "!"); println!("{:?}", tuple); } ``` -------------------------------- ### Using Rune Objects from Rust Source: https://github.com/rune-rs/rune/blob/main/book/src/objects.md Shows how to create and interact with Rune objects from Rust code. This example demonstrates accessing object fields and handling optional values. ```rust use rune::runtime::Object; fn main() { let mut obj: Object = Object::new(); obj.insert("hello".into(), 42.into()); let value = obj.get("hello"); println!("{:?}", value); let value = obj.get("world"); println!("{:?}", value); } ``` -------------------------------- ### Rune Playground Example Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2020-10-19-tmir1.md A basic Rune program demonstrating variable declaration and printing to the console. This snippet is runnable in the Rune playground. ```rune const NAME = "Friend"; pub fn main() { println!("Hello, {}", NAME); } ``` -------------------------------- ### Loading modules from filesystem in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/items_imports.md Modules can be loaded from separate files. This example shows the main file importing modules defined in `./foo/mod.rn` and `./bar.rn`. ```rune mod foo; mod bar; fn main() { println("{}", foo::bar()); } ``` -------------------------------- ### Using Tuples from Rust Source: https://github.com/rune-rs/rune/blob/main/book/src/tuples.md Demonstrates the usage of tuples in Rust, specifically how they are represented and can be used in a program. This example shows a simple tuple creation and printing. ```rust fn main() { let tup = (2, 3.2); let (x, y) = tup; println!("The value of y is: {}", y); } ``` -------------------------------- ### Sample Rune Workspace Directory Structure Source: https://github.com/rune-rs/rune/blob/main/book/src/workspaces.md This outlines a common directory structure for a Rune workspace, including a root manifest and nested packages with their respective source, test, example, and benchmark directories. ```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 Ignore Pattern Example Source: https://github.com/rune-rs/rune/blob/main/book/src/pattern_matching.md Shows how to use the ignore pattern (`_`) in Rune to skip values during pattern matching. ```rune fn main() { let data = vec![1, 2, 3]; match data { [_, x, _] => println!("Second item in vector is {}.", x), _ => println!("Vector does not have 3 elements."), } } ``` -------------------------------- ### Basic ACE Editor Setup for Rune Source: https://github.com/rune-rs/rune/blob/main/examples/ace/index.html Initializes an ACE editor instance, sets the theme to 'monokai', and configures the session mode to 'rune'. Enables basic and live autocompletion. ```javascript var editor = ace.edit("editor"); editor.setTheme("ace/theme/monokai"); editor.getSession().setMode("ace/mode/rune"); editor.setOptions({ enableBasicAutocompletion: true, enableLiveAutocompletion: true }); ``` -------------------------------- ### Rune infinite loop example Source: https://github.com/rune-rs/rune/blob/main/book/src/loops.md Shows an example of an infinite `loop` in Rune. This loop will run indefinitely unless explicitly terminated by a control flow operator like `break` or `return`. It uses `sleep` to prevent excessive terminal output. ```rune use std::time::Duration; loop { println!("Hello forever!"); sleep(Duration::from_secs(1)); } ``` -------------------------------- ### Rune: Generator Function Example Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2020-10-19-common-miscompilation.md Illustrates a simple generator function `foo` containing a `yield` statement, called by the `main` function. This example highlights the need for a distinct indexing phase to identify generators. ```rune fn foo() { yield 42; } pub fn main() { foo() } ``` -------------------------------- ### Build highlight.js Fork Source: https://github.com/rune-rs/rune/blob/main/book/README.md Installs npm dependencies and builds the custom highlight.js fork. This is used to add Rune syntax highlighting support. ```bash npm install node tools/build.js -h :common ``` -------------------------------- ### Define and Use a Struct in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/dynamic_types.md Example of defining a struct with fields and then instantiating it to print a greeting. This demonstrates basic dynamic type definition and usage in Rune. ```rune struct Person { name: String, greeting: String, } impl Person { fn new(name: String, greeting: String) -> Self { Self { name, greeting } } fn greet(&self) -> String { format!("{}, and good luck with this section!", self.greeting, self.name) } } fn main() { let p = Person::new("John-John Tedro".to_string(), "Greetings from".to_string()); println!("{}", p.greet()); } ``` ```text $> cargo run -- run scripts/book/dynamic_types/greeting.rn Greetings from John-John Tedro, and good luck with this section! ``` -------------------------------- ### Checking all entry points in a workspace Source: https://github.com/rune-rs/rune/blob/main/book/src/workspaces.md Run `rune check` from the workspace root to validate all defined binaries, libraries, tests, examples, and benchmarks across all packages. ```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: ... ... ``` -------------------------------- ### Compile Rune Source into VM with `rune::prepare` Source: https://context7.com/rune-rs/rune/llms.txt Compiles Rune source code into a VM unit. Handles context setup, diagnostics, and produces either a bare Unit or a ready-to-use Vm. Ensure diagnostics are checked before proceeding. ```rust use rune::termcolor::{ColorChoice, StandardStream}; use rune::{Context, Diagnostics, Source, Sources, Vm}; use rune::sync::Arc; fn main() -> rune::support::Result<()> { // Build a context with all standard library modules let context = Context::with_default_modules()?; let runtime = Arc::try_new(context.runtime()?)?; // Inline source via the sources! macro let mut sources = rune::sources! { entry => { pub fn add(a, b) { a + b } } }; let mut diagnostics = Diagnostics::new(); let result = rune::prepare(&mut sources) .with_context(&context) .with_diagnostics(&mut diagnostics) .build(); // produces Arc if !diagnostics.is_empty() { let mut writer = StandardStream::stderr(ColorChoice::Always); diagnostics.emit(&mut writer, &sources)?; } let unit = Arc::try_new(result?)?; let mut vm = Vm::new(runtime, unit); // Call a Rune function by path and pass Rust values as arguments let output = vm.call(["add"], (10i64, 20i64))?; let output: i64 = rune::from_value(output)?; println!("{output}"); // 30 Ok(()) } ``` -------------------------------- ### Add operation with trace and stack dump Source: https://github.com/rune-rs/rune/blob/main/book/src/the_stack.md This example demonstrates the 'add' instruction in Runestick. Use `--trace` and `--dump-stack` flags to observe the stack's state during execution. ```rune fn main() { let a = 1; let b = 3; return a + b; } ``` ```text $> 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* ``` -------------------------------- ### Rune Rest Pattern Example Source: https://github.com/rune-rs/rune/blob/main/book/src/pattern_matching.md Illustrates the use of the rest pattern (`..`) in Rune to match collections with potentially extra fields or values. ```rune fn main() { let data = vec![1, 2, 3, 4, 5]; match data { [1, 2, ..] => println!("Starts with 1, 2 and has more elements."), [.., 4, 5] => println!("Ends with 4, 5 and has more elements."), _ => println!("Other."), } } ``` -------------------------------- ### Basic Try Operator Usage with Option Source: https://github.com/rune-rs/rune/blob/main/book/src/try_operator.md Demonstrates how the try operator (?) causes a function to return early when encountering an Option::None variant. This example requires running the script with `cargo run -- run`. ```rune fn main() { let result = try_option(Some(1)); println!("Result: {}", result); let result = try_option(None); println!("Result: {}", result); } fn try_option(value: Option) -> i64 { let value = value?; value + 1 } ``` ```text $> cargo run -- run scripts/book/try_operator/basic_try.rn Result: 2, 1 ``` -------------------------------- ### Tuple Pattern Matching in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/tuples.md Shows how to use pattern matching to deconstruct tuples in Rune. This example extracts the first element of a tuple and prints a message based on its value. ```rune fn main() { let tuple = (1, "hello"); match tuple { (number, _) => { println!("the first part was a number:"); println!("{}", number); } } } ``` -------------------------------- ### Rune: Tuple with Two Closures Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2020-10-19-common-miscompilation.md Demonstrates a `main` function that defines and returns a tuple containing two distinct closures. This example shows how closures are compiled as unaddressable functions and introduces potential naming conflicts. ```rune pub fn main() { let a = || 1; let b = || 2; (a, b) } ``` -------------------------------- ### Pattern Match External Enum Variants in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/external_types.md Example of pattern matching on an external enum in Rune, demonstrating access to fields marked with `#[rune(get)]`. ```rune pub fn main(external) { match external { External::First(a) => a, External::Second(b) => b, } } ``` -------------------------------- ### Execute 'Hello World' Rune Script Source: https://github.com/rune-rs/rune/blob/main/book/src/getting_started.md Shows the command to run the 'Hello World' Rune script using `rune-cli` and its expected output. ```text $> cargo run -- run scripts/book/getting_started/hello_world.rn Hello World ``` -------------------------------- ### Example Execution Output Source: https://github.com/rune-rs/rune/blob/main/book/src/field_functions.md The expected output when running the `checked_add_assign` example, indicating a numerical overflow error. ```text $> cargo run --example checked_add_assign Error: numerical overflow (at inst 2) ``` -------------------------------- ### External Enum Pattern Matching with #[rune(get)] Source: https://github.com/rune-rs/rune/blob/main/book/src/external_types.md External enums can be pattern matched in Rune. Only fields annotated with `#[rune(get)]` are visible during pattern matching. ```rust enum External { First(#[rune(get)] u32, u32), Second(#[rune(get)] u32), } ``` -------------------------------- ### Run Rune Scripts with `rune-cli` Source: https://github.com/rune-rs/rune/blob/main/book/src/getting_started.md Demonstrates how to execute a Rune script from the command line using `cargo run -- run `. This is the standard way to run Rune programs. ```text $> cargo run -- run scripts/book/getting_started/dbg.rn [1, 2, 3] '今' dynamic function (at: 0x1a) native function (0x1bd03b8ee40) dynamic function (at: 0x17) ``` -------------------------------- ### Expose Field for Reading with #[rune(get)] Source: https://github.com/rune-rs/rune/blob/main/book/src/external_types.md Mark a field with `#[rune(get)]` to allow Rune scripts to read its value. This enables accessing fields like `external.value`. ```rust #[derive(Debug, Any)] struct External { #[rune(get)] value: u32, } ``` -------------------------------- ### External Enum with Struct Variant and #[rune(get)] Source: https://github.com/rune-rs/rune/blob/main/book/src/external_types.md Defines an external enum with a struct variant, exposing a specific field `c` for pattern matching using `#[rune(get)]`. ```rust enum External { First(#[rune(get)] u32, u32), Second(#[rune(get)] u32), Third { a: u32, b: u32, #[rune(get)] c: u32, }, } ``` -------------------------------- ### Calling Rune Functions from Rust Source: https://github.com/rune-rs/rune/blob/main/book/src/functions.md Demonstrates how to set up and invoke Rune functions from a Rust application using the Rune library. ```rust use rune::runtime::Vm; use rune::Context; fn main() { let mut context = Context::new(); context.install(rune::modules::default_modules()).unwrap(); let module = rune::load( "fn add(a, b) { a + b } fn main() { add(20, 23) } ").unwrap(); let value = Vm::new(context, module).execute().unwrap(); println!("output: {}", value); } ``` -------------------------------- ### Generator Boot-up Sequence Source: https://github.com/rune-rs/rune/blob/main/book/src/generators.md Shows the execution flow of a generator during its initial warm-up phase, before the first `yield` statement is reached. ```rune fn bootup() -> impl Generator { println!("firing off the printer..."); let name = yield "waiting for value..."; println!("ready to go!"); yield format!("Hello, {}!", name); } let mut printer = bootup(); // Resume to execute code before the first yield printer.resume(()).unwrap(); // Send a value and get the greeting let greeting = printer.resume("John").unwrap(); println!("{}", greeting); // Resume to get the next value printer.resume(()).unwrap(); ``` -------------------------------- ### Read External Type Field in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/external_types.md Demonstrates how to access a field marked with `#[rune(get)]` from a Rune script. ```rune pub fn main(external) { println!("{}", external.value); } ``` -------------------------------- ### Rune VM Stack State After Function Return Source: https://github.com/rune-rs/rune/blob/main/book/src/call_frames.md Demonstrates the Rune virtual machine's stack state after a function returns, showing how the stack is cleaned and the return value is integrated into the previous frame. ```text 1+0 = 1 1+1 = 2 1+2 = 3 0003 = clean 2 1+0 = 3 0004 = return <= frame 0 (0): 0+0 = 3 0+1 = 3 ``` -------------------------------- ### Construct External Enum Variant in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/external_types.md Example of constructing an enum variant marked with `#[rune(constructor)]` from a Rune script. ```rune pub fn main() { External::First(1, 2) } ``` -------------------------------- ### Modify External Type Field in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/external_types.md Shows how to modify a field marked with `#[rune(get, set)]` from a Rune script. ```rune pub fn main(external) { external.value = external.value + 1; } ``` -------------------------------- ### Rust Code for Custom Rune CLI Entry Point Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2023-10-10-rune-0.13.0.md Sets up the entry point for a custom Rune CLI, allowing for custom context configuration. ```rust const VERSION = "0.13.0"; fn main() { rune::cli::Entry::new() .about(format_args!("My Rune Project {VERSION}")) .context(&mut |opts| { Ok(my_project::setup_rune_context()?) }) .run(); } ``` -------------------------------- ### rune::prepare Source: https://context7.com/rune-rs/rune/llms.txt Compiles Rune source code into a VM-ready unit. It accepts sources, an optional context, and diagnostics collector, returning a builder for either a bare `Unit` or a `Vm`. ```APIDOC ## rune::prepare – Compile Rune source into a VM ### Description The central entry point for compiling Rune scripts from Rust. Accepts a mutable `Sources` handle, an optional `Context` (which carries all installed native modules), and an optional `Diagnostics` collector. Returns a builder that can produce either a bare `Unit` (compiled bytecode) or a ready-to-use `Vm`. ### Usage Example ```rust use rune::{Context, Diagnostics, Source, Sources, Vm}; use rune::termcolor::{ColorChoice, StandardStream}; use rune::sync::Arc; fn main() -> rune::support::Result<()> { // Build a context with all standard library modules let context = Context::with_default_modules()?; let runtime = Arc::try_new(context.runtime()?) ; // Inline source via the sources! macro let mut sources = rune::sources! { entry => { pub fn add(a, b) { a + b } } }; let mut diagnostics = Diagnostics::new(); let result = rune::prepare(&mut sources) .with_context(&context) .with_diagnostics(&mut diagnostics) .build(); // produces Arc if !diagnostics.is_empty() { let mut writer = StandardStream::stderr(ColorChoice::Always); diagnostics.emit(&mut writer, &sources)?; } let unit = Arc::try_new(result?)?; let mut vm = Vm::new(runtime, unit); // Call a Rune function by path and pass Rust values as arguments let output = vm.call(["add"], (10i64, 20i64))?; let output: i64 = rune::from_value(output)?; println!("{output}"); // 30 Ok(()) } ``` ``` -------------------------------- ### Coerce Operator Example Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2023-10-10-rune-0.13.0.md The coerce operator ` as ` is now supported in Rune 0.13.0, mirroring Rust's behavior for built-in types. ```rust 1u8 as f64 ``` -------------------------------- ### Rust Iterator Ambiguity Example Source: https://github.com/rune-rs/rune/blob/main/book/src/traits.md Illustrates a potential ambiguity in Rust if multiple traits with the same method name are implemented on a type, which Rune avoids. ```rust struct Foo { /* .. */ } impl Iterator for Foo { fn next(self) { /* .. */ } } impl OtherIterator for Foo { fn next(self) { /* .. */ } } let foo = Foo { /* .. */ }; // Which implementation of `next` should we call? while let Some(value) = foo.next() { } ``` -------------------------------- ### Rune's println! macro implementation Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2020-10-19-tmir1.md Shows how Rune implements the println! macro using FormatArgs and expands it to std::io::println. ```rust fn println_macro(stream: &TokenStream) -> Result { let mut p = Parser::from_token_stream(stream); let args = p.parse_all::()?; let expanded = args.expand()?; Ok(quote!(std::io::println(#expanded)).into_token_stream()) } ``` -------------------------------- ### Constant evaluation with greeting function Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2020-10-19-tmir1.md Example of constant evaluation in Rune, defining a const fn and a const array of greetings that can be computed at compile time. ```rune const fn greeting(name) { `Hello {name}` } /// Define a collection of predefined greetings. const GREETINGS = [ greeting("Stranger"), greeting("Jane"), greeting("John"), greeting("Mio"), ]; pub fn main() { let rng = rand::Pcg64::new(); let greetings = GREETINGS; println(greetings[rng.int_range(0, greetings.len())]); } ``` -------------------------------- ### Using Rust Vec in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/vectors.md Illustrates how to use a standard Rust `Vec` within Rune. The example shows a vector containing a single integer. ```rust use rune::runtime::Vec; fn main() { let mut vec = Vec::new(); vec.push(10); println!("{}", vec); } ``` -------------------------------- ### Basic Modules and Visibility in Rune Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2020-10-19-tmir1.md Demonstrates basic module structure, public and private items, and nested modules. Useful for understanding encapsulation in Rune. ```rune mod crate_helper_module { pub fn crate_helper() {} fn implementation_detail() {} } pub fn public_api() {} pub mod submodule { use crate::crate_helper_module; pub fn my_method() { crate_helper_module::crate_helper(); } fn my_implementation() {} mod test { fn test_my_implementation() { super::my_implementation(); } } } pub fn main() { submodule::my_method(); } ``` -------------------------------- ### Importing a function in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/items_imports.md Use a `use` statement to import items like functions from modules. This example imports the `range` function from `std::iter`. ```rune use std::iter::range; fn main() { for i in range(0..3) { println("{}", i); } } ``` -------------------------------- ### Run a Rune Script with rune-cli Source: https://github.com/rune-rs/rune/blob/main/crates/rune-cli/README.md Execute a Rune Language script using the `rune-cli` binary. This command is typically run from the project's root directory. ```text cargo run --bin rune -- scripts/hello_world.rn ``` -------------------------------- ### Run Rune Script with CLI Source: https://github.com/rune-rs/rune/blob/main/README.md Execute Rune programs using the bundled CLI. Use `--dump` and `--trace` flags for detailed diagnostics during execution. ```text cargo run --bin rune -- run scripts/hello_world.rn ``` ```text cargo run --bin rune -- run scripts/hello_world.rn --dump --trace ``` -------------------------------- ### Customizing Field Cloning with `clone_with` Source: https://github.com/rune-rs/rune/blob/main/book/src/field_functions.md Specifies a custom method (`Thing::clone`) to be used for cloning a field when `#[rune(get)]` is applied, using `clone_with`. ```rust use rune::Any; use rune::sync::Arc; #[derive(Any)] struct External { #[rune(get, clone_with = Thing::clone)] field: Thing, } #[derive(Any, Clone)] struct Thing { name: Arc, } ``` -------------------------------- ### Rune Workspace Configuration Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2023-10-10-rune-0.13.0.md Configure Rune CLI to locate sources across multiple submodules by defining a `Rune.toml` file with a `[workspace]` section specifying member directories. ```toml [workspace] members = [ "benches", "examples", ] ``` ```toml [package] name = "rune-benches" version = "0.0.0" ``` -------------------------------- ### Emit Instructions for Rune Closures Source: https://github.com/rune-rs/rune/blob/main/book/src/compiler_guide.md This command emits instructions and dumps functions for a Rune script containing closures. It demonstrates how closure calls are represented in the compiled output. ```rune {{#include ../../scripts/book/compiler_guide/closures.rn}} ``` ```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 ``` -------------------------------- ### Compile error for missing item in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/items_imports.md Attempting to use an item that does not exist will result in a compile-time error. This example shows an error for a non-existent `Foo::new`. ```rune fn main() { let foo = Foo::new(); } ``` -------------------------------- ### Basic Object Usage in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/objects.md Demonstrates the creation and access of key-value pairs within an anonymous object in a Rune script. Shows how to retrieve values and handle non-existent keys. ```rune let obj = { first: "bar", second: 42, }; println!("{:?}", obj.first); println!("{:?}", obj.second); println!("{:?}", obj.third); println!("{:?}", obj.into()) ``` -------------------------------- ### Rune's built-in template! and format! macros Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2020-10-19-tmir1.md Illustrates using Rune's internal template! and format! macros directly for string formatting, mimicking println! behavior. ```rust use std::io; pub fn main() { io::println(#[builtin] template! { "Hello ", #[builtin] format! { "World", width = 12, align = right } }); } ``` -------------------------------- ### Rune: Evaluation Order Explanation Source: https://github.com/rune-rs/rune/blob/main/site/content/posts/2020-10-19-common-miscompilation.md Provides a simplified representation of the evaluation order for the complex anonymous function assignment example. This clarifies the sequence of operations that can lead to miscompilations. ```text second[third] = first; ``` -------------------------------- ### Concurrent HTTP Requests with Async Functions and Await Source: https://github.com/rune-rs/rune/blob/main/book/src/async.md Shows how to perform concurrent HTTP requests using `async` functions and the `.await` keyword. This approach ensures that multiple I/O operations are handled in parallel, improving efficiency. ```rune use std::time::Duration; async fn fetch(url: &str) { let res = reqwest::get(url).await; match res { Ok(res) => { println!("Result: {} {}", res.status(), res.version()); } Err(e) => { eprintln!("Failed to fetch {}: {}", url, e); } } } fn main() { let request = fetch("http://httpbin.org/delay/3"); let timeout = async { tokio::time::sleep(Duration::from_secs(1)).await; println!("Request timed out!"); }; runtime::block_on(async { tokio::select! { _ = request => {}, _ = timeout => {}, } }); } ``` -------------------------------- ### Inline module definition in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/items_imports.md Define modules directly within a source file using the `mod` keyword. This example demonstrates an inline module with a simple calculation. ```rune mod foo { pub fn bar() -> i64 { 3 } } fn main() { println("{}", foo::bar()); } ``` -------------------------------- ### Call Dynamic Functions in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/compiler_guide.md Demonstrates how to call dynamic functions using their unique identifiers. This is useful for invoking functions that are not statically known at compile time. ```rune 0xbef6d5f6276cd45e = main::$0::$0() 0x1c69d5964e831fc1 = main() ``` -------------------------------- ### Expose Field for Reading and Writing with #[rune(set)] Source: https://github.com/rune-rs/rune/blob/main/book/src/external_types.md Mark a field with `#[rune(set)]` in addition to `#[rune(get)]` to allow Rune scripts to both read and modify its value. ```rust #[derive(Debug, Any)] struct External { #[rune(get, set)] value: u32, } ``` -------------------------------- ### Run Rune Script with Diagnostics Source: https://github.com/rune-rs/rune/blob/main/crates/rune/README.md Execute Rune programs with detailed diagnostics. Use the --dump and --trace flags for in-depth program analysis during execution. ```text cargo run --bin rune -- run scripts/hello_world.rn --dump --trace ``` -------------------------------- ### Using VecTuple for Non-Uniform Types in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/vectors.md Demonstrates the use of `VecTuple` in Rune to handle vectors with elements of different types. The example shows a tuple containing an integer and a string. ```rust use rune::runtime::VecTuple; fn main() { let mut vec = VecTuple::new(); vec.push(2); vec.push("Hello World"); println!("{}", vec); } ``` -------------------------------- ### Rune VM Stack State During Function Call Source: https://github.com/rune-rs/rune/blob/main/book/src/call_frames.md Illustrates the state of the Rune virtual machine's stack when a new call frame is created, showing how arguments are accessed within the new frame. ```text 0+0 = 3 0+1 = 1 0+2 = 2 0008 = call 0xbfd58656ec9a8ebe, 2 // fn `foo` => frame 1 (1): 1+0 = 1 1+1 = 2 ``` -------------------------------- ### Missing Instance Function Error in Rune Source: https://github.com/rune-rs/rune/blob/main/book/src/instance_functions.md This example shows the error message when an instance function is not found for a given type. The error includes type and function hashes for identification. ```rune fn main() { foo.bar(); } ``` -------------------------------- ### Rune Program with Function Call Source: https://github.com/rune-rs/rune/blob/main/book/src/call_frames.md This Rune program demonstrates a function call and its effect on the stack, including the creation of a new call frame. ```rune fn foo(a, b) { let a = a; let b = b; a + b } fn main() { let a = 3; let b = 1; let c = 2; foo(a, b) } ```