### Example Foo Input with Let Binding Source: https://docs.rs/chumsky/latest/chumsky/guide/_07_tutorial/index.html An example of valid Foo input demonstrating a let binding followed by an expression that uses the bound variable. ```plaintext let five = 5; five * 3 ``` -------------------------------- ### Example Usage of ExtParser Source: https://docs.rs/chumsky/latest/chumsky/extension/v1/trait.ExtParser.html An example demonstrating how to implement an extension trait to allow custom parser combinators to be used with Chumsky. ```APIDOC ### Example Implementation ```rust use chumsky::prelude::*; pub struct FrobnicatedWith { a: A, b: B } pub trait ParserExt<'src, I, O, E> where I: Input<'src>, E: extra::ParserExtra<'src, I> { fn frobnicated_with(self, other: B) -> FrobnicatedWith where Self: Sized, B: Parser<'src, I, O, E>, { FrobnicatedWith { a: self, b: other } } } // Users can then import this trait and use it like so: // let parser = some_parser.frobnicated_with(another_parser); ``` ``` -------------------------------- ### Contextual Parser Example Source: https://docs.rs/chumsky/latest/chumsky/trait.Parser.html This example demonstrates how to use `contextual` to enable or disable parsers based on a provided context. It shows parsing numbers in hexadecimal or denary mode using `extra::Context` and `configure`. ```rust // Our parser can be in two modes depending on context: hexadecimal, or denary #[derive(Clone)] enum Mode { Hex, Dec } let digits = one_of::<_, _, extra::Context>("0123456789") .or(one_of("abcdef").contextual().configure(|cfg, ctx| matches!(ctx, Mode::Hex))) .repeated(); let num = just::<_, _, extra::Default>("0x").ignore_then(digits.with_ctx(Mode::Hex)) // Fallback: when '0x' isn't present, parse using denary mode .or(digits.with_ctx(Mode::Dec)) .to_slice(); assert_eq!(num.parse("0x1a3f5b").into_result(), Ok("0x1a3f5b")); assert_eq!(num.parse("12345").into_result(), Ok("12345")); // Without the '0x' prefix, hexadecimal digits are invalid assert!(num.parse("1a3f5b").has_errors()); ``` -------------------------------- ### MappedInput::begin Implementation Source: https://docs.rs/chumsky/latest/chumsky/input/struct.MappedInput.html Creates an initial cursor and cache at the start of the `MappedInput` stream. ```rust fn begin(self) -> (Self::Cursor, Self::Cache) ``` -------------------------------- ### Rich Error Example Source: https://docs.rs/chumsky/latest/chumsky/error/struct.Rich.html Demonstrates how to create and parse a Rich error. This example shows how to use `one_of` to create a parser that expects specific characters and how to extract and assert details from the resulting error. ```rust use chumsky::prelude::*; use chumsky::error::{RichReason, RichPattern}; let parser = one_of::<_, _, extra::Err>>("1234"); let error = parser.parse("5").into_errors()[0].clone(); assert_eq!(error.span(), &SimpleSpan::new((), 0..1)); assert!(matches!(error.reason(), &RichReason::ExpectedFound {..})); assert_eq!(error.found(), Some(&'5')); ``` -------------------------------- ### Get Slice from Start Cursor Source: https://docs.rs/chumsky/latest/chumsky/input/struct.MappedInput.html Safely extracts a slice from a given start cursor to the end of the input. This is an unsafe operation. ```rust unsafe fn slice_from( (cache, _, _): &mut Self::Cache, from: RangeFrom<&Self::Cursor>, ) -> Self::Slice ``` -------------------------------- ### ConfigParser Configure Method Example Source: https://docs.rs/chumsky/latest/chumsky/trait.ConfigParser.html Demonstrates using the `configure` method to create a parser that accepts a specific number of items based on a prefix length derived from context. ```rust let int = text::int::<_, extra::Err>>(10) .from_str() .unwrapped(); // By default, accepts any number of items let item = text::ascii::ident() .padded() .repeated(); // With configuration, we can declare an exact number of items based on a prefix length let len_prefixed_arr = int .ignore_with_ctx(item.configure(|repeat, ctx| repeat.exactly(*ctx)).collect::>()); assert_eq!( len_prefixed_arr.parse("2 foo bar").into_result(), Ok(vec!["foo", "bar"]), ); assert_eq!( len_prefixed_arr.parse("0").into_result(), Ok(vec![]), ); len_prefixed_arr.parse("3 foo bar baz bam").into_result().unwrap_err(); len_prefixed_arr.parse("3 foo bar").into_result().unwrap_err(); ``` -------------------------------- ### Implement ExactSizeInput for MappedSpan Source: https://docs.rs/chumsky/latest/chumsky/input/struct.MappedSpan.html Enables getting a span from a start cursor to the end of the input for MappedSpan. ```rust unsafe fn span_from( (cache, mapper): &mut Self::Cache, range: RangeFrom<&Self::Cursor>, ) -> Self::Span ``` -------------------------------- ### Rust Project Setup with Chumsky Source: https://docs.rs/chumsky/latest/chumsky/guide/_07_tutorial/index.html Initializes a new Rust project, adds Chumsky as a dependency, and reads a file specified by the first command-line argument to print its contents. Error handling is minimal, using `.unwrap()` for simplicity. ```rust use chumsky::prelude::*; fn main() { let src = std::fs::read_to_string(std::env::args().nth(1).unwrap()).unwrap(); println!("{}", src); } ``` -------------------------------- ### MappedInput::span_from Implementation Source: https://docs.rs/chumsky/latest/chumsky/input/struct.MappedInput.html Gets a span from a start cursor to the end of the input for `MappedInput`. This requires `I` to be an `ExactSizeInput`. ```rust unsafe fn span_from( (cache, mapper, eoi): &mut Self::Cache, range: RangeFrom<&Self::Cursor>, ) -> Self::Span ``` -------------------------------- ### From Implementation Source: https://docs.rs/chumsky/latest/chumsky/extension/v1/struct.Ext.html Provides a basic From implementation. ```APIDOC ### impl From for T #### fn from(t: T) -> T ##### Description Returns the argument unchanged. ``` -------------------------------- ### ExactSizeInput span_from Method Source: https://docs.rs/chumsky/latest/chumsky/input/trait.ExactSizeInput.html Gets a span from a start cursor to the end of the input. Cursors must be generated by this input. ```rust unsafe fn span_from( cache: &mut Self::Cache, range: RangeFrom<&Self::Cursor>, ) -> Self::Span; ``` -------------------------------- ### Get Slice from Range Source: https://docs.rs/chumsky/latest/chumsky/input/struct.MappedInput.html Safely extracts a slice from the input given a start and end cursor. This operation is unsafe due to cursor manipulation. ```rust unsafe fn slice( (cache, _, _): &mut Self::Cache, range: Range<&Self::Cursor>, ) -> Self::Slice ``` -------------------------------- ### Sample Program for Interpreter Source: https://docs.rs/chumsky/latest/chumsky/guide/_07_tutorial/index.html A basic program demonstrating variable declarations, function definition, and function calls within the interpreter. ```rust let five = 5; let eight = 3 + five; fn add x y = x + y; add(five, eight) ``` -------------------------------- ### CloneToUninit Implementation Source: https://docs.rs/chumsky/latest/chumsky/error/enum.RichReason.html Nightly-only experimental API for clone_to_uninit. ```APIDOC ## impl CloneToUninit for T ### Description Nightly-only experimental API for clone_to_uninit. ### Method CloneToUninit ### Endpoint N/A #### unsafe fn clone_to_uninit(&self, dest: *mut u8) Performs copy-assignment from `self` to `dest`. ``` -------------------------------- ### Implement ExactSizeInput for &'src Graphemes Source: https://docs.rs/chumsky/latest/chumsky/text/unicode/struct.Graphemes.html Implements the ExactSizeInput trait for a reference to Graphemes, providing a method to get the span from a start cursor to the end of the input. ```rust unsafe fn span_from( this: &mut Self::Cache, range: RangeFrom<&Self::Cursor>, ) -> Self::Span ``` -------------------------------- ### Remove a prefix from a slice Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `strip_prefix` to get a subslice after removing a specified prefix. Returns `None` if the slice does not start with the prefix. Handles empty prefixes and prefixes equal to the slice. ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); ``` ```rust let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` -------------------------------- ### CloneToUninit Implementation Source: https://docs.rs/chumsky/latest/chumsky/combinator/struct.IntoIter.html Nightly-only experimental API for cloning to uninitialized memory. ```APIDOC ### impl CloneToUninit for T #### unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ### Method `unsafe fn` ### Endpoint N/A (Method on a trait object) ### Parameters - **dest** (*mut u8) - A mutable pointer to the destination memory location. ### Request Example ```rust // let mut buffer = [0u8; size_of::()]; // unsafe { my_value.clone_to_uninit(buffer.as_mut_ptr()); } ``` ### Response None. ``` -------------------------------- ### Iterate Slice Chunks from End Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `rchunks` to get an iterator over mutable slices of a specified size, starting from the end. The last chunk may be smaller if the slice length is not divisible by `chunk_size`. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### Rust Option `and` Method Examples Source: https://docs.rs/chumsky/latest/chumsky/number/format/type.OptionU8.html Demonstrates the `and` method, which returns `None` if either option is `None`, otherwise returns the second option. ```rust let x = Some(2); let y: Option<&str> = None; assert_eq!(x.and(y), None); ``` ```rust let x: Option = None; let y = Some("foo"); assert_eq!(x.and(y), None); ``` ```rust let x = Some(2); let y = Some("foo"); assert_eq!(x.and(y), Some("foo")); ``` ```rust let x: Option = None; let y: Option<&str> = None; assert_eq!(x.and(y), None); ``` -------------------------------- ### Check if Pointer is within Slice Range Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Demonstrates how to use `as_ptr_range` to get the start and end pointers of a slice and check if a given pointer falls within that range. This is useful for interacting with C-style APIs. ```rust let a = [1, 2, 3]; let x = &a[1] as *const _; let y = &5 as *const _; assert!(a.as_ptr_range().contains(&x)); assert!(!a.as_ptr_range().contains(&y)); ``` -------------------------------- ### Using choice for Lexer Tokens Source: https://docs.rs/chumsky/latest/chumsky/primitive/fn.choice.html Demonstrates how to use the `choice` primitive to define a lexer that recognizes various keywords, integers, and identifiers. This is ideal for lexers due to performance benefits. ```rust #[derive(Clone, Debug, PartialEq)] enum Token<'src> { If, For, While, Fn, Int(u64), Ident(&'src str), } let tokens = choice(( text::ascii::keyword::<_, _, extra::Err>>("if").to(Token::If), text::ascii::keyword("for").to(Token::For), text::ascii::keyword("while").to(Token::While), text::ascii::keyword("fn").to(Token::Fn), text::int(10).from_str().unwrapped().map(Token::Int), text::ascii::ident().map(Token::Ident), )) .padded() .repeated() .collect::>(); use Token::*; assert_eq!( tokens.parse("if 56 for foo while 42 fn bar").into_result(), Ok(vec![If, Int(56), For, Ident("foo"), While, Int(42), Fn, Ident("bar")]), ); ``` -------------------------------- ### Iterate Mutable Slice Chunks from End Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `rchunks_mut` to get an iterator over mutable slices of a specified size, starting from the end. This allows in-place modification of elements within each chunk. The last chunk may be smaller. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[3, 2, 2, 1, 1]); ``` -------------------------------- ### Rust Option `or` Method Examples Source: https://docs.rs/chumsky/latest/chumsky/number/format/type.OptionU8.html Demonstrates the `or` method, which returns the first option if it has a value, otherwise returns the second option. Arguments are eagerly evaluated. ```rust let x = Some(2); let y = None; assert_eq!(x.or(y), Some(2)); ``` ```rust let x = None; let y = Some(100); assert_eq!(x.or(y), Some(100)); ``` ```rust let x = Some(2); let y = Some(100); assert_eq!(x.or(y), Some(2)); ``` ```rust let x: Option = None; let y = None; assert_eq!(x.or(y), None); ``` -------------------------------- ### Iterating Over Reverse Chunks of a Slice Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `rchunks` to get an iterator over `chunk_size` elements of the slice at a time, starting from the end. The last chunk may be smaller if `chunk_size` does not divide the slice length. Panics if `chunk_size` is zero. ```rust let slice = [0, 1, 2, 3, 4, 5]; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &[4, 5]); assert_eq!(iter.next().unwrap(), &[2, 3]); assert_eq!(iter.next().unwrap(), &[0, 1]); assert!(iter.next().is_none()); ``` -------------------------------- ### Example Input and Foldr Output Source: https://docs.rs/chumsky/latest/chumsky/guide/_07_tutorial/index.html Illustrates the intermediate output generated by `repeated()` before being processed by `foldr`. This shows the sequence of operators and the final atom. ```text ['-', '-', '-'], Num(42.0) ``` -------------------------------- ### Get Element Offset in Slice Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Shows how to use the experimental `element_offset` method to find the index of an element reference within a slice. This method uses pointer arithmetic and does not compare elements. It returns `None` if the element reference is not aligned with the start of an element. ```rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust #![feature(substr_range)] let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### get Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Safely gets a reference to an element or subslice by index or range. Returns None if the index is out of bounds. ```APIDOC ## pub fn get(&self, index: I) -> Option<&>::Output> where I: SliceIndex<[T]> ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or `None` if out of bounds. If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Method `get` ### Parameters - `index` (I): The index or range to access. ### Request Example ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` ### Response Example ```rust // On success, returns Some(&element or subslice) // On failure (out of bounds), returns None ``` ``` -------------------------------- ### Build Parser Dynamically with Boxed Source: https://docs.rs/chumsky/latest/chumsky/trait.Parser.html Demonstrates how to dynamically build a parser using `boxed`. By boxing each parser, type mismatches are avoided, allowing for flexible construction of parsers at runtime. ```rust let user_input = user_input(); let mut parser = just('a').boxed(); for i in user_input { // Doesn't work due to type mismatch - since every combinator creates a unique type parser = parser.or(i).boxed(); } let parser = parser.then(just('z')); parser.parse("az").into_result().unwrap(); ``` -------------------------------- ### Get Last Element of Slice Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `last()` to get an immutable reference to the last element. Returns `None` if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### Example Foo Language Code Source: https://docs.rs/chumsky/latest/chumsky/guide/_07_tutorial/index.html Sample code written in the 'Foo' programming language, demonstrating variable assignment, function definition, and expression evaluation. ```plaintext let seven = 7; fn add x y = x + y; add(2, 3) * -seven ``` -------------------------------- ### Get First Element of Slice Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `first()` to get an immutable reference to the first element. Returns `None` if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### Append Element and Get Mutable Reference (Experimental) Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `push_mut` to append an element and immediately get a mutable reference to it. This is a nightly-only experimental API. ```rust #![feature(push_mut)] let mut vec = vec![1, 2]; let last = vec.push_mut(3); assert_eq!(*last, 3); assert_eq!(vec, [1, 2, 3]); let last = vec.push_mut(3); *last += 1; assert_eq!(vec, [1, 2, 3, 4]); ``` -------------------------------- ### fn with_ctx Source: https://docs.rs/chumsky/latest/chumsky/primitive/struct.Set.html Runs the previous contextual parser with the provided context. ```APIDOC ## fn with_ctx(ctx: E::Context) ### Description Run the previous contextual parser with the provided context. ### Method `with_ctx` ### Parameters - **ctx** (E::Context) - Required - The context to run the parser with. ### Request Example ```json { "example": "request body for with_ctx" } ``` ### Response #### Success Response (200) - **Output** (Type depends on the parser) - Description: The result of the parser with the provided context. #### Response Example ```json { "example": "response body for with_ctx" } ``` ``` -------------------------------- ### with_ctx Source: https://docs.rs/chumsky/latest/chumsky/combinator/struct.IgnoreWithCtx.html Runs the previous contextual parser with the provided context. ```APIDOC ## fn with_ctx(self, ctx: E::Context) ### Description Run the previous contextual parser with the provided context. ### Method `with_ctx` ### Parameters - `ctx` (E::Context): The context to run the parser with. ``` -------------------------------- ### Remove and Get Last Element (Immutable) Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `split_off_last` to remove the last element from an immutable slice and get an immutable reference to it. Returns `None` if the slice is empty. ```rust let mut slice: &[_] = &['a', 'b', 'c']; let last = slice.split_off_last().unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(last, &'c'); ``` -------------------------------- ### IoInput Constructor Source: https://docs.rs/chumsky/latest/chumsky/input/struct.IoInput.html How to create a new IoInput instance from a seekable reader. ```APIDOC ## Implementations ### impl IoInput #### pub fn new(reader: R) -> IoInput Create a new `IoReader` from a seekable reader. ``` -------------------------------- ### Remove and Get First Element (Immutable) Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `split_off_first` to remove the first element from an immutable slice and get an immutable reference to it. Returns `None` if the slice is empty. ```rust let mut slice: &[_] = &['a', 'b', 'c']; let first = slice.split_off_first().unwrap(); assert_eq!(slice, &['b', 'c']); assert_eq!(first, &'a'); ``` -------------------------------- ### Rust Option `xor` Method Examples Source: https://docs.rs/chumsky/latest/chumsky/number/format/type.OptionU8.html Shows the `xor` method, which returns `Some` if exactly one of the two options is `Some`, otherwise returns `None`. ```rust let x = Some(2); let y: Option = None; assert_eq!(x.xor(y), Some(2)); ``` ```rust let x: Option = None; let y = Some(2); assert_eq!(x.xor(y), Some(2)); ``` ```rust let x = Some(2); let y = Some(2); assert_eq!(x.xor(y), None); ``` ```rust let x: Option = None; let y: Option = None; assert_eq!(x.xor(y), None); ``` -------------------------------- ### Borrow and BorrowMut Implementations Source: https://docs.rs/chumsky/latest/chumsky/combinator/struct.IntoIter.html Implementations for borrowing and mutable borrowing. ```APIDOC ### impl Borrow for T #### fn borrow(&self) -> &T ### Description Immutably borrows from an owned value. ### Method `fn` ### Endpoint N/A (Method on a trait object) ### Parameters None ### Request Example ```rust // let borrowed_value = &my_value; ``` ### Response An immutable reference to the value. ### impl BorrowMut for T #### fn borrow_mut(&mut self) -> &mut T ### Description Mutably borrows from an owned value. ### Method `fn` ### Endpoint N/A (Method on a trait object) ### Parameters None ### Request Example ```rust // let mut_borrowed_value = &mut my_value; ``` ### Response A mutable reference to the value. ``` -------------------------------- ### Get Mutable Reference to Last Element Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `last_mut()` to get a mutable reference to the last element. Returns `None` if the slice is empty. Allows in-place modification. ```rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_mut() { *last = 10; } assert_eq!(x, &[0, 1, 10]); let y: &mut [i32] = &mut []; assert_eq!(None, y.last_mut()); ``` -------------------------------- ### digits parser example Source: https://docs.rs/chumsky/latest/chumsky/text/fn.digits.html Demonstrates parsing ASCII digits using the `digits` parser with radix 10. The parser is converted to a slice for output. It shows successful parsing of single digits, multiple digits, and a string of zeroes. It also shows that an empty string results in parsing errors. ```rust let digits = text::digits::<_, extra::Err>>(10).to_slice(); assert_eq!(digits.parse("0").into_result(), Ok("0")); assert_eq!(digits.parse("1").into_result(), Ok("1")); assert_eq!(digits.parse("01234").into_result(), Ok("01234")); assert_eq!(digits.parse("98345").into_result(), Ok("98345")); // A string of zeroes is still valid. Use `int` if this is not desirable. assert_eq!(digits.parse("0000").into_result(), Ok("0000")); assert!(digits.parse("").has_errors()); ``` -------------------------------- ### Get Mutable Reference to First Element Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `first_mut()` to get a mutable reference to the first element. Returns `None` if the slice is empty. Allows in-place modification. ```rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_mut() { *first = 5; } assert_eq!(x, &[5, 1, 2]); let y: &mut [i32] = &mut []; assert_eq!(None, y.first_mut()); ``` -------------------------------- ### From and Into Implementations Source: https://docs.rs/chumsky/latest/chumsky/combinator/struct.IntoIter.html Implementations for type conversions using `From` and `Into`. ```APIDOC ### impl From for T #### fn from(t: T) -> T ### Description Returns the argument unchanged. ### Method `fn` ### Endpoint N/A (Associated function) ### Parameters - **t** (T) - The value to convert. ### Request Example ```rust // let new_value = T::from(original_value); ``` ### Response The converted value. ### impl Into for T #### fn into(self) -> U ### Description Calls `U::from(self)`. This conversion is whatever the implementation of `From for U` chooses to do. ### Method `fn` ### Endpoint N/A (Method on a value) ### Parameters None ### Request Example ```rust // let converted_value: U = original_value.into(); ``` ### Response The converted value. ``` -------------------------------- ### Parser Type Erasure Examples Source: https://docs.rs/chumsky/latest/chumsky/cache/trait.Cached.html Examples of type-erased parser types for the `Parser` associated type in the `Cached` trait. These are recommended due to the often unwieldy types of parsers. ```rust Boxed<'src, 'src, &'src str, Token<'src>, extra::Default> ``` ```rust Arc, extra::Default> + Send + Sync + 'src> ``` -------------------------------- ### Implement ConfigParser for Just Source: https://docs.rs/chumsky/latest/chumsky/primitive/struct.Just.html Enables configuration of the 'Just' parser using a closure. This is useful for context-aware parsing, such as handling indentation. ```rust impl<'src, I, E, T> ConfigParser<'src, I, T, E> for Just type Config = JustCfg ``` ```rust fn configure(self, cfg: F) -> Configure where Self: Sized, F: Fn(Self::Config, &E::Context) -> Self::Config, ``` -------------------------------- ### Accept End of Input Parser Source: https://docs.rs/chumsky/latest/chumsky/primitive/fn.end.html Use this parser to ensure that the input has been fully consumed. The output type is `()`. No specific setup or imports are required beyond the basic chumsky setup. ```rust pub const fn end<'src, I: Input<'src>, E: ParserExtra<'src, I>>() -> End ``` -------------------------------- ### fn with_state(self, state: State) -> WithState Source: https://docs.rs/chumsky/latest/chumsky/trait.Parser.html Runs the previous parser with the provided state. This is uncommonly used and exists mostly for completeness. One possible use-case is ‘glueing’ together parsers declared in different places with incompatible state types. Note that the state value will be cloned and dropping _during_ parsing, so it is recommended to ensure that this is a relatively performant operation. ```APIDOC ## fn with_state(self, state: State) -> WithState ### Description Runs the previous parser with the provided state. This is uncommonly used and exists mostly for completeness. One possible use-case is ‘glueing’ together parsers declared in different places with incompatible state types. Note that the state value will be cloned and dropping _during_ parsing, so it is recommended to ensure that this is a relatively performant operation. ### Method (Implicitly part of the parser chain, not a direct HTTP method) ### Endpoint (N/A - this is a method on a parser object) ### Parameters #### Path Parameters (N/A) #### Query Parameters (N/A) #### Request Body (N/A) ### Request Example (N/A - this is a method call, not an API request) ### Response #### Success Response (200) (N/A - returns a new parser type) #### Response Example (N/A) ``` -------------------------------- ### Remove and Get Last Element (Mutable) Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `split_off_last_mut` to remove the last element from a mutable slice and get a mutable reference to it. Returns `None` if the slice is empty. The element can be modified. ```rust let mut slice: &mut [_] = &mut ['a', 'b', 'c']; let last = slice.split_off_last_mut().unwrap(); *last = 'd'; assert_eq!(slice, &['a', 'b']); assert_eq!(last, &'d'); ``` -------------------------------- ### then_with_ctx Source: https://docs.rs/chumsky/latest/chumsky/primitive/struct.Set.html Parses one thing and then another, creating the second parser from the result of the first, including context. ```APIDOC ## fn then_with_ctx( self, then: P, ) -> ThenWithCtx> ### Description Parse one thing and then another thing, creating the second parser from the result of the first. If you don’t need the context in the output, prefer `Parser::ignore_with_ctx`. ### Method `then_with_ctx` ### Parameters - `then`: The parser to apply after the first, created from the first's result, and its output is included. ``` -------------------------------- ### Remove and Get First Element (Mutable) Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `split_off_first_mut` to remove the first element from a mutable slice and get a mutable reference to it. Returns `None` if the slice is empty. The element can be modified. ```rust let mut slice: &mut [_] = &mut ['a', 'b', 'c']; let first = slice.split_off_first_mut().unwrap(); *first = 'd'; assert_eq!(slice, &['b', 'c']); assert_eq!(first, &'d'); ``` -------------------------------- ### ExactSizeInput Implementation for WithContext Source: https://docs.rs/chumsky/latest/chumsky/input/trait.ExactSizeInput.html Implementation of ExactSizeInput for inputs wrapped with context. Requires the inner input to also implement ExactSizeInput. ```rust impl<'src, S, I> ExactSizeInput<'src> for WithContext where I: ExactSizeInput<'src> + Input<'src>, S: Span + Clone + 'src, S::Context: Clone + 'src, S::Offset: From<::Offset>, ``` -------------------------------- ### Get First N Elements as Array Slice Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `first_chunk::()` to get an array slice reference to the first `N` elements. Returns `None` if the slice is shorter than `N`. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` -------------------------------- ### IoInput Blanket Implementations Source: https://docs.rs/chumsky/latest/chumsky/input/struct.IoInput.html Demonstrates blanket implementations for IoInput, including Any, Borrow, BorrowMut, From, and Into traits, which are common to many Rust types. ```rust impl Any for T where T: 'static + ?Sized, ``` ```rust impl Borrow for T where T: ?Sized, ``` ```rust impl BorrowMut for T where T: ?Sized, ``` ```rust impl From for T fn from(t: T) -> T ``` ```rust impl Into for T where U: From, ``` ```rust impl IntoEither for T ``` -------------------------------- ### CloneToUninit Trait Implementation Source: https://docs.rs/chumsky/latest/chumsky/util/enum.Maybe.html Details the nightly-only experimental `CloneToUninit` trait implementation. ```APIDOC ### impl CloneToUninit for T where T: Clone, #### unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description 🔬This is a nightly-only experimental API. (`clone_to_uninit`) Performs copy-assignment from `self` to `dest`. ### Method N/A (Method within an `impl` block) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get Mutable First N Elements as Array Slice Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `first_chunk_mut::()` to get a mutable array slice reference to the first `N` elements. Returns `None` if the slice is shorter than `N`. ```rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_chunk_mut::<2>() { first[0] = 5; first[1] = 4; } assert_eq!(x, &[5, 4, 2]); assert_eq!(None, x.first_chunk_mut::<4>()); ``` -------------------------------- ### Rust Option `insert` Method Example Source: https://docs.rs/chumsky/latest/chumsky/number/format/type.OptionU8.html Demonstrates `insert`, which inserts a value into the option, returning a mutable reference. If a value already exists, it's dropped. ```rust let mut opt = None; let val = opt.insert(1); assert_eq!(*val, 1); assert_eq!(opt.unwrap(), 1); let val = opt.insert(2); assert_eq!(*val, 2); *val = 3; assert_eq!(opt.unwrap(), 3); ``` -------------------------------- ### Recursive Tree Parsing Example Source: https://docs.rs/chumsky/latest/chumsky/recursive/fn.recursive.html This example demonstrates parsing arbitrarily nested lists using a recursive parser. It defines an enum `Tree` and uses `chumsky::recursive` to parse structures like `[a, b, [c, d]]`. ```rust #[derive(Debug, PartialEq)] enum Tree<'src> { Leaf(&'src str), Branch(Vec>), } // Parser that recursively parses nested lists let tree = recursive::<_, _, extra::Err>, _, _>(|tree| tree .separated_by(just(',')) .collect::>() .delimited_by(just('['), just(']')) .map(Tree::Branch) .or(text::ascii::ident().map(Tree::Leaf)) .padded()); assert_eq!(tree.parse("hello").into_result(), Ok(Tree::Leaf("hello"))); assert_eq!(tree.parse("[a, b, c]").into_result(), Ok(Tree::Branch(vec![ Tree::Leaf("a"), Tree::Leaf("b"), Tree::Leaf("c"), ]))); // The parser can deal with arbitrarily complex nested lists assert_eq!(tree.parse("[[a, b], c, [d, [e, f]]]").into_result(), Ok(Tree::Branch(vec![ Tree::Branch(vec![ Tree::Leaf("a"), Tree::Leaf("b"), ]), Tree::Leaf("c"), Tree::Branch(vec![ Tree::Leaf("d"), Tree::Branch(vec![ Tree::Leaf("e"), Tree::Leaf("f"), ]), ]), ]))); ``` -------------------------------- ### then_with_ctx Source: https://docs.rs/chumsky/latest/chumsky/primitive/struct.Choice.html Parses one parser and then another, creating the second parser from the result of the first, including context. ```APIDOC ## fn then_with_ctx( self, then: P, ) -> ThenWithCtx> where Self: Sized, O: 'src, P: Parser<'src, I, U, Full>, ### Description Parse one thing and then another thing, creating the second parser from the result of the first. If you don’t need the context in the output, prefer `Parser::ignore_with_ctx`. ### Method `then_with_ctx` ### Parameters - `then`: The parser to apply, created from the output of the first parser. ``` -------------------------------- ### TryFrom and TryInto Implementations Source: https://docs.rs/chumsky/latest/chumsky/error/enum.RichReason.html Implementations for TryFrom and TryInto traits. ```APIDOC ## impl TryFrom for T ### Description Blanket implementation for the TryFrom trait. ### Method TryFrom ### Endpoint N/A #### type Error = Infallible The type returned in the event of a conversion error. #### fn try_from(value: U) -> Result>::Error> Performs the conversion. ## impl TryInto for T ### Description Blanket implementation for the TryInto trait. ### Method TryInto ### Endpoint N/A #### type Error = >::Error The type returned in the event of a conversion error. #### fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Unsafe Get Multiple Disjoint Mutable Elements by Index Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Use `get_disjoint_unchecked_mut` to get mutable references to multiple elements or slices at specified indices without bounds checking. This is unsafe and requires careful handling of indices to avoid undefined behavior. ```rust let x = &mut [1, 2, 4]; unsafe { let [a, b] = x.get_disjoint_unchecked_mut([0, 2]); *a *= 10; *b *= 100; } assert_eq!(x, &[10, 2, 400]); ``` ```rust unsafe { let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]); a[0] = 8; b[0] = 88; b[1] = 888; } assert_eq!(x, &[8, 88, 888]); ``` ```rust unsafe { let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]); a[0] = 11; a[1] = 111; b[0] = 1; } assert_eq!(x, &[1, 11, 111]); ``` -------------------------------- ### Using the Whitespace Parser Source: https://docs.rs/chumsky/latest/chumsky/text/fn.whitespace.html Demonstrates parsing with the whitespace parser. It accepts any amount of whitespace, including none. ```rust let whitespace = text::whitespace::<_, extra::Err>>(); // Any amount of whitespace is parsed... assert_eq!(whitespace.parse("\t \n \r ").into_result(), Ok(())); // ...including none at all! assert_eq!(whitespace.parse("").into_result(), Ok(())); ``` -------------------------------- ### Get Length Source: https://docs.rs/chumsky/latest/chumsky/inspector/struct.TruncateState.html Returns the number of elements currently in the vector. ```APIDOC ## GET /vec/len ### Description Returns the number of elements in the vector, also referred to as its ‘length’. ### Method GET ### Endpoint /vec/len ### Parameters #### Query Parameters - **self** (reference) - Required - The vector to get the length of. ### Request Body ```json { "vec": [1, 2, 3] } ``` ### Response #### Success Response (200) - **usize** - The number of elements in the vector. #### Response Example ```json { "length": 3 } ``` ``` -------------------------------- ### Type Information Source: https://docs.rs/chumsky/latest/chumsky/error/struct.Cheap.html Provides a method to get the `TypeId` of a type. ```APIDOC ### impl Any for T where T: 'static + ?Sized, #### fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Request Example None ### Response #### Success Response (TypeId) - Returns the `TypeId` of the object. #### Response Example `TypeId` ``` -------------------------------- ### Rust Option `get_or_insert_default` Method Examples Source: https://docs.rs/chumsky/latest/chumsky/number/format/type.OptionU8.html Shows `get_or_insert_default`, which inserts the `Default` value if the option is `None`, then returns a mutable reference to the contained value. ```rust let mut x = None; { let y: &mut u32 = x.get_or_insert_default(); assert_eq!(y, &0); *y = 7; } assert_eq!(x, Some(7)); ```