### Doctest Example Source: https://github.com/iwj/rust-polyglot/blob/main/src/rustdoc.md Code examples within doc comments are automatically compiled and run as tests by `cargo test`. ```rust /// ``` /// let hello = String::from("Hello, world!"); /// ``` ``` -------------------------------- ### Rust Doc Comment Example Source: https://github.com/iwj/rust-polyglot/blob/main/src/rustdoc.md API documentation is written using `///` doc comments directly above the item being documented. ```rust /// pigpiod tick ([us]) pub type Tick = Word; ``` -------------------------------- ### Macro Invocation Syntax Examples Source: https://github.com/iwj/rust-polyglot/blob/main/src/macros.md Illustrates the different syntaxes for invoking function-like macros. The macro itself cannot distinguish between these invocation styles. ```Rust macro!(...) ``` ```Rust macro!{..} ``` ```Rust macro![..] ``` -------------------------------- ### Fancy-Pre Block Syntax Source: https://github.com/iwj/rust-polyglot/blob/main/fancy-pre.md This is the basic syntax for a fancy-pre block. It includes a start and end marker, with the content inside. ```markdown %!fancy-pre ``` content ``` %/fancy-pre ``` -------------------------------- ### Rust Attribute Syntax Source: https://github.com/iwj/rust-polyglot/blob/main/src/syntax.md Shows examples of Rust attributes, which are metadata attached to code items. Includes conditional compilation, must_use, allow, feature gates, test markers, inline hints, and memory layout control. ```rust #[cfg(..)] ``` ```rust #[must_use] ``` ```rust #[allow(dead_code)] ``` ```rust #![allow(dead_code)] ``` ```rust #![feature(exit_status_error)] ``` ```rust #[test] ``` ```rust #[inline] ``` ```rust #[repr(...)] ``` ```rust #[path="foo.rs"] mod bar; ``` ```rust #[derive(...)] ``` -------------------------------- ### Monomorphised Closure Argument Example Source: https://github.com/iwj/rust-polyglot/blob/main/src/traits.md Shows the signature for a generic function taking a closure that implements the `Fn` trait. ```Rust f: F where F: Fn() ``` -------------------------------- ### Doctest with Hidden Lines Source: https://github.com/iwj/rust-polyglot/blob/main/src/rustdoc.md Lines starting with `# ` in doctests are part of the test but are not included in the generated documentation. ```rust /// use std::fs::File; /// /// # if cfg!(unix) { /// let _ = File::open("/dev/null").unwrap(); /// # } ``` -------------------------------- ### Doctest with should_panic Annotation Source: https://github.com/iwj/rust-polyglot/blob/main/src/rustdoc.md The `should_panic` attribute can also be used within doctests to specify that the code example should panic. ```rust /// ```should_panic /// panic!(); /// ``` ``` -------------------------------- ### Variable Binding and Assignment Source: https://github.com/iwj/rust-polyglot/blob/main/src/syntax.md Illustrates different ways to introduce bindings using `let` and perform assignments. ```Rust let %pattern% = %value%; // Irrefutable patterns let %pattern% = %value% else { %diverges...% }; // Refutable (Rust 1.65, Nov 2022) %place% = %value%; // Assignment to a mutable variable or location %pattern% = %value%; // Destructuring assignment (Rust 1.59, Feb 2022) ``` -------------------------------- ### Derive Macro Syntax Source: https://github.com/iwj/rust-polyglot/blob/main/src/macros.md Illustrates the syntax for using derive macros and helper attributes on types or fields. ```Rust #[derive(macro)] ``` ```Rust #[derive] macros can define helper #[attributes] ``` -------------------------------- ### macro_rules! Pattern Matching Syntax Source: https://github.com/iwj/rust-polyglot/blob/main/src/macros.md Illustrates the syntax for pattern matching within macro_rules! macros, including binding variables and repetition constructs. ```Rust $binding:syntaxtype ``` ```Rust $( ... )? ``` ```Rust $( ... )* ``` ```Rust $( ... ),* ``` ```Rust $( ... )+ ``` ```Rust $( ... ),+ ``` -------------------------------- ### Rust Match Expression Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Illustrates the basic structure of a `match` expression in Rust for handling different patterns and conditions. ```rust match variable { pat1 => ..., pat2 if cond =>, ... } ``` -------------------------------- ### Nominal Type Literals in Rust Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Demonstrates various ways to construct literals for nominal types including structs, tuples, and enum variants. Shows abbreviated field initialization and explicit type specification. ```rust let _ = S { f: 42, g: "forty-two" }; let _ = ST(42, ()); let _ = Z0; let _ = Z1(); let _ = Z2{}; let _ = E::V0; let _ = E::V1(42); let _ = E::V2 { f: format!("hi") }; let _ = SG { f: 0u8, g: "type of F is inferred" }; let _ = SG:: { f: Default::default(), g: "type of F is specified" }; let f = 0u8; let _ = SG { g: "f is abbreviated", f }; ``` -------------------------------- ### Using macro_rules! Bindings in Replacement Source: https://github.com/iwj/rust-polyglot/blob/main/src/macros.md Shows how to use a bound variable from the template in the replacement part of a macro_rules! macro. ```Rust $binding ``` -------------------------------- ### Exporting a macro_rules! Macro Source: https://github.com/iwj/rust-polyglot/blob/main/src/macros.md Demonstrates how to make a macro available in other crates using the `#[macro_export]` attribute. ```Rust #[macro_export] ``` -------------------------------- ### Rust Expression-Based Control Flow Source: https://github.com/iwj/rust-polyglot/blob/main/src/syntax.md Illustrates Rust's expression-oriented control flow structures, including blocks, if/else, if let, match, loops, and closures. These constructs can return values, making them more flexible than traditional statements. ```rust { %stmt0%; %stmt1%; } // With semicolon, has type `()` { %stmt0%; %stmt1% } // No semicolon, has type of `%stmt1%` ``` ```rust if %condition% { %statements...% } // Can only have type `()` if %condition% { %value% } else { %other_value% } // No `? :`, use this ``` ```rust if let %pattern% = %value% { %...% } %[%else %...%%]% ``` ```rust match %value% { %pat0% %[% if %cond0% %]% => %expr0%, %...% } ``` ```rust '%label%: loop { ... } // %#.4:33mm `'%label%:` is optional of course '%label%: while %condition% { } '%label%: while let %pattern% = %expr% { } '%label%: for %loopvar% in %something_iterable% { ... } ``` ```rust return %v% // At end of function, it is idiomatic to just write `%v%` ``` ```rust break %value%; // `loop` only; specifies value of `loop` expr break '%label% %value%; // `break %value%` with named loop; Rust 1.65, Nov 2022 ``` ```rust continue; continue '%label%; break; break '%label%'; ``` ```rust %function%(%arg0%,%arg1%) %receiver%.%method%(%arg0%,%arg1%,%arg2%) // See [on Methods](traits.md#methods) ``` ```rust |%arg0%, %arg1%, %...%| %expression% // %#.2 Closures |%arg0%: %Type0%, %arg1%: %Type1%, %...%| -> %ReturnType% %expression% ``` ```rust %fallible%? // See [in Error handling](errors.md#result--) ``` ```rust *%value% // [`Deref`], see [in Traits, methods](traits.md#deref-and-method-resolution) ``` ```rust %value% as %OtherType% // Type conversion (safe but maybe lossy, see [in Safety](safety.md#integers-conversion-checking)) ``` ```rust %Counter% { %counter%: 42 } // Constructor ("struct literal") ``` ```rust %collection%[%index%] // Usually panics if not found, eg array bounds check ``` -------------------------------- ### Creating Range Expressions Source: https://github.com/iwj/rust-polyglot/blob/main/src/syntax.md Shows how to create exclusive and inclusive range expressions in Rust. ```Rust %start%..%end%; %start%..=%end% // End-exclusive and -inclusive [`Range`] ``` -------------------------------- ### Defining a macro_rules! Macro Source: https://github.com/iwj/rust-polyglot/blob/main/src/macros.md Basic syntax for defining a macro using macro_rules!. It involves a name, followed by a list of template-replacement pairs. ```Rust macro_rules! name { { template1 } => { replacement1 }, ... } ``` -------------------------------- ### Derive Macro Syntax Source: https://github.com/iwj/rust-polyglot/blob/main/src/macros.md Demonstrates the syntax for using a derive macro with structs, enums, or unions. The macro generates additional code based on the decorated data structure. ```Rust #[derive(Macro)] ``` -------------------------------- ### Accessing Struct Fields Source: https://github.com/iwj/rust-polyglot/blob/main/src/syntax.md Demonstrates syntax for accessing fields in named structs and tuple structs. ```Rust %thing%.%field% // Field of a struct with named fields %tuple%.0; %tuple%.1; // Fields of tuple or tuple struct ``` -------------------------------- ### Defining Empty Product Types (Unit Structs) Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Defines unit structs, which represent empty products. ```rust struct Z0; ``` ```rust struct Z1(); ``` ```rust struct Z2{} ``` -------------------------------- ### Rust Assert Macro Source: https://github.com/iwj/rust-polyglot/blob/main/src/errors.md Demonstrates the `assert!` macro, which panics if the given condition is false. It's used for verifying internal invariants and detecting programming errors during development. ```rust [`assert!`] ``` -------------------------------- ### Defining a Struct with Tuple-like Fields Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Defines a nominal product type using a tuple-like structure. ```rust struct ST(u64, ()); ``` -------------------------------- ### Allow Incomplete Features in Rust Source: https://github.com/iwj/rust-polyglot/blob/main/src/stability.md When using unstable features that are known to be incomplete or potentially unsound, you must add `#![allow(incomplete_features)]` to your crate's toplevel. This acknowledges the known issues. ```rust #![allow(incomplete_features)] ``` -------------------------------- ### Enable Unstable Feature in Rust Source: https://github.com/iwj/rust-polyglot/blob/main/src/stability.md Use `#![feature(something)]` at the crate's toplevel to enable experimental or unstable language features on the Nightly toolchain. This is required for features not yet stabilized. ```rust #![feature(something)] ``` -------------------------------- ### Procedural Macro Signature Source: https://github.com/iwj/rust-polyglot/blob/main/src/macros.md Defines the basic signature of a procedural macro, which takes a TokenStream and returns a TokenStream. ```Rust proc_macro ``` -------------------------------- ### Attribute Macro Syntax Source: https://github.com/iwj/rust-polyglot/blob/main/src/macros.md Shows the syntax for applying an attribute macro to a language construct. The macro can modify or filter the decorated item. ```Rust #[macro] ``` -------------------------------- ### Referencing Raw Pointers Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Syntax for referring to raw pointers, which are not guaranteed to be valid or non-null. ```rust *const T ``` ```rust *mut T ``` -------------------------------- ### Using the ? Operator with Result Source: https://github.com/iwj/rust-polyglot/blob/main/src/errors.md Demonstrates how the `?` operator simplifies error propagation. It unwraps `Ok` values or returns the `Err` from the containing function, automatically converting the error type if necessary. ```rust // `?` applied to an `Ok` simply unwraps the inner success value `T`. // `?` applied to an `Err` // causes the containing function to return `Err(E)` // after converting the error `E` // to the containing function's error return type (using [`From`]). ``` -------------------------------- ### Specifying Generic Parameters with Turbofish Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Use the turbofish syntax `::` to explicitly specify generic parameters for a function call when type elision is not sufficient. ```rust let r = function::(...); ``` -------------------------------- ### Collecting Iterator Results Source: https://github.com/iwj/rust-polyglot/blob/main/src/traits.md Demonstrates how to use the .collect() method to reassemble iterator results into a collection, often requiring explicit type annotation. This is preferred over manually adding to a mutable collection. ```rust let processed = things .filter_map(|t| ...) .map(|t| ...?; ...; Ok(u)) .take(42) .collect::,io::Error>()?; ``` -------------------------------- ### Defining a Struct with Named Fields Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Defines a nominal product type with named fields. ```rust struct S { f: u64, g: &'static str } ``` -------------------------------- ### Referencing Primitive Integer Types Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Syntax for referring to Rust's primitive integer types. ```rust usize ``` ```rust isize ``` ```rust u8 ``` ```rust u16 ``` ```rust u32 ``` ```rust u64 ``` ```rust u128 ``` ```rust i8 ``` ```rust i16 ``` ```rust i32 ``` ```rust i64 ``` ```rust i128 ``` -------------------------------- ### Referencing Immutable and Mutable References Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Syntax for referring to immutable and mutable references, which are always valid and never null. ```rust &T ``` ```rust &mut T ``` ```rust &'lifetime T ``` ```rust &'l mut T ``` -------------------------------- ### Rust Item Declarations Source: https://github.com/iwj/rust-polyglot/blob/main/src/syntax.md Demonstrates common item declarations in Rust, including functions, type aliases, structs, traits, constants, static variables, and modules. These define the structure and components of a Rust program. ```rust fn %function%(%arg0%: %T%, %arg1%: %U%) -> %ReturnType% { %...% } type %TypeAlias% = %OtherType%; // Type alias, structural equality pub struct %Counter% { %counter%: u64 } // Nominal type equality trait %Trait% { fn %trait_method%(self); } const %FORTY_TWO%: u32 = 42; static %TABLE%: [u8; 256] = { 0x32, 0x26, 0o11, %entries...% }; impl %Type% { ... } impl %Trait% for %Type% { ... } mod %some_module%; // Causes `%some_module%.rs` to be read mod %some_module% { ... } // Module source is right here ``` -------------------------------- ### Using `Box` as a Workaround Source: https://github.com/iwj/rust-polyglot/blob/main/src/traits.md Illustrates the common workaround of using `Box` when an alias for an existential type is needed, such as for storing in variables. ```Rust Box ``` -------------------------------- ### Explicit Ok(()) Return Source: https://github.com/iwj/rust-polyglot/blob/main/src/errors.md Illustrates the requirement to explicitly return `Ok(())` at the end of a fallible function that would otherwise implicitly return `()`, a common pattern when not using macros like `culpa`. ```rust // One must write // `Ok(())` at the end of a function which would otherwise fall off the end // implicitly returning `()`. ``` -------------------------------- ### Referencing a Tuple Type Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Syntax for referring to tuple types of varying arity. ```rust (T,) ``` ```rust (T,U) ``` ```rust (T,U,V) ``` -------------------------------- ### Enable Unstable Options in Rustc Source: https://github.com/iwj/rust-polyglot/blob/main/src/stability.md Add `-Z unstable-options` to your command line arguments when using `rustc` or `cargo` to enable unstable command-line options. This is necessary for certain experimental compiler flags. ```bash -Z unstable-options ``` -------------------------------- ### Referencing Floating Point Types Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Syntax for referring to Rust's IEEE-754 floating-point types. ```rust f32 ``` ```rust f64 ``` -------------------------------- ### Referencing Other Primitive Types Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Syntax for referring to other primitive types like boolean, character, and string slices. ```rust bool ``` ```rust char ``` ```rust str ``` -------------------------------- ### Referencing a Trait Object Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Syntax for referring to a trait object, enabling runtime trait dispatch via a vtable. ```rust dyn Trait ``` -------------------------------- ### Defining Generic Parameters with Bounds Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Generic parameters can be constrained using bounds directly in the function signature or with a `where` clause. ```rust fn foo() -> T; ``` ```rust fn foo() -> T where T: Default + Clone; ``` -------------------------------- ### Referencing a Slice Type Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Syntax for referring to a slice type, representing a contiguous sequence of objects whose size is known at runtime. ```rust [T] ``` -------------------------------- ### Referencing an Array Type Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Syntax for referring to an array type with a fixed size known at compile time. ```rust [T; N] ``` -------------------------------- ### Referencing Types to be Inferred Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Syntax for indicating that a type should be inferred by the compiler. ```rust _ ``` ```rust &'_ T ``` ```rust &'_ mut T ``` -------------------------------- ### Rust Panic Macro Source: https://github.com/iwj/rust-polyglot/blob/main/src/errors.md Shows the explicit `panic!()` macro, which causes an unrecoverable program failure. This is typically used for programming errors rather than expected exceptional cases. ```rust [`panic!()`] ``` -------------------------------- ### Referencing an Existential Type Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Syntax for referring to an existential type, often used for opaque types returned from functions. ```rust impl Trait ``` -------------------------------- ### Defining an Uninhabited Type Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Defines an uninhabited type, which has no possible values. ```rust enum Void { } ``` -------------------------------- ### Function with Elided Lifetime Source: https://github.com/iwj/rust-polyglot/blob/main/src/ownership.md A simple function that returns an Option<&str>. The lifetime of the returned reference is elided but inferred by the compiler. ```rust fn not_bonkers(s: &str) -> Option<&str> { if s == "bonkers" { None } else { Some(s) } } ``` -------------------------------- ### Returning an Existential Type with `impl Trait` Source: https://github.com/iwj/rust-polyglot/blob/main/src/traits.md Demonstrates using `impl Trait` in a function signature to return an iterator whose concrete type is not specified. ```Rust fn get_strings() -> Result, io::Error>; ``` -------------------------------- ### Struct with Lifetime Annotation Source: https://github.com/iwj/rust-polyglot/blob/main/src/ownership.md Defines a struct that holds an immutable reference to a u64. The lifetime parameter 'r ensures the reference is valid for the lifetime of the struct. ```rust struct CounterRef<'r>(&'r u64); ``` -------------------------------- ### Function with Explicit Lifetime Source: https://github.com/iwj/rust-polyglot/blob/main/src/ownership.md The explicit lifetime version of the 'not_bonkers' function, showing the inferred lifetime parameter 's. ```rust fn not_bonkers<'s>(s: &'s str) -> Option<&'s str> { ``` -------------------------------- ### Test Function with should_panic Annotation Source: https://github.com/iwj/rust-polyglot/blob/main/src/rustdoc.md The `#[should_panic]` attribute can be applied to `#[test]` functions to indicate that the test is expected to panic. ```rust #[test] #[should_panic] fn panics() { panic!() } ``` -------------------------------- ### Defining a Generic Struct Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Defines a generic nominal type that can be parameterized by other types. ```rust struct SG{ f: F, g: &'static str } ``` -------------------------------- ### Defining a Sum Type (Enum) Source: https://github.com/iwj/rust-polyglot/blob/main/src/types.md Defines a nominal sum type using an enum, which can hold different variants. ```rust enum E { V0, V1(usize), V2{ f: String, } } ```