Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Full Moon
https://docs.rs/full_moon/latest/full_moon/
Admin
Full Moon is a lossless parser for Lua, supporting Lua 5.1, 5.2, 5.3, 5.4, and Luau.
Tokens:
33,504
Snippets:
401
Trust Score:
9.7
Update:
1 month ago
Context
Chat
Benchmark
62.33
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Trim start matches example Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Demonstrates removing a slice of characters from the start of a string. ```rust let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); ``` -------------------------------- ### Check string prefix Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Verifies if the string starts with a specific pattern. ```rust let bananas = "bananas"; assert!(bananas.starts_with("bana")); assert!(!bananas.starts_with("nana")); ``` ```rust let bananas = "bananas"; // Note that both of these assert successfully. assert!(bananas.starts_with(&['b', 'a', 'n', 'a'])); assert!(bananas.starts_with(&['a', 'b', 'c', 'd'])); ``` -------------------------------- ### Token::start_position Source: https://docs.rs/full_moon/latest/full_moon/tokenizer/struct.Token.html Retrieves the starting position of the token. ```APIDOC ### pub fn start_position(&self) -> Position The position a token begins at. ``` -------------------------------- ### Get first pair Source: https://docs.rs/full_moon/latest/full_moon/ast/punctuated/struct.Punctuated.html Retrieves a reference to the first pair in the sequence. ```rust let mut punctuated = Punctuated::new(); assert_eq!(punctuated.first(), None); punctuated.push(Pair::new(1, None)); assert_eq!(punctuated.first(), Some(&Pair::new(1, None))); ``` -------------------------------- ### Trim start patterns from strings Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Removes prefixes matching a pattern from a string slice. ```rust assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); ``` -------------------------------- ### VisitorMut Trait Methods Source: https://docs.rs/full_moon/latest/full_moon/visitors/trait.VisitorMut.html A collection of visitor methods for mutable AST node traversal, including start and end visit hooks for various syntax elements. ```rust fn visit_table_constructor( &mut self, node: TableConstructor, ) -> TableConstructor { ... } fn visit_table_constructor_end( &mut self, node: TableConstructor, ) -> TableConstructor { ... } fn visit_token_reference(&mut self, node: TokenReference) -> TokenReference { ... } fn visit_token_reference_end( &mut self, node: TokenReference, ) -> TokenReference { ... } fn visit_un_op(&mut self, node: UnOp) -> UnOp { ... } fn visit_un_op_end(&mut self, node: UnOp) -> UnOp { ... } fn visit_var(&mut self, node: Var) -> Var { ... } fn visit_var_end(&mut self, node: Var) -> Var { ... } fn visit_var_expression(&mut self, node: VarExpression) -> VarExpression { ... } fn visit_var_expression_end(&mut self, node: VarExpression) -> VarExpression { ... } fn visit_while(&mut self, node: While) -> While { ... } fn visit_while_end(&mut self, node: While) -> While { ... } fn visit_luau_attribute(&mut self, node: LuauAttribute) -> LuauAttribute { ... } fn visit_luau_attribute_end(&mut self, node: LuauAttribute) -> LuauAttribute { ... } fn visit_const_assignment( &mut self, node: ConstAssignment, ) -> ConstAssignment { ... } fn visit_const_assignment_end( &mut self, node: ConstAssignment, ) -> ConstAssignment { ... } fn visit_const_function(&mut self, node: ConstFunction) -> ConstFunction { ... } fn visit_const_function_end(&mut self, node: ConstFunction) -> ConstFunction { ... } fn visit_else_if_expression( &mut self, node: ElseIfExpression, ) -> ElseIfExpression { ... } fn visit_else_if_expression_end( &mut self, node: ElseIfExpression, ) -> ElseIfExpression { ... } fn visit_exported_type_declaration( &mut self, node: ExportedTypeDeclaration, ) -> ExportedTypeDeclaration { ... } fn visit_exported_type_declaration_end( &mut self, node: ExportedTypeDeclaration, ) -> ExportedTypeDeclaration { ... } fn visit_exported_type_function( &mut self, node: ExportedTypeFunction, ) -> ExportedTypeFunction { ... } fn visit_exported_type_function_end( &mut self, node: ExportedTypeFunction, ) -> ExportedTypeFunction { ... } fn visit_generic_declaration( &mut self, node: GenericDeclaration, ) -> GenericDeclaration { ... } fn visit_generic_declaration_end( &mut self, node: GenericDeclaration, ) -> GenericDeclaration { ... } fn visit_generic_declaration_parameter( &mut self, node: GenericDeclarationParameter, ) -> GenericDeclarationParameter { ... } fn visit_generic_declaration_parameter_end( &mut self, node: GenericDeclarationParameter, ) -> GenericDeclarationParameter { ... } fn visit_generic_parameter_info( &mut self, node: GenericParameterInfo, ) -> GenericParameterInfo { ... } fn visit_generic_parameter_info_end( &mut self, node: GenericParameterInfo, ) -> GenericParameterInfo { ... } fn visit_if_expression(&mut self, node: IfExpression) -> IfExpression { ... } fn visit_if_expression_end(&mut self, node: IfExpression) -> IfExpression { ... } fn visit_indexed_type_info( &mut self, node: IndexedTypeInfo, ) -> IndexedTypeInfo { ... } fn visit_indexed_type_info_end( &mut self, node: IndexedTypeInfo, ) -> IndexedTypeInfo { ... } fn visit_interpolated_string( &mut self, node: InterpolatedString, ) -> InterpolatedString { ... } fn visit_interpolated_string_end( &mut self, node: InterpolatedString, ) -> InterpolatedString { ... } fn visit_type_argument(&mut self, node: TypeArgument) -> TypeArgument { ... } fn visit_type_argument_end(&mut self, node: TypeArgument) -> TypeArgument { ... } fn visit_type_assertion(&mut self, node: TypeAssertion) -> TypeAssertion { ... } fn visit_type_assertion_end(&mut self, node: TypeAssertion) -> TypeAssertion { ... } fn visit_type_declaration( &mut self, node: TypeDeclaration, ) -> TypeDeclaration { ... } fn visit_type_declaration_end( &mut self, node: TypeDeclaration, ) -> TypeDeclaration { ... } fn visit_type_field(&mut self, node: TypeField) -> TypeField { ... } fn visit_type_field_end(&mut self, node: TypeField) -> TypeField { ... } fn visit_type_field_key(&mut self, node: TypeFieldKey) -> TypeFieldKey { ... } fn visit_type_field_key_end(&mut self, node: TypeFieldKey) -> TypeFieldKey { ... } fn visit_type_function(&mut self, node: TypeFunction) -> TypeFunction { ... } fn visit_type_function_end(&mut self, node: TypeFunction) -> TypeFunction { ... } fn visit_type_info(&mut self, node: TypeInfo) -> TypeInfo { ... } ``` -------------------------------- ### Get last pair Source: https://docs.rs/full_moon/latest/full_moon/ast/punctuated/struct.Punctuated.html Retrieves a reference to the last pair in the sequence. ```rust let mut punctuated = Punctuated::new(); punctuated.push(Pair::new(1, None)); assert_eq!(punctuated.last(), Some(&Pair::new(1, None))); ``` -------------------------------- ### Get Punctuation Source: https://docs.rs/full_moon/latest/full_moon/ast/punctuated/enum.Pair.html Retrieve an optional reference to the trailing punctuation. ```rust let pair = Pair::new(1, None); assert_eq!(pair.punctuation(), None); ``` -------------------------------- ### Trim start whitespace in Rust Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Removes leading whitespace from a string slice. ```rust let s = " עברית "; assert!(Some('ע') == s.trim_start().chars().next()); ``` -------------------------------- ### Get Value Reference Source: https://docs.rs/full_moon/latest/full_moon/ast/punctuated/enum.Pair.html Obtain an immutable reference to the inner value. ```rust let pair = Pair::new(1, None); assert_eq!(pair.value(), &1); ``` -------------------------------- ### Split string with rsplitn Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Splits a string into at most n substrings starting from the end. ```rust let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect(); assert_eq!(v, ["lamb", "little", "Mary had a"]); let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect(); assert_eq!(v, ["leopard", "tiger", "lionX"]); let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect(); assert_eq!(v, ["leopard", "lion::tiger"]); ``` ```rust let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect(); assert_eq!(v, ["ghi", "abc1def"]); ``` -------------------------------- ### ContainedSpan::new Source: https://docs.rs/full_moon/latest/full_moon/ast/span/struct.ContainedSpan.html Creates a new ContainedSpan instance using the provided start and end token references. ```APIDOC ## pub fn new(start: TokenReference, end: TokenReference) -> Self ### Description Creates a contained span from the start and end bounds. ### Parameters - **start** (TokenReference) - The starting token reference. - **end** (TokenReference) - The ending token reference. ### Returns - **Self** - A new instance of ContainedSpan. ``` -------------------------------- ### Goto::new Source: https://docs.rs/full_moon/latest/full_moon/ast/lua52/struct.Goto.html Creates a new Goto instance with the specified label name. ```APIDOC ## pub fn new(label_name: TokenReference) -> Self ### Description Creates a new Goto instance with the given label name. ### Parameters - **label_name** (TokenReference) - Required - The name corresponding to the label. ``` -------------------------------- ### Lexer::new Source: https://docs.rs/full_moon/latest/full_moon/tokenizer/struct.Lexer.html Creates a new Lexer instance from a source string and a specified Lua version. ```APIDOC ## Lexer::new(source: &str, lua_version: LuaVersion) -> Self ### Description Creates a new Lexer from the given source string and Lua version(s). ### Parameters - **source** (&str) - Required - The Lua source code string to tokenize. - **lua_version** (LuaVersion) - Required - The Lua version(s) to parse for. ``` -------------------------------- ### ShortString::new Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Creates a new instance of ShortString from a provided text input. ```APIDOC ## pub fn new<T: Into<String> + AsRef<str>>(text: T) -> Self ### Description Creates a new ShortString from the given text. ### Parameters - **text** (T) - Required - The input text to convert into a ShortString. ``` -------------------------------- ### ContainedSpan::tokens Source: https://docs.rs/full_moon/latest/full_moon/ast/span/struct.ContainedSpan.html Retrieves the start and end token references from the ContainedSpan. ```APIDOC ## pub fn tokens(&self) -> (&TokenReference, &TokenReference) ### Description Returns the start and end bounds of the span as a tuple of references. ### Returns - **(&TokenReference, &TokenReference)** - A tuple containing references to the start and end tokens. ``` -------------------------------- ### Trim prefix and suffix from a string Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Demonstrates chaining trim_prefix and trim_suffix methods. ```rust assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/"); ``` -------------------------------- ### Create a new Punctuated sequence Source: https://docs.rs/full_moon/latest/full_moon/ast/punctuated/struct.Punctuated.html Initializes an empty punctuated sequence. ```rust let mut punctuated: Punctuated<i32> = Punctuated::new(); ``` -------------------------------- ### Get length of Punctuated Source: https://docs.rs/full_moon/latest/full_moon/ast/punctuated/struct.Punctuated.html Returns the number of pairs currently in the sequence. ```rust let mut punctuated = Punctuated::new(); assert_eq!(punctuated.len(), 0); punctuated.push(Pair::new((), None)); assert_eq!(punctuated.len(), 1); ``` -------------------------------- ### Create a new Pair Source: https://docs.rs/full_moon/latest/full_moon/ast/punctuated/enum.Pair.html Instantiate a new Pair with a value and optional punctuation. ```rust let pair = Pair::new(1, None); ``` -------------------------------- ### Token::new Source: https://docs.rs/full_moon/latest/full_moon/tokenizer/struct.Token.html Creates a new token with a zero position. ```APIDOC ### pub fn new(token_type: TokenType) -> Token Creates a token with a zero position. ``` -------------------------------- ### Create a version-specific symbol Source: https://docs.rs/full_moon/latest/full_moon/tokenizer/struct.TokenReference.html Creates a symbol with leading and trailing whitespace, validating it against a specific Lua version. ```rust rust # use full_moon::tokenizer::{Symbol, TokenReference, TokenType, TokenizerErrorType}; # use full_moon::LuaVersion; # fn main() -> Result<(), Box<dyn std::error::Error>> { assert!(TokenReference::symbol_specific_lua_version(“goto”, LuaVersion::lua51()).is_err()); assert!(TokenReference::symbol_specific_lua_version(“goto”, LuaVersion::lua52()).is_ok()); # Ok(()) # } ``` -------------------------------- ### Label::new Source: https://docs.rs/full_moon/latest/full_moon/ast/lua52/struct.Label.html Creates a new Label instance with the specified name. ```APIDOC ### pub fn new(name: TokenReference) -> Self Creates a new Label with the given name. ``` -------------------------------- ### trim_ascii_start Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Returns a string slice with leading ASCII whitespace removed. ```APIDOC ## pub fn trim_ascii_start(&self) -> &str ### Description Returns a string slice with leading ASCII whitespace removed. 'Whitespace' refers to the definition used by `u8::is_ascii_whitespace`. ``` -------------------------------- ### Find match indices with match_indices Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Returns an iterator over disjoint matches and their starting indices. ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` -------------------------------- ### Get Subslice Safely Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Retrieves a subslice of a string using a non-panicking indexing method. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### LuaVersion Methods Source: https://docs.rs/full_moon/latest/full_moon/ast/struct.LuaVersion.html Methods for creating and configuring LuaVersion instances. ```APIDOC ## pub fn new() -> Self Creates a new LuaVersion with the default features: Luau, Lua 5.2, Lua 5.3, and Lua 5.4. ## pub fn lua51() -> Self Creates a new LuaVersion with only Lua 5.1. ## pub fn luau() -> Self Creates a new LuaVersion with only Luau. (Requires feature `luau`) ## pub fn with_luau(self) -> Self Adds Luau as a version to parse for. (Requires feature `luau`) ## pub fn has_luau(self) -> bool Returns true if Luau is enabled. ## pub fn lua52() -> Self Creates a new LuaVersion with only Lua 5.2. (Requires feature `lua52`) ## pub fn with_lua52(self) -> Self Adds Lua 5.2 as a version to parse for. (Requires feature `lua52`) ## pub fn has_lua52(self) -> bool Returns true if Lua 5.2 is enabled. ## pub fn lua53() -> Self Creates a new LuaVersion with only Lua 5.3. (Requires feature `lua53`) ## pub fn with_lua53(self) -> Self Adds Lua 5.3 as a version to parse for. (Requires feature `lua53`) ## pub fn has_lua53(self) -> bool Returns true if Lua 5.3 is enabled. ## pub fn lua54() -> Self Creates a new LuaVersion with only Lua 5.4. (Requires feature `lua54`) ## pub fn with_lua54(self) -> Self Adds Lua 5.4 as a version to parse for. (Requires feature `lua54`) ## pub fn has_lua54(self) -> bool Returns true if Lua 5.4 is enabled. ## pub fn luajit() -> Self Creates a new LuaVersion with only LuaJIT. (Requires feature `luajit`) ## pub fn with_luajit(self) -> Self Adds LuaJIT as a version to parse for. (Requires feature `luajit`) ## pub fn has_luajit(self) -> bool Returns true if LuaJIT is enabled. ## pub fn cfxlua() -> Self Creates a new LuaVersion with CFX Lua. (Requires feature `cfxlua`) ## pub fn with_cfxlua(self) -> Self Adds CFX Lua as a version to parse for. (Requires feature `cfxlua`) ## pub fn has_cfxlua(self) -> bool Returns true if CFX Lua is enabled. ``` -------------------------------- ### Get Raw Pointer Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Retrieves a raw pointer to the first byte of the string slice. ```rust let s = "Hello"; let ptr = s.as_ptr(); ``` -------------------------------- ### Accessing Ast nodes Source: https://docs.rs/full_moon/latest/full_moon/ast/struct.Ast.html Demonstrates how to retrieve the statements from an Ast instance after parsing. ```rust assert_eq!(full_moon::parse("local x = 1; local y = 2")?.nodes().stmts().count(), 2); ``` -------------------------------- ### Get Mutable Value Reference Source: https://docs.rs/full_moon/latest/full_moon/ast/punctuated/enum.Pair.html Obtain a mutable reference to the inner value to modify it. ```rust let mut pair = Pair::new(1, None); *pair.value_mut() += 1; assert_eq!(pair.into_value(), 2); ``` -------------------------------- ### Calculate String Length Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Demonstrates how to calculate the length of a string in bytes versus the number of characters. ```rust let len = "foo".len(); assert_eq!(3, len); assert_eq!("ƒoo".len(), 4); // fancy f! assert_eq!("ƒoo".chars().count(), 3); ``` -------------------------------- ### Lexer Token Navigation and Consumption Source: https://docs.rs/full_moon/latest/full_moon/tokenizer/struct.Lexer.html Methods for interacting with the token stream produced by the Lexer. ```APIDOC ## Lexer Token Methods ### current() Returns the current token. ### peek() Returns the next token without consuming it. ### consume() Consumes the current token and returns the next token. ### collect() Returns a vector of all tokens left in the source string. ### process_next() Processes and returns the next token in the source string, ignoring trivia. ``` -------------------------------- ### Find reverse match indices with rmatch_indices Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Returns an iterator over disjoint matches and their starting indices in reverse order. ```rust let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect(); assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]); let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect(); assert_eq!(v, [(4, "abc"), (1, "abc")]); let v: Vec<_> = "ababa".rmatch_indices("aba").collect(); assert_eq!(v, [(2, "aba")]); // only the last `aba` ``` -------------------------------- ### rsplitn Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Returns an iterator over substrings of the string slice, separated by a pattern, starting from the end, restricted to returning at most n items. ```APIDOC ## pub fn rsplitn<P>(&self, n: usize, pat: P) -> RSplitN<'_, P> ### Description Returns an iterator over substrings of this string slice, separated by a pattern, starting from the end of the string, restricted to returning at most `n` items. ``` -------------------------------- ### Create a TokenReference symbol Source: https://docs.rs/full_moon/latest/full_moon/tokenizer/struct.TokenReference.html Creates a symbol with leading and trailing whitespace. Only whitespace is supported for trivia. ```rust let symbol = TokenReference::symbol("\nreturn ")?; assert_eq!(symbol.leading_trivia().next().unwrap().to_string(), "\n"); assert_eq!(symbol.token().token_type(), &TokenType::Symbol { symbol: Symbol::Return, }); assert_eq!(symbol.trailing_trivia().next().unwrap().to_string(), " "); assert!(TokenReference::symbol("isnt whitespace").is_err()); assert!(TokenReference::symbol(" notasymbol ").is_err()); ``` -------------------------------- ### Get unchecked subslice Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Access a subslice without safety checks. Ensure indices are within bounds and on UTF-8 boundaries to avoid undefined behavior. ```rust let v = "🗻∈🌏"; unsafe { assert_eq!("🗻", v.get_unchecked(0..4)); assert_eq!("∈", v.get_unchecked(4..7)); assert_eq!("🌏", v.get_unchecked(7..11)); } ``` -------------------------------- ### Strip prefix from string Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Removes a prefix exactly once if present, returning an Option. ```rust assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar")); assert_eq!("foo:bar".strip_prefix("bar"), None); assert_eq!("foofoo".strip_prefix("foo"), Some("foo")); ``` -------------------------------- ### Repeat string content Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Creates a new string by repeating the original content n times, noting that it will panic if capacity overflows. ```rust assert_eq!("abc".repeat(4), String::from("abcabcabcabc")); ``` ```rust // this will panic at runtime let huge = "0123456789abcdef".repeat(usize::MAX); ``` -------------------------------- ### TokenReference::new Source: https://docs.rs/full_moon/latest/full_moon/tokenizer/struct.TokenReference.html Creates a new TokenReference instance from leading trivia, the primary token, and trailing trivia. ```APIDOC ## pub fn new(leading_trivia: Vec<Token>, token: Token, trailing_trivia: Vec<Token>) -> Self ### Description Creates a TokenReference from leading/trailing trivia as well as the leading token. ``` -------------------------------- ### Titlecase string transformations Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Demonstrates word_to_titlecase behavior, including handling of non-cased scripts, lack of word segmentation, and complex Greek character casing. ```rust assert_eq!(new_year, new_year.word_to_titlecase()); ``` ```rust #![feature(titlecase)] let georgian = "ერთობაშია"; assert_eq!(georgian, georgian.word_to_titlecase()); ``` ```rust #![feature(titlecase)] let blazingly_fast = "ferris and I"; assert_eq!("Ferris and i", blazingly_fast.word_to_titlecase()); ``` ```rust #![feature(titlecase)] let odysseus = "ὈΔΥΣΣΕΎΣ"; assert_eq!("Ὀδυσσεύς", odysseus.word_to_titlecase()); let odysseus_king_of_ithaca = "Ο ΟΔΥΣΣΈΑΣ ΒΑΣΙΛΙΆΣ ΤΗΣ ΙΘΆΚΗΣ"; assert_eq!("Ο οδυσσέας βασιλιάς της ιθάκης", odysseus_king_of_ithaca.word_to_titlecase()); ``` -------------------------------- ### Using rsplit Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Splits a string and yields substrings in reverse order. ```rust let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect(); assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]); let v: Vec<&str> = "".rsplit('X').collect(); assert_eq!(v, [""]); let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect(); assert_eq!(v, ["leopard", "tiger", "", "lion"]); let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect(); assert_eq!(v, ["leopard", "tiger", "lion"]); ``` ```rust let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect(); assert_eq!(v, ["ghi", "def", "abc"]); ``` -------------------------------- ### Return struct definition Source: https://docs.rs/full_moon/latest/full_moon/ast/struct.Return.html The definition of the Return struct within the full_moon::ast module. ```rust pub struct Return { /* private fields */ } ``` -------------------------------- ### VisitorMut trait methods Source: https://docs.rs/full_moon/latest/full_moon/visitors/trait.VisitorMut.html A collection of visitor methods for mutable node and token processing. ```rust fn visit_type_info_end(&mut self, node: TypeInfo) -> TypeInfo { ... } fn visit_type_instantiation( &mut self, node: TypeInstantiation, ) -> TypeInstantiation { ... } fn visit_type_instantiation_end( &mut self, node: TypeInstantiation, ) -> TypeInstantiation { ... } fn visit_type_intersection( &mut self, node: TypeIntersection, ) -> TypeIntersection { ... } fn visit_type_intersection_end( &mut self, node: TypeIntersection, ) -> TypeIntersection { ... } fn visit_type_specifier(&mut self, node: TypeSpecifier) -> TypeSpecifier { ... } fn visit_type_specifier_end(&mut self, node: TypeSpecifier) -> TypeSpecifier { ... } fn visit_type_union(&mut self, node: TypeUnion) -> TypeUnion { ... } fn visit_type_union_end(&mut self, node: TypeUnion) -> TypeUnion { ... } fn visit_goto(&mut self, node: Goto) -> Goto { ... } fn visit_goto_end(&mut self, node: Goto) -> Goto { ... } fn visit_label(&mut self, node: Label) -> Label { ... } fn visit_label_end(&mut self, node: Label) -> Label { ... } fn visit_attribute(&mut self, node: Attribute) -> Attribute { ... } fn visit_attribute_end(&mut self, node: Attribute) -> Attribute { ... } fn visit_compound_assignment( &mut self, node: CompoundAssignment, ) -> CompoundAssignment { ... } fn visit_compound_assignment_end( &mut self, node: CompoundAssignment, ) -> CompoundAssignment { ... } fn visit_compound_op(&mut self, node: CompoundOp) -> CompoundOp { ... } fn visit_compound_op_end(&mut self, node: CompoundOp) -> CompoundOp { ... } fn visit_identifier(&mut self, token: Token) -> Token { ... } fn visit_multi_line_comment(&mut self, token: Token) -> Token { ... } fn visit_number(&mut self, token: Token) -> Token { ... } fn visit_single_line_comment(&mut self, token: Token) -> Token { ... } fn visit_string_literal(&mut self, token: Token) -> Token { ... } fn visit_symbol(&mut self, token: Token) -> Token { ... } fn visit_token(&mut self, token: Token) -> Token { ... } fn visit_whitespace(&mut self, token: Token) -> Token { ... } fn visit_interpolated_string_segment(&mut self, token: Token) -> Token { ... } fn visit_c_style_comment(&mut self, token: Token) -> Token { ... } } ``` -------------------------------- ### Implement a Custom Visitor Source: https://docs.rs/full_moon/latest/full_moon/visitors/trait.Visitor.html Create a struct that implements the Visitor trait to track specific AST elements, such as local variable assignments. ```rust // A visitor that logs every local assignment made #[derive(Default)] struct LocalVariableVisitor { names: Vec<String>, } impl Visitor for LocalVariableVisitor { fn visit_local_assignment(&mut self, local_assignment: &ast::LocalAssignment) { self.names.extend(&mut local_assignment.names().iter().map(|name| name.token().to_string())); } } let mut visitor = LocalVariableVisitor::default(); visitor.visit_ast(&full_moon::parse("local x = 1; local y, z = 2, 3")?); assert_eq!(visitor.names, vec!["x", "y", "z"]); ``` -------------------------------- ### Goto Accessors Source: https://docs.rs/full_moon/latest/full_moon/ast/lua52/struct.Goto.html Methods to retrieve the components of the Goto statement. ```APIDOC ## pub fn goto_token(&self) -> &TokenReference ### Description Returns the `goto` symbol in the statement. ## pub fn label_name(&self) -> &TokenReference ### Description Returns the name corresponding to the label part of the statement. ``` -------------------------------- ### ShortString::as_str Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Returns a string slice representation of the ShortString. ```APIDOC ## pub fn as_str(&self) -> &str ### Description Returns a &str representation of the ShortString. ``` -------------------------------- ### Using split_inclusive Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Splits a string while keeping the matched pattern as a terminator for each substring. ```rust let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb." .split_inclusive('\n').collect(); assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]); ``` ```rust let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n" .split_inclusive('\n').collect(); assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]); ``` -------------------------------- ### parse Source: https://docs.rs/full_moon/latest/full_moon/all.html Parses a string of Lua or Luau code into an AST. ```APIDOC ## parse(input: &str) -> Ast ### Description Parses the provided Lua or Luau source code string into an `Ast` structure. This is the primary entry point for converting source code into a manipulatable AST. ### Parameters - **input** (&str) - Required - The Lua or Luau source code to parse. ``` -------------------------------- ### Parse a punctuated sequence Source: https://docs.rs/full_moon/latest/full_moon/ast/punctuated/index.html Demonstrates how a punctuated sequence is identified within a parsed AST. ```rust let ast = parse("call(arg1, arg2, arg3)")?; // ^^^^^ ~~~~~ ^^^^^ ``` -------------------------------- ### VarExpression Definition Source: https://docs.rs/full_moon/latest/full_moon/ast/struct.VarExpression.html The basic structure definition for VarExpression. ```rust pub struct VarExpression { /* private fields */ } ``` -------------------------------- ### Asserting split behavior Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Demonstrates an assertion for a split operation. ```rust assert_eq!(d, &["a", "b", "c"]); ``` -------------------------------- ### pub fn parse(code: &str) -> Result<Ast, Vec<Error>> Source: https://docs.rs/full_moon/latest/full_moon/fn.parse.html Parses a string of Lua code into an AST. It utilizes the most complete set of Lua versions enabled by the current feature set. ```APIDOC ## Function: parse ### Description Creates an `Ast` from Lua code. Will use the most complete set of Lua versions enabled in your feature set. ### Signature `pub fn parse(code: &str) -> Result<Ast, Vec<Error>>` ### Parameters - **code** (&str) - Required - The Lua source code string to be parsed. ### Errors - If the code cannot be tokenized, a `TokenizerError` is returned. - If the code is not valid Lua 5.1 code, an `AstError` (specifically `AstError::UnexpectedToken`) is returned. ### Example ```rust assert!(full_moon::parse("local x = 1").is_ok()); assert!(full_moon::parse("local x = ").is_err()); ``` ``` -------------------------------- ### strip_prefix<P>(&self, prefix: P) -> Option<&str> Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Removes a prefix from the string slice exactly once if it matches, returning the remaining substring. ```APIDOC ## strip_prefix<P>(&self, prefix: P) -> Option<&str> ### Description Returns a string slice with the prefix removed. If the string starts with the pattern `prefix`, returns the substring after the prefix, wrapped in `Some`. If the string does not start with `prefix`, returns `None`. ### Parameters - **prefix** (Pattern) - Required - The pattern to match at the start of the string (e.g., &str, char, slice of chars, or closure). ``` -------------------------------- ### Convert string to lowercase Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Returns a new String with the lowercase equivalent of the input, handling Unicode rules. ```rust let s = "HELLO WORLD"; assert_eq!("hello world", s.to_lowercase()); ``` ```rust let sigma = "Σ"; assert_eq!("σ", sigma.to_lowercase()); // but at the end of a word, it's ς, not σ: let odysseus = "ὈΔΥΣΣΕΎΣ"; assert_eq!("ὀδυσσεύς", odysseus.to_lowercase()); let odysseus_king_of_ithaca = "Ο ΟΔΥΣΣΈΑΣ ΒΑΣΙΛΙΆΣ ΤΗΣ ΙΘΆΚΗΣ"; assert_eq!("ο οδυσσέας βασιλιάς της ιθάκης", odysseus_king_of_ithaca.to_lowercase()); ``` ```rust let new_year = "农历新年"; assert_eq!(new_year, new_year.to_lowercase()); ``` -------------------------------- ### Strip suffix from string Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Removes a suffix exactly once if present, returning an Option. ```rust assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar")); assert_eq!("bar:foo".strip_suffix("bar"), None); assert_eq!("foofoo".strip_suffix("foo"), Some("foo")); ``` -------------------------------- ### Trim left whitespace (Deprecated) Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Deprecated method for removing leading whitespace. Use trim_start instead. ```rust let s = " Hello\tworld\t"; assert_eq!("Hello\tworld\t", s.trim_left()); ``` ```rust let s = " English"; assert!(Some('E') == s.trim_left().chars().next()); let s = " עברית"; assert!(Some('ע') == s.trim_left().chars().next()); ``` -------------------------------- ### pub fn split_whitespace(&self) -> SplitWhitespace<'_> Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Splits a string slice by Unicode whitespace. ```APIDOC ## pub fn split_whitespace(&self) -> SplitWhitespace<'_> ### Description Splits a string slice by whitespace defined according to the Unicode Derived Core Property `White_Space`. The iterator returns sub-slices of the original string. ``` -------------------------------- ### Trim leading whitespace with trim_start Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Removes leading whitespace from a string slice based on byte position. ```rust let s = "\n Hello\tworld\t\n"; assert_eq!("Hello\tworld\t\n", s.trim_start()); ``` ```rust let s = " English "; assert!(Some('E') == s.trim_start().chars().next()); ``` -------------------------------- ### pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Splits a string slice by ASCII whitespace. ```APIDOC ## pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> ### Description Splits a string slice by ASCII whitespace, using the same definition as `char::is_ascii_whitespace`. The iterator returns sub-slices of the original string. ``` -------------------------------- ### Check string suffix Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Verifies if the string ends with a specific pattern. ```rust let bananas = "bananas"; assert!(bananas.ends_with("anas")); assert!(!bananas.ends_with("nana")); ``` -------------------------------- ### Find pattern index Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Returns the byte index of the first occurrence of a pattern. ```rust let s = "Löwe 老虎 Léopard Gepardi"; assert_eq!(s.find('L'), Some(0)); assert_eq!(s.find('é'), Some(14)); assert_eq!(s.find("pard"), Some(17)); ``` ```rust let s = "Löwe 老虎 Léopard"; assert_eq!(s.find(char::is_whitespace), Some(5)); assert_eq!(s.find(char::is_lowercase), Some(1)); assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1)); assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4)); ``` ```rust let s = "Löwe 老虎 Léopard"; let x: &[_] = &['1', '2']; assert_eq!(s.find(x), None); ``` -------------------------------- ### trim_prefix<P>(&self, prefix: P) -> &str Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Removes an optional prefix from the string slice, returning the original string if no match is found. ```APIDOC ## trim_prefix<P>(&self, prefix: P) -> &str ### Description Returns a string slice with the optional prefix removed. If the string starts with `prefix`, returns the substring after the prefix. If not, returns the original string. This is a nightly-only experimental API. ### Parameters - **prefix** (Pattern) - Required - The pattern to match at the start. ``` -------------------------------- ### Check Character Boundaries Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Verifies if a specific byte index corresponds to a valid UTF-8 character boundary. ```rust let s = "Löwe 老虎 Léopard"; assert!(s.is_char_boundary(0)); // start of `老` assert!(s.is_char_boundary(6)); assert!(s.is_char_boundary(s.len())); // second byte of `ö` assert!(!s.is_char_boundary(2)); // third byte of `老` assert!(!s.is_char_boundary(8)); ``` -------------------------------- ### Demonstrate lack of NFC normalization Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Shows that visually identical strings with different codepoint representations are not considered equal by the unnormalized comparison. ```rust #![feature(casefold)] // These two strings are visually and semantically identical... let comp = "Å"; let decomp = "Å"; // ... but not codepoint-for-codepoint equal. assert_eq!(comp, "\u{C5}"); assert_eq!(decomp, "A\u{030A}"); ``` -------------------------------- ### Parse Lua code into an Ast Source: https://docs.rs/full_moon/latest/full_moon/fn.parse.html Demonstrates basic usage of the parse function to validate Lua code strings. Returns an error if the input is not valid Lua. ```rust assert!(full_moon::parse("local x = 1").is_ok()); assert!(full_moon::parse("local x = ").is_err()); ``` -------------------------------- ### Trim left matches (Deprecated) Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Removes prefixes matching patterns; superseded by trim_start_matches. ```rust assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12"); ``` -------------------------------- ### ShortString::is_empty Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Checks if the ShortString contains no data. ```APIDOC ## pub fn is_empty(&self) -> bool ### Description Returns whether or not the ShortString is empty. ``` -------------------------------- ### Goto Modifiers Source: https://docs.rs/full_moon/latest/full_moon/ast/lua52/struct.Goto.html Methods to return a new Goto instance with modified fields. ```APIDOC ## pub fn with_goto_token(self, goto_token: TokenReference) -> Self ### Description Returns a new Goto instance with the specified `goto` symbol. ## pub fn with_label_name(self, label_name: TokenReference) -> Self ### Description Returns a new Goto instance with the specified label name. ``` -------------------------------- ### pub fn bytes(&self) -> Bytes<'_> Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Returns an iterator over the bytes of a string slice. ```APIDOC ## pub fn bytes(&self) -> Bytes<'_> ### Description Returns an iterator over the bytes of a string slice. As a string slice consists of a sequence of bytes, this method returns an iterator to traverse them. ``` -------------------------------- ### Convert to Byte Slice Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Converts a string slice into a byte slice. ```rust let bytes = "bors".as_bytes(); assert_eq!(b"bors", bytes); ``` -------------------------------- ### Symbol::from_str Source: https://docs.rs/full_moon/latest/full_moon/tokenizer/enum.Symbol.html Parses a symbol from a string given a specific Lua version. ```APIDOC ## Symbol::from_str(symbol: &str, lua_version: LuaVersion) -> Option<Self> ### Description Given the symbol text (without whitespace) and the target Lua version, this method returns the associated Symbol if it exists. If the symbol is not valid for the provided Lua version, it returns None. ### Parameters - **symbol** (&str) - The string representation of the symbol. - **lua_version** (LuaVersion) - The Lua version context used to validate the symbol. ### Returns - **Option<Self>** - The corresponding Symbol variant if found, otherwise None. ``` -------------------------------- ### to_ascii_uppercase Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Returns a copy of the string where each ASCII character is mapped to its uppercase equivalent. ```APIDOC ## pub fn to_ascii_uppercase(&self) -> String ### Description Returns a copy of this string where each character is mapped to its ASCII upper case equivalent. ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged. ### Returns - **String** - A new string with ASCII characters converted to uppercase. ``` -------------------------------- ### Convert word to titlecase Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Experimental API that converts a single word to titlecase by uppercasing the first cased letter. ```rust #![feature(titlecase)] let s = "HELLO WORLD"; assert_eq!("Hello world", s.word_to_titlecase()); ``` ```rust #![feature(titlecase)] let the_night_before_christmas = "'twas"; assert_eq!("'Twas", the_night_before_christmas.word_to_titlecase()); ``` ```rust #![feature(titlecase)] let new_year = "农历新年"; ``` -------------------------------- ### Escape characters with default formatting Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Escapes characters using standard default escaping rules. ```rust for c in "❤\n!".escape_default() { print!("{c}"); } println!(); ``` ```rust println!("{}", "❤\n!".escape_default()); ``` ```rust println!("\\u{2764}\\n!"); ``` ```rust assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!"); ``` -------------------------------- ### Split string with splitn Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Splits a string into at most n substrings using a pattern. ```rust let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect(); assert_eq!(v, ["Mary", "had", "a little lambda"]); let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect(); assert_eq!(v, ["lion", "", "tigerXleopard"]); let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect(); assert_eq!(v, ["abcXdef"]); let v: Vec<&str> = "".splitn(1, 'X').collect(); assert_eq!(v, [""]); ``` ```rust let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect(); assert_eq!(v, ["abc", "defXghi"]); ``` -------------------------------- ### TokenReference Methods Source: https://docs.rs/full_moon/latest/full_moon/tokenizer/struct.TokenReference.html Methods available on the TokenReference struct to access token metadata. ```APIDOC ## pub fn start_position(&self) -> Position ### Description Returns the position where the token begins. ## pub fn end_position(&self) -> Position ### Description Returns the position where the token ends. ## pub fn token_type(&self) -> &TokenType ### Description Returns the type of the token, including any associated data. Use this if you need detailed information about the token. ## pub fn token_kind(&self) -> TokenKind ### Description Returns the kind of the token without additional data. Use this for a lightweight check if you do not need identifier names or other metadata. ``` -------------------------------- ### ShortString::len Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Returns the length of the ShortString in bytes. ```APIDOC ## pub fn len(&self) -> usize ### Description Returns the length of the ShortString. ``` -------------------------------- ### Split string once Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Splits a string on the first occurrence of a delimiter. ```rust assert_eq!("cfg".split_once('='), None); assert_eq!("cfg=".split_once('='), Some(("cfg", ""))); assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo"))); assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar"))); ``` -------------------------------- ### Trim prefix nightly API Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Removes an optional prefix, returning the original string if the prefix is absent. Requires the trim_prefix_suffix feature. ```rust #![feature(trim_prefix_suffix)] // Prefix present - removes it assert_eq!("foo:bar".trim_prefix("foo:"), "bar"); assert_eq!("foofoo".trim_prefix("foo"), "foo"); // Prefix absent - returns original string assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar"); // Method chaining example assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/"); ``` -------------------------------- ### Floor Character Boundary Source: https://docs.rs/full_moon/latest/full_moon/struct.ShortString.html Finds the closest valid UTF-8 character boundary not exceeding a given index. ```rust let s = "❤️🧡💛💚💙💜"; assert_eq!(s.len(), 26); assert!(!s.is_char_boundary(13)); let closest = s.floor_char_boundary(13); assert_eq!(closest, 10); assert_eq!(&s[..closest], "❤️🧡"); ``` -------------------------------- ### spaces Source: https://docs.rs/full_moon/latest/full_moon/tokenizer/enum.TokenType.html Creates a whitespace TokenType consisting of a specified number of spaces. ```APIDOC ## pub fn spaces(spaces: usize) -> Self ### Description Returns a whitespace `TokenType` consisting of spaces. ``` -------------------------------- ### While struct definition Source: https://docs.rs/full_moon/latest/full_moon/ast/struct.While.html The definition of the While struct as it appears in the full_moon AST. ```rust pub struct While { /* private fields */ } ``` -------------------------------- ### Position Methods Source: https://docs.rs/full_moon/latest/full_moon/tokenizer/struct.Position.html Methods available on the Position struct to access coordinate information. ```APIDOC ## pub fn bytes(self) -> usize ### Description Returns the number of bytes, ignoring lines, required to find this position. ## pub fn character(self) -> usize ### Description Returns the index of the character on the line for this position. ## pub fn line(self) -> usize ### Description Returns the line number where the position lies. ``` -------------------------------- ### Define Block struct Source: https://docs.rs/full_moon/latest/full_moon/ast/struct.Block.html The structure definition for a block of statements. ```rust pub struct Block { /* private fields */ } ```