### BarkML Configuration Parsing Example Source: https://docs.rs/barkml/latest/barkml Demonstrates how to parse a BarkML configuration string into a statement using the `barkml::from_str` function. This example shows basic usage for loading configuration data. ```rust use barkml::from_str; let config = r#"#; versioning = "1.0.0" [database] host = "localhost" port = 5432 #"#; let statement = from_str(config).expect("Failed to parse BarkML"); ``` -------------------------------- ### BarkML Configuration Parsing Example Source: https://docs.rs/barkml/latest/barkml/index Demonstrates how to parse a BarkML configuration string into a statement using the `barkml::from_str` function. This example shows basic usage for loading configuration data. ```rust use barkml::from_str; let config = r#"#; versioning = "1.0.0" [database] host = "localhost" port = 5432 #"#; let statement = from_str(config).expect("Failed to parse BarkML"); ``` -------------------------------- ### StandardLoaderBuilder Initialization Source: https://docs.rs/barkml/latest/barkml/struct.StandardLoaderBuilder Example of initializing and configuring the StandardLoaderBuilder in Rust. ```Rust use barkml::load::standard::StandardLoaderBuilder; fn main() { let loader = StandardLoaderBuilder::new() .resolve_macros(true) .allow_collisions(false) .add_search_path("/path/to/models") .max_recursion_depth(10) .validate_on_load(true) .build(); match loader { Ok(l) => { println!("Loader built successfully!"); // Use the loader 'l' }, Err(e) => { eprintln!("Failed to build loader: {}", e); } } } ``` -------------------------------- ### StandardLoaderBuilder Usage Example Source: https://docs.rs/barkml/latest/src/barkml/load/standard.rs Demonstrates how to use the `StandardLoaderBuilder` to configure and create a `StandardLoader` instance with specific settings. ```Rust let loader = StandardLoader::builder() .resolve_macros(false) .allow_collisions(true) .validate_on_load(true) .build(); assert!(!loader.config.resolve_macros); assert!(loader.config.allow_collisions); assert!(loader.config.validate_on_load); ``` -------------------------------- ### Serialization Examples (Rust Tests) Source: https://docs.rs/barkml/latest/src/barkml/ser/mod.rs Demonstrates the serialization of various Rust data types to BarkML `Value` using the `to_value` function. Includes examples for primitive types (string, integer, boolean, float), arrays, and maps, showcasing the library's versatility. ```rust #[cfg(test)] mod tests { // External crates use indexmap::IndexMap; use serde::{Deserialize, Serialize}; // Parent module use super::*; // Local crate use crate::de::from_value; #[derive(Debug, PartialEq, Deserialize, Serialize)] struct TestConfig { version: String, debug: bool, port: u16, timeout: f64, } #[derive(Debug, PartialEq, Deserialize, Serialize)] struct DatabaseConfig { host: String, port: u16, ssl: bool, } #[derive(Debug, PartialEq, Deserialize, Serialize)] struct AppConfig { app_name: String, database: DatabaseConfig, features: Vec, } #[test] fn serialize_simple_values_works_correctly() { // Arrange & Act - Test string let value = to_value(&"test".to_string()).expect("should serialize string"); // Assert if let crate::Data::String(s) = &value.data { assert_eq!(s, "test"); } else { panic!("Expected string value"); } // Arrange & Act - Test integer let value = to_value(&42i32).expect("should serialize integer"); // Assert if let crate::Data::I32(n) = &value.data { assert_eq!(*n, 42); } else { panic!("Expected i32 value"); } // Arrange & Act - Test boolean let value = to_value(&true).expect("should serialize boolean"); // Assert if let crate::Data::Bool(b) = &value.data { assert!(*b); } else { panic!("Expected boolean value"); } // Arrange & Act - Test float let value = to_value(&3.14f64).expect("should serialize float"); // Assert if let crate::Data::F64(f) = &value.data { assert_eq!(*f, 3.14); } else { panic!("Expected f64 value"); } } #[test] fn serialize_array_works_correctly() { // Arrange let array = vec![ "first".to_string(), "second".to_string(), "third".to_string(), ]; // Act let value = to_value(&array).expect("should serialize array"); // Assert - Check that we can deserialize it back let deserialized: Vec = from_value(&value).expect("should deserialize back"); assert_eq!(deserialized, array); } #[test] fn serialize_map_works_correctly() { // Arrange let mut map = IndexMap::new(); ``` -------------------------------- ### Statement Construction Example Source: https://docs.rs/barkml/latest/src/barkml/load/standard.rs Illustrates the creation of complex `Statement` structures, including nested assignments, control statements, and version values, often used in configuration or module definitions. ```Rust let statement = Statement::new_module( ".", IndexMap::from([ ( "tire".into(), Statement::new_control( "tire", None, Value::new_version( Version::new(1, 0, 0), Metadata { location: Location::default(), comment: None, label: Some("Test".into()), }, ), Metadata::default(), ) .unwrap(), ), ( "section-1".into(), Statement::new_section( "section-1", IndexMap::from([ ( "number".into(), Statement::new_assign( "number", None, Value::new_int(4, Metadata::default()), Metadata { location: Location::default(), comment: None, label: None, }, ), ), ]), Metadata::default(), ) ), ]), Metadata::default(), ); // Further assertions or usage of the created statement would follow here. ``` -------------------------------- ### Rust: Load Multiple Modules Sequentially Source: https://docs.rs/barkml/latest/src/barkml/load/standard.rs Demonstrates loading multiple modules sequentially using `StandardLoader` in Rust. This example appends data from different files, verifying that elements from all loaded modules are accessible. ```rust #[test] pub fn load_multiple() { let mut loader = StandardLoader::default(); loader .add_module( "main", &mut std::io::Cursor::new(include_str!("../../examples/append.d/00-first.bml")), None, ) .unwrap() .add_module( "main", &mut std::io::Cursor::new(include_str!("../../examples/append.d/01-second.bml")), None, ) .unwrap(); let result = loader.load().unwrap(); assert!(result.find_by_path("section-1.number").is_some()); assert!(result.find_by_path("section-2.number").is_some()); } ``` -------------------------------- ### Generic Blanket Trait Implementations Source: https://docs.rs/barkml/latest/barkml/ser/struct.SerializeVec Provides examples of blanket implementations for common Rust traits like Any, Borrow, BorrowMut, From, and Into. These are generic implementations that apply to many types, showcasing fundamental Rust programming patterns. ```APIDOC Generic Blanket Implementations: impl Any for T where T: 'static + ?Sized - fn type_id(&self) -> TypeId - Gets the TypeId of self. impl Borrow for T where T: ?Sized - fn borrow(&self) -> &T - Immutably borrows from an owned value. impl BorrowMut for T where T: ?Sized - fn borrow_mut(&mut self) -> &mut T - Mutably borrows from an owned value. impl From for T - fn from(t: T) -> T - Returns the argument unchanged. impl Into for T - (No specific method shown in this snippet, but implies conversion capabilities) ``` -------------------------------- ### Rust Walk: Access and Retrieve Fields Source: https://docs.rs/barkml/latest/src/barkml/load/walk.rs Demonstrates how to check for the existence of fields using `has_field` and retrieve their values using the `get` method. It covers successful retrieval and handling of non-existent fields. ```rust #[test] fn test_field_access() { let stmt = create_test_statement(); let walker = Walk::new(&stmt); assert!(walker.has_field("test_field")); assert!(!walker.has_field("nonexistent")); let value: String = walker.get("test_field").unwrap(); assert_eq!(value, "test_value"); } ``` -------------------------------- ### barkml Statement Get Value Source: https://docs.rs/barkml/latest/barkml/struct.Statement Retrieves the associated value from a statement, specifically intended for assignment statements. ```APIDOC get_value() -> Option<&Value> - Gets the value for assignment statements. - Returns: An Option containing a reference to the Value if present, otherwise None. ``` -------------------------------- ### StandardLoader Initialization and Loading Source: https://docs.rs/barkml/latest/barkml/struct.StandardLoader Details the initialization of the StandardLoader and the primary function for loading BarkML configurations. This includes loading the main module with auto-discovery and reading all configuration files. ```APIDOC pub fn main

(&mut self, name: &[str], search_paths: Vec

) -> Result<&mut Self, Error> Loads the main module with auto-discovery in search paths. Parameters: name: The name of the main module. search_paths: A vector of paths to search for modules. Returns: A Result containing a mutable reference to Self on success, or an Error on failure. Constraints: P must implement AsRef. pub fn read(&self) -> Result Reads all BarkML configuration files according to the loader’s configuration and returns the resulting module statement. Returns: A Result containing the root Statement on success, or an Error on failure. pub fn load(&self) -> Result Loads everything into a module statement and resolves macros if enabled. Returns: A Result containing the root Statement on success, or an Error on failure. ``` -------------------------------- ### barkml Parser API Documentation Source: https://docs.rs/barkml/latest/barkml/struct.Parser Comprehensive API documentation for the barkml Parser struct, covering its methods for initialization and parsing. Includes details on parameters, return types, and usage context. ```APIDOC Parser Struct Methods: new(name: &[str], lexer: Lexer<'source, Token>) -> Self - Creates a new parser instance. - Parameters: - name: A string slice representing the name. - lexer: A Lexer instance from the 'logos' crate, configured with 'Token' type. - Returns: A new Parser instance. with_file_path(name: &[str], file_path: &[str], lexer: Lexer<'source, Token>) -> Self - Creates a new parser instance with file path information. - Description: Create a new parser with file path information. - Parameters: - name: A string slice representing the name. - file_path: A string slice representing the path to the file being parsed. - lexer: A Lexer instance from the 'logos' crate, configured with 'Token' type. - Returns: A new Parser instance with file path context. parse(&mut self) -> Result - Parses the input provided by the lexer. - Parameters: - self: A mutable reference to the Parser instance. - Returns: A Result containing either a Statement on success or an Error on failure. - Statement: The parsed statement structure. - Error: The error type from the barkml crate. ``` -------------------------------- ### BarkML Crate Structure Overview Source: https://docs.rs/barkml/latest/barkml Provides an overview of the BarkML crate's internal structure, listing key modules and structs. This helps users understand the library's organization and available components. ```APIDOC BarkML Crate Structure: Modules: - barkml::de: Serde deserialization support for BarkML AST nodes. - barkml::ser: Serde serialization support for BarkML AST nodes. - barkml::utils: Utility functions for working with BarkML files and paths. Structs: - barkml::LoadStats: Statistics about the loading process. - barkml::LoaderConfig: Configuration options for loaders. - barkml::Location: Represents a location in the source code. - barkml::Metadata: Stores the metadata associated with a value or statement. - barkml::Parser: Core parser for BarkML syntax. - barkml::Scope: Manages macro resolution and symbol references. - barkml::StandardLoader: Standard loader for BarkML files. - barkml::StandardLoaderBuilder: Builder pattern for StandardLoader. - barkml::Statement: Represents top-level statements and groupings. - barkml::Value: Represents an individual value in the BarkML language. ``` -------------------------------- ### Get Type ID Source: https://docs.rs/barkml/latest/barkml/enum.Error Retrieves the `TypeId` of the implementing type. This is part of the `Any` trait and is used for runtime type identification. ```Rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Get Child Count (Rust) Source: https://docs.rs/barkml/latest/barkml/enum.Walk Returns the number of children or fields present in the current scope. Returns a `usize` value. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### StandardLoader Initialization and Stats Source: https://docs.rs/barkml/latest/barkml/struct.StandardLoader Provides methods for creating a new StandardLoader instance, either directly or via a builder pattern. It also includes functionality to retrieve loading statistics. ```APIDOC StandardLoader::new(config: LoaderConfig) -> Self Creates a new StandardLoader with the specified configuration. StandardLoader::builder() -> StandardLoaderBuilder Creates a new StandardLoader with a builder pattern. StandardLoader::stats(&self) -> &LoadStats Gets the current loading statistics. ``` -------------------------------- ### Get Blocks by Field (Rust) Source: https://docs.rs/barkml/latest/barkml/enum.Walk Retrieves all blocks associated with a specific field identifier. Returns a `Result` containing an `IndexSet` of strings or an `Error`. ```rust pub fn get_blocks(&self, field: &[str]) -> Result, Error> ``` -------------------------------- ### BarkML Crate Structure Overview Source: https://docs.rs/barkml/latest/barkml/index Provides an overview of the BarkML crate's internal structure, listing key modules and structs. This helps users understand the library's organization and available components. ```APIDOC BarkML Crate Structure: Modules: - barkml::de: Serde deserialization support for BarkML AST nodes. - barkml::ser: Serde serialization support for BarkML AST nodes. - barkml::utils: Utility functions for working with BarkML files and paths. Structs: - barkml::LoadStats: Statistics about the loading process. - barkml::LoaderConfig: Configuration options for loaders. - barkml::Location: Represents a location in the source code. - barkml::Metadata: Stores the metadata associated with a value or statement. - barkml::Parser: Core parser for BarkML syntax. - barkml::Scope: Manages macro resolution and symbol references. - barkml::StandardLoader: Standard loader for BarkML files. - barkml::StandardLoaderBuilder: Builder pattern for StandardLoader. - barkml::Statement: Represents top-level statements and groupings. - barkml::Value: Represents an individual value in the BarkML language. ``` -------------------------------- ### Get All Block Names (Rust) Source: https://docs.rs/barkml/latest/barkml/enum.Walk Retrieves all block names within the current scope. Returns a `Result` containing an `IndexSet` of strings or an `Error`. ```rust pub fn get_all_blocks(&self) -> Result, Error> ``` -------------------------------- ### Parser Structure and Initialization (Rust) Source: https://docs.rs/barkml/latest/src/barkml/syn/parser.rs Defines the Parser struct responsible for processing tokens and building the Abstract Syntax Tree (AST). Includes methods to create new parser instances, initializing with a lexer and optionally file path information. ```rust 10const MAX_RECURSION_DEPTH: usize = 64; 11 12pub struct Parser<'source> { 13 tokens: TokenReader<'source>, 14 /// Current recursion depth for preventing stack overflow 15 recursion_depth: usize, 16} 17 18impl<'source> Parser<'source> { 19 pub fn new(name: &str, lexer: Lexer<'source, Token>) -> Self { 20 Self { 21 tokens: TokenReader { 22 module_name: name.to_string(), 23 lexer: lexer.peekable(), 24 location: Location { 25 module: Some(name.to_string()), 26 line: 0, 27 column: 0, 28 source_text: None, 29 length: 0, 30 file_path: None, 31 }, 32 }, 33 recursion_depth: 0, 34 } 35 } 36 37 /// Create a new parser with file path information 38 pub fn with_file_path(name: &str, file_path: &str, lexer: Lexer<'source, Token>) -> Self { 39 Self { 40 tokens: TokenReader { 41 module_name: name.to_string(), 42 lexer: lexer.peekable(), 43 location: Location { 44 module: Some(name.to_string()), 45 line: 0, 46 column: 0, 47 source_text: None, 48 length: 0, 49 file_path: Some(file_path.to_string()), 50 }, 51 }, 52 recursion_depth: 0, 53 } 54 } 55} ``` -------------------------------- ### Get Section Names (Rust) Source: https://docs.rs/barkml/latest/barkml/enum.Walk Retrieves all section names within the current scope. Returns a `Result` containing an `IndexSet` of strings or an `Error`. ```rust pub fn get_sections(&self) -> Result, Error> ``` -------------------------------- ### BarkML Deserialization API Documentation Source: https://docs.rs/barkml/latest/src/barkml/de/mod.rs API documentation for the BarkML deserialization functions, detailing their purpose, parameters, and return values. ```APIDOC BarkML Deserialization Functions: from_statement(statement: &Statement) -> Result - Deserializes a Rust type `T` from a BarkML `Statement`. - `T` must implement `serde::de::Deserialize`. - Supports deserializing from module, section, block, and assignment statements. - Returns an error if the statement structure doesn't match `T` or if values cannot be converted. from_value(value: &Value) -> Result - Deserializes a Rust type `T` from a BarkML `Value`. - `T` must implement `serde::de::Deserialize`. - Useful for converting individual BarkML values (string, number, boolean) to Rust types. - Returns an error if the value type doesn't match `T` or cannot be converted. ``` -------------------------------- ### Rust: Get Position Source: https://docs.rs/barkml/latest/src/barkml/ast/types.rs Retrieves the human-readable position of the location, represented as a tuple of 1-based line and column numbers. This is a constant function. ```rust /// Get the human-readable position (1-based for display) pub const fn position(&self) -> (usize, usize) { (self.line + 1, self.column + 1) } ``` -------------------------------- ### Get Field Names (Rust) Source: https://docs.rs/barkml/latest/barkml/enum.Walk Retrieves all available field names within the current scope. Returns a `Result` containing a `Vec` of strings or an `Error`. ```rust pub fn field_names(&self) -> Result, Error> ``` -------------------------------- ### StandardLoaderBuilder API Source: https://docs.rs/barkml/latest/barkml/struct.StandardLoaderBuilder Documentation for the StandardLoaderBuilder struct in the barkml crate, detailing its methods for configuring a standard loader. This includes methods for setting search paths, recursion depth, macro resolution, collision handling, and building the loader. ```APIDOC StandardLoaderBuilder: A builder for StandardLoader with a fluent interface. Methods: new() -> Self Creates a new instance of StandardLoaderBuilder. resolve_macros(resolve: bool) -> Self Configures whether to resolve macros during loading. Parameters: resolve: A boolean indicating whether to resolve macros. allow_collisions(allow: bool) -> Self Configures whether to allow collisions during loading. Parameters: allow: A boolean indicating whether to allow collisions. add_search_path(path: impl AsRef) -> Self Adds a directory to the search path for loading. Parameters: path: The directory path to add to the search path. max_recursion_depth(depth: u32) -> Self Sets the maximum recursion depth for loading. Parameters: depth: The maximum recursion depth. validate_on_load(validate: bool) -> Self Configures whether to validate the loaded content. Parameters: validate: A boolean indicating whether to validate on load. build() -> Result Builds the StandardLoader instance based on the configured options. Returns: A Result containing the StandardLoader on success or an error on failure. ``` -------------------------------- ### Get Label by Index (Rust) Source: https://docs.rs/barkml/latest/barkml/enum.Walk Fetches a block label by its index and converts it to the requested type T. Requires T to implement `TryFrom` for `barkml::Value`. ```rust pub fn get_label(&self, index: usize) -> Result where T: TryFrom<&'source Value, Error = Error> ``` -------------------------------- ### BarkML Language Features Source: https://docs.rs/barkml/latest/barkml/index Outlines the core features of the BarkML declarative configuration language. These include its syntax, macro capabilities, character encoding support, and error handling. ```APIDOC BarkML Language Features: - Declarative configuration syntax - Self-referential macro replacements - UTF-8 support by default - Type-safe value handling - Comprehensive error reporting ``` -------------------------------- ### Rust: Get Value Memory Size Source: https://docs.rs/barkml/latest/barkml/struct.Value Calculates and returns the approximate memory footprint of the `Value` instance. This can be used for memory profiling or optimization. ```rust pub fn memory_size(&self) -> usize ``` -------------------------------- ### BarkML Loader Methods Source: https://docs.rs/barkml/latest/barkml/trait.Loader Provides core functionalities for loading and processing BarkML configuration files. Includes methods for reading raw content, loading and resolving macros, and validating the structure. ```APIDOC Loader Trait Methods for StandardLoader: fn read(&self) -> Result Reads all BarkML configuration files according to the loader’s configuration and returns the resulting module statement. This method performs the actual file reading and parsing but does not resolve macros. The returned statement tree may contain unresolved macro references that need to be processed separately. Returns: The parsed module statement, or an error if reading or parsing fails. fn load(&self) -> Result Loads everything into a module statement and resolves macros if enabled. This is the main entry point for loading BarkML content. It reads the content, then optionally resolves macros based on the loader’s configuration. This method provides the complete loading pipeline in a single call. Returns: The fully processed module statement with macros resolved (if enabled), or an error if any step of the loading process fails. fn validate(&self) -> Result<(), Error> Validates the loaded content without fully processing it. This method performs validation checks on the loaded content to ensure it’s well-formed and doesn’t contain obvious errors. It’s useful for quick validation without the overhead of full macro resolution. Returns: `Ok(())` if validation passes, or an error describing the validation failure. ``` -------------------------------- ### BarkML Language Features Source: https://docs.rs/barkml/latest/barkml Outlines the core features of the BarkML declarative configuration language. These include its syntax, macro capabilities, character encoding support, and error handling. ```APIDOC BarkML Language Features: - Declarative configuration syntax - Self-referential macro replacements - UTF-8 support by default - Type-safe value handling - Comprehensive error reporting ``` -------------------------------- ### Rust Any trait type_id method Source: https://docs.rs/barkml/latest/barkml/struct.StandardLoader Gets the TypeId of self. This method is part of the Any trait, providing a way to obtain a unique identifier for a type at runtime. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### barkml Metadata Struct Methods Source: https://docs.rs/barkml/latest/barkml/struct.Metadata Provides constructors and helper methods for the barkml::Metadata struct, allowing creation and querying of metadata details. ```APIDOC impl Metadata pub const fn new(location: Location) -> Self Creates a new Metadata instance with the given location. pub const fn with_details(location: Location, comment: Option, label: Option) -> Self Creates a new Metadata instance with location, comment, and label. pub const fn has_comment(&self) -> bool Returns true if this metadata has a comment. pub const fn has_label(&self) -> bool Returns true if this metadata has a label. pub const fn has_annotations(&self) -> bool Returns true if this metadata has any additional information beyond location. ``` -------------------------------- ### Get Available Paths Source: https://docs.rs/barkml/latest/barkml/struct.Scope Returns a vector containing references to all available String paths within the symbol table. This helps in enumerating accessible elements in the scope. ```APIDOC pub fn available_paths(&self) -> Vec<&String> - Returns all available paths in the symbol table. - The returned value is a vector of references to String paths. ``` -------------------------------- ### Loader Trait API Documentation Source: https://docs.rs/barkml/latest/barkml/trait.Loader Comprehensive API documentation for the Loader trait methods, detailing their purpose, parameters, return values, and usage. ```APIDOC Loader Trait Methods: - is_resolution_enabled(&self) -> bool - Purpose: Checks if macro resolution is enabled for this loader. - Description: When enabled, macros in the loaded content will be resolved and replaced with their actual values during the loading process. - Returns: `true` if macro resolution is enabled, `false` otherwise. - skip_macro_resolution(&mut self) -> Result<&mut Self, Error> - Purpose: Disables macro resolution for this loader. - Description: When disabled, macros in the loaded content will remain as-is, allowing for manual resolution later or inspection of the raw macro references. - Parameters: - `self`: A mutable reference to the loader instance. - Returns: A mutable reference to self for method chaining, or an error if the operation cannot be completed. - read(&self) -> Result - Purpose: Reads BarkML content from the source. - Description: This method is responsible for fetching the raw BarkML data. The specific source and format depend on the implementation. - Returns: A `Result` containing the parsed `Statement` on success, or an `Error` on failure. - load(&self) -> Result - Purpose: Loads and processes BarkML content. - Description: This provided method likely orchestrates the reading and potential resolution of BarkML content into a usable `Statement`. - Returns: A `Result` containing the loaded `Statement` on success, or an `Error` on failure. - validate(&self) -> Result<(), Error> - Purpose: Validates the loaded BarkML content. - Description: This provided method checks the integrity and correctness of the BarkML data after loading. - Returns: A `Result` indicating success (`()`) or an `Error` if validation fails. ``` -------------------------------- ### Get Backtrace from Error Source: https://docs.rs/barkml/latest/barkml/enum.Error Retrieves an optional backtrace associated with an error. This method is useful for debugging by providing a snapshot of the call stack at the point the error occurred. ```Rust fn backtrace(&self) -> Option<&Backtrace> ``` -------------------------------- ### barkml utils Module Functions Source: https://docs.rs/barkml/latest/barkml/utils/index Documentation for utility functions in the barkml crate's 'utils' module. These functions assist in handling BarkML-specific file paths and directories. ```APIDOC Module utils Utility functions for working with BarkML files and paths. Functions: basename(path: &str) -> &str Extracts the basename (filename without extension) from a path. discover_files(dir: &str) -> Result, snafu::Error> Discovers BarkML files in a directory. Returns a vector of file paths. is_barkml_dir(path: &str) -> bool Checks if a path represents a BarkML directory (ends with '.d'). is_barkml_file(path: &str) -> bool Checks if a path represents a BarkML file. validate_path(path: &str) -> Result<(), snafu::Error> Validates that a path is safe to read from. Prevents directory traversal or access to sensitive files. ``` -------------------------------- ### BarkML Comment Parsing Source: https://docs.rs/barkml/latest/src/barkml/syn/lexer.rs Specifies the regular expressions for recognizing and capturing line comments (starting with '#') and multi-line comments (enclosed in '/* ... */'). ```rust #[regex(r"(#[ \t\f]*[^\n\r]+[\n\r])?", line_comment)] LineComment((Location, String)), #[regex(r"/\*[^/\*]*\*/", multiline_comment)] MultiLineComment((Location, String)), ``` -------------------------------- ### Iterate Error Chain Source: https://docs.rs/barkml/latest/barkml/enum.Error Provides an iterator to traverse the chain of errors. It starts with the current error and recursively follows the `Error::source` to explore nested errors. ```Rust fn iter_chain(&self) -> ChainCompat<'_, '_> where Self: AsErrorSource ``` -------------------------------- ### Rust TryInto Trait and try_into Method Source: https://docs.rs/barkml/latest/barkml/enum.Walk Documentation for the Rust `TryInto` trait, detailing its `Error` type and the `try_into` method for performing conversions. It explains the return type in case of conversion errors and the signature of the conversion method. ```APIDOC TryInto Trait: Associated Types: type Error = >::Error - Description: The type returned in the event of a conversion error. - Source: https://doc.rust-lang.org/nightly/core/convert/trait.TryInto.html#associatedtype.Error Methods: fn try_into(self) -> Result>::Error> - Description: Performs the conversion. - Parameters: - self: The value to convert. - Returns: A Result containing the converted value of type U or an error of type >::Error. - Source: https://doc.rust-lang.org/nightly/core/convert/trait.TryInto.html#tymethod.try_into ``` -------------------------------- ### Rust: Get TypeId using Any trait Source: https://docs.rs/barkml/latest/barkml/ser/struct.ValueSerializeStructVariant The `type_id` method, part of the `Any` trait, retrieves a unique identifier for the type of `self`. This is useful for runtime type introspection and downcasting. ```Rust fn type_id(&self) -> TypeId ``` -------------------------------- ### CloneToUninit Trait Methods Source: https://docs.rs/barkml/latest/barkml/enum.HashableFloat Documentation for the experimental CloneToUninit trait, used for cloning data into uninitialized memory. Includes the unsafe clone_to_uninit method. ```APIDOC unsafe trait CloneToUninit { unsafe fn clone_to_uninit(&self, dest: *mut u8); } // Method: clone_to_uninit // Description: Performs copy-assignment from `self` to `dest`. // This is a nightly-only experimental API. // Parameters: // - self: A reference to the object to clone. // - dest: A raw mutable pointer to the destination memory. // Returns: // - None. The operation is performed in-place. ``` -------------------------------- ### Rust: Get TypeId using Any trait Source: https://docs.rs/barkml/latest/barkml/ser/struct.KeySerializer The `type_id` method, part of the `Any` trait, retrieves a unique identifier for the type of `self`. This is useful for runtime type introspection and downcasting. ```Rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Parsing Entry Point and Metadata (Rust) Source: https://docs.rs/barkml/latest/src/barkml/syn/parser.rs The main parsing function initiates the parsing process by calling the module parsing logic. The metadata parsing function extracts comments and labels associated with AST nodes. ```rust 76 pub fn parse(&mut self) -> Result { 77 self.module() 78 } 79 80 fn metadata(&mut self) -> Result { 81 let mut meta = Metadata { 82 location: self.tokens.location(), 83 comment: None, 84 label: None, 85 }; 86 87 // Process comments 88 while let Some(token) = self.tokens.peek()? { 89 match token { 90 Token::LineComment((_, comment)) | Token::MultiLineComment((_, comment)) => { 91 self.tokens.discard(); 92 // If we already have a comment, append this one with a newline 93 if let Some(existing) = meta.comment.as_mut() { 94 existing.push('\n'); 95 existing.push_str(&comment); 96 } else { 97 meta.comment = Some(comment.clone()); 98 } 99 } 100 Token::LabelIdentifier((_, label)) => { 101 self.tokens.discard(); 102 meta.label = Some(label.clone()); 103 break; 104 } 105 _ => break, 106 } 107 } 108 109 // If we didn't find a label in the comment processing loop, check again 110 if meta.label.is_none() { 111 if let Some(Token::LabelIdentifier((_, label))) = self.tokens.peek()? { 112 self.tokens.discard(); 113 meta.label = Some(label.clone()); 114 } 115 } 116 117 Ok(meta) 118 } ``` -------------------------------- ### Get Symbol Table Reference Source: https://docs.rs/barkml/latest/barkml/struct.Scope Retrieves a reference to the internal symbol table, which maps String identifiers to Value types. This is crucial for understanding the scope's symbol management. ```APIDOC pub fn symbol_table(&self) -> &[IndexMap] - Returns a reference to the symbol table. - The symbol table is an IndexMap mapping String keys to Value types. ``` -------------------------------- ### Rust: Get TypeId using Any trait Source: https://docs.rs/barkml/latest/barkml/ser/struct.SerializeStatementStructVariant The `type_id` method, part of the `Any` trait, retrieves a unique identifier for the type of `self`. This is useful for runtime type introspection and downcasting. ```Rust fn type_id(&self) -> TypeId ``` -------------------------------- ### barkml Location Struct and Methods (Rust) Source: https://docs.rs/barkml/latest/barkml/struct.Location Documentation for the Location struct in the barkml crate. It represents a source code location with fields like file path, line, column, and length. Includes methods for creating, manipulating, and retrieving context from a location. ```APIDOC barkml Location Struct Documentation (0.8.5) Represents a specific location within a source code file. Fields: - column: The column number within the line. - file_path: The path to the source file. - length: The length of the span in characters. - line: The line number within the file. - module: The module path where the location is defined. - source_text: The text content of the source file. Methods: - context(): Returns the source text context around the location. - formatted_context(): Returns a formatted string showing the source text with the location highlighted. - is_complete(): Checks if the location has all necessary information. - new(line: usize, column: usize, length: usize): Creates a new Location instance. - position(): Returns the line and column as a tuple. - set_file_path(file_path: impl Into): Sets the file path. - set_module(module: impl Into): Sets the module path. - set_source_text(source_text: impl Into): Sets the source text. - span_to(other: &Location): Creates a new Location spanning from this location to another. - with_details(file_path: impl Into, module: impl Into, source_text: impl Into): Creates a new Location with additional details. Trait Implementations: - Clone, Debug, Default, Deserialize, Display, Eq, Hash, PartialEq, Serialize, StructuralPartialEq: Standard Rust traits for data manipulation and serialization. - Auto Traits (Freeze, RefUnwindSafe, Send, Sync, Unpin, UnwindSafe): Indicate thread safety and memory management properties. - Blanket Implementations (Any, Borrow, BorrowMut, CloneToUninit, DeserializeOwned, Equivalent, From, Into, ToOwned, ToString, TryFrom, TryInto): Generic implementations provided by Rust's standard library and traits. ``` -------------------------------- ### Rust: Serialize sequence start Source: https://docs.rs/barkml/latest/src/barkml/ser/statement.rs Initiates the serialization of a sequence (like a Vec or array). It returns a `SerializeStatementSeq` struct, which is used to collect statements for each element in the sequence. ```Rust fn serialize_seq(self, _len: Option) -> Result { Ok(SerializeStatementSeq { statements: IndexMap::new(), index: 0, metadata: self.metadata.clone(), }) } ``` -------------------------------- ### Equivalent Trait Methods Source: https://docs.rs/barkml/latest/barkml/enum.HashableFloat Documentation for the Equivalent trait, used for checking equivalence between keys. Includes the equivalent method from hashbrown and equivalent crates. ```APIDOC trait Equivalent { fn equivalent(&self, key: &K) -> bool; } // Method: equivalent (hashbrown) // Description: Checks if this value is equivalent to the given key. // Parameters: // - self: The object to compare. // - key: A reference to the key to compare against. // Returns: // - true if the value is equivalent to the key, false otherwise. // Method: equivalent (equivalent crate) // Description: Compare self to `key` and return `true` if they are equal. // Parameters: // - self: The object to compare. // - key: A reference to the key to compare against. // Returns: // - true if the value is equal to the key, false otherwise. ``` -------------------------------- ### Barkml Crate Functions Source: https://docs.rs/barkml/latest/barkml/all Provides a list of utility functions and serialization/deserialization functions available in the barkml crate. These functions cover parsing, serialization, and path manipulation. ```APIDOC Functions: de::from_statement(statement: Statement) -> Result Deserializes a Statement into a target type T. de::from_value(value: Value) -> Result Deserializes a Value into a target type T. from_str(s: &str) -> Result Parses a string into a Statement. ser::to_statement(value: &T) -> Result Serializes a value into a Statement. ser::to_value(value: &T) -> Result Serializes a value into a Value. utils::basename(path: &str) -> Option<&str> Extracts the base name from a file path. utils::discover_files(dir: &str) -> Result, Error> Discovers barkml files within a directory. utils::is_barkml_dir(path: &str) -> bool Checks if a path points to a barkml directory. utils::is_barkml_file(path: &str) -> bool Checks if a path points to a barkml file. utils::validate_path(path: &str) -> Result<(), Error> Validates a given file path. ``` -------------------------------- ### Rust Into and From Traits Source: https://docs.rs/barkml/latest/barkml/ser/struct.SerializeVec Documentation for Rust's `Into` and `From` traits, which enable type conversions. `Into` is automatically implemented when `From` is implemented, allowing for idiomatic conversions. The `into` method calls the corresponding `From::from` implementation. ```rust impl Into for T where U: From Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. ``` -------------------------------- ### Rust: ToString::to_string Source: https://docs.rs/barkml/latest/barkml/struct.Value Converts the given value to a String. This method requires the type to implement the Display trait and provides a standard way to get a string representation. ```rust fn to_string(&self) -> String ``` -------------------------------- ### Rust Into and From Traits Source: https://docs.rs/barkml/latest/barkml/ser/struct.ValueSerializer Documentation for the `Into` and `From` traits in Rust, which provide a standard way to perform conversions between types. `Into` is automatically implemented when `From` is implemented. ```APIDOC Rust Conversion Traits: Into and From Trait: core::convert::Into - Enables conversion from a type T to a type U. - Signature: impl Into for T where U: From - Method: into(self) -> U - Calls U::from(self). - This conversion is defined by the implementation of From for U. Trait: core::convert::From - Enables conversion from a type T to a type U. - Signature: impl From for T where T: Into - Note: Implementing `From` for `U` automatically provides `Into` for `T`. Example: ```rust let num = 5u32; let num_usize = num.into(); // Converts u32 to usize if From for usize is implemented // Equivalent using From: let num_usize_from = usize::from(num); ``` ``` -------------------------------- ### Rust: Get Value as String Reference Source: https://docs.rs/barkml/latest/barkml/struct.Value Safely attempts to retrieve a reference to the `String` data stored within the `Value`. Returns `None` if the `Value` does not contain a string. ```rust pub fn as_string(&self) -> Option<&String> ``` -------------------------------- ### BarkML Statement: Get Grouped Children Source: https://docs.rs/barkml/latest/barkml/struct.Statement Retrieves children for container statements. This method returns an Option containing an IndexMap where keys are Strings and values are Statements, representing grouped children. ```rust pub fn get_grouped(&self) -> Option<&IndexMap> ``` -------------------------------- ### Rust: Get Source Context Source: https://docs.rs/barkml/latest/src/barkml/ast/types.rs Returns the source text associated with the location. If no source text has been set, it returns an empty string. This is useful for providing context in error messages. ```rust /// Get the source context for error reporting /// /// Returns the source text if available, or an empty string if not. /// This is useful for providing context in error messages. pub fn context(&self) -> String { self.source_text.clone().unwrap_or_default() } ```