### Example TOML Configuration Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/types.md This TOML defines a sample application configuration including server settings and logging preferences. ```toml title = "App" [server] host = "0.0.0.0" port = 8080 enabled = true [server.tls] cert = "/etc/certs/server.crt" key = "/etc/certs/server.key" [logging] level = "info" targets = ["stdout", "file"] ``` -------------------------------- ### Mutable Configuration Example Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/configuration.md Shows an example of creating a mutable configuration structure by converting `Cow` fields to owned types, suitable for runtime modifications. ```rust #[derive(Clone)] pub struct MutableConfig { pub name: String, pub port: i64, } impl MutableConfig { pub fn from_static() -> Self { #[static_toml(cow)] static DEFAULTS = include_toml!("defaults.toml"); MutableConfig { name: DEFAULTS.app.name.into_owned(), port: DEFAULTS.app.port, } } } ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/architecture.md This is the input TOML data that will be processed. ```toml [app] name = "MyApp" [database] connections = [1, 2, 3] ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/types.md A sample TOML file demonstrating a nested configuration structure for a database, including host, port, and SSL settings. ```toml [database] host = "localhost" port = 5432 pool_size = 10 [database.ssl] enabled = true ca_cert = "/path/to/cert" ``` -------------------------------- ### File Not Found Example Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md This example shows the typical error output when the TOML file specified in `include_toml!` cannot be found. Ensure the file exists at the specified relative path from the `CARGO_MANIFEST_DIR`. ```rust error: cannot read file at `config.toml` --> src/lib.rs:5:40 | 5 | | static CONFIG = include_toml!("config.toml"); | ^^^^^^^^^^^^ | = note: No such file or directory (os error 2) ``` -------------------------------- ### TOML File Example Source: https://github.com/cptpiepmatz/static-toml/blob/main/doc/macro.md This TOML file demonstrates nested lists and tuples, serving as input for the static-toml macro. ```toml # TOML file [[list]] value = 123 [[list]] value = 456 [[tuple]] a = 1 [[tuple]] b = 2 ``` -------------------------------- ### Example TOML Structure Source: https://github.com/cptpiepmatz/static-toml/blob/main/doc/macro.md Illustrates the structure of a TOML file that can be processed by the static_toml macro. ```toml # This is a TOML document title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00-08:00 [database] enabled = true ports = [ 8000, 8001, 8002 ] data = [ ["delta", "phi"], [3.14] ] temp_targets = { cpu = 79.5, case = 72.0 } [servers] [servers.alpha] ip = "10.0.0.1" role = "frontend" [servers.beta] ip = "10.0.0.2" role = "backend" ``` -------------------------------- ### File Path Resolution Examples Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/configuration.md Illustrates how static_toml resolves file paths relative to CARGO_MANIFEST_DIR based on the root_mod attribute. ```rust #[static_toml(root_mod = config)] static APP = include_toml!("config.toml"); // Resolves to: $CARGO_MANIFEST_DIR/config.toml #[static_toml(root_mod = cfg)] static DB = include_toml!("etc/database.toml"); // Resolves to: $CARGO_MANIFEST_DIR/etc/database.toml ``` -------------------------------- ### Iterating Over Homogeneous String Array from Static TOML Config Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/types.md Example of iterating over a homogeneous array of strings loaded from TOML. Each element is accessed directly within the loop. ```rust // homogeneous array of strings for name in CONFIG.arrays.names { println!("{}", name); } ``` -------------------------------- ### Typical Syn Parsing Error Output Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Shows an example of the compiler's error output when a syntax error is detected by the `syn` parser within a macro invocation. ```rust error: expected `=" --> src/lib.rs:3:20 | 3 | static CONFIG include_toml!("config.toml"); | ^^^^^^ expected `=" ``` -------------------------------- ### TOML Parse Error Example Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Example of a typical TOML parse error output, indicating the location and nature of the error. ```text error: TOML parse error --> src/lib.rs:5:40 | 5 | static CONFIG = include_toml!("config.toml"); | ^^^^^^^^^^^^ | = note: expected a value at line 3 column 18 ``` -------------------------------- ### Accessing TOML Configuration Values Source: https://github.com/cptpiepmatz/static-toml/blob/main/README.md After including a TOML file with `static_toml!`, access its values directly as if they were Rust variables. This example demonstrates accessing nested values from a 'database' section. ```rust assert_eq!(CONFIG.database.url, "localhost"); assert_eq!(CONFIG.database.port, 5432); ``` -------------------------------- ### Embed TOML file using static-toml macro Source: https://github.com/cptpiepmatz/static-toml/blob/main/README.md Use the `static_toml!` macro with `include_toml!` to embed a TOML file and access its data as static Rust structures. This example embeds a `messages.toml` file and accesses a specific string value. ```rust static_toml::static_toml! { static MESSAGES = include_toml!("messages.toml"); } const WELCOME_MESSAGE: &str = MESSAGES.info.welcome; ``` -------------------------------- ### Invalid Identifier Error Example Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Example of a typical error message when a TOML key cannot be converted to a valid Rust identifier. ```text error: cannot convert key to valid identifier --> src/lib.rs:5:40 | 5 | static CONFIG = include_toml!("config.toml"); | ^^^^^^^^^^^^ | = note: `api-key` cannot be converted to a valid identifier ``` -------------------------------- ### Create a TOML configuration file Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Create a `config.toml` file in your project root to define application and database settings. ```toml [app] name = "My Application" version = "1.0.0" [database] host = "localhost" port = 5432 ``` -------------------------------- ### Rust Macro Input Parsing Steps Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/architecture.md Illustrates the step-by-step parsing process for a Rust macro input, including attribute separation, visibility, storage class, variable name, and the include_toml! macro call with its file path. ```rust // Input: pub static CONFIG = include_toml!("config.toml"); // Step 1: Parse attributes (#[...]) // - Separate into: doc, derive, static_toml, other // Step 2: Parse visibility (pub, pub(crate), etc.) // Step 3: Parse storage class (static or const) // Step 4: Parse variable name (CONFIG) // Step 5: Parse = token // Step 6: Parse include_toml! macro call // Step 7: Parse file path string // Step 8: Parse ; terminator // Result: StaticTomlItem { // attrs: { prefix, suffix, root_mod, ... }, // visibility: Some(pub), // storage_class: Static(...), // name: CONFIG, // path: "config.toml" // } ``` -------------------------------- ### Basic static_toml! Macro Usage with Attributes Source: https://github.com/cptpiepmatz/static-toml/blob/main/doc/crate.md Demonstrates how to use the static_toml! macro with multiple configuration attributes like prefix, suffix, and derive(Default). This is useful for customizing the generated data types and enabling default value implementations. ```rust static_toml::static_toml! { // all data types will be prefixed, suffixed and derive Default #[derive(Default)] #[static_toml(prefix = Prefix, suffix = Suffix)] static EXAMPLE = include_toml!("example.toml"); } ``` -------------------------------- ### TOML Identifier Key Naming Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Compares invalid and valid TOML keys for Rust identifiers. Keys with special characters or starting with numbers are invalid. ```toml # ✗ Invalid keys [123-config] api-key = "secret" db.host = "localhost" # ✓ Valid keys [config] api_key = "secret" db_host = "localhost" ``` -------------------------------- ### Combine Multiple Static TOML Options Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/configuration.md Demonstrates combining various configuration options within the static_toml! macro. Options can be combined in any order. ```rust static_toml::static_toml! { #[static_toml( prefix = Service, suffix = Config, root_mod = settings, values_ident = items, prefer_slices = true, auto_doc = true, cow )] #[derive(Debug, Clone)] pub static SETTINGS = include_toml!("settings.toml"); } ``` -------------------------------- ### Multiple Configurations with Environment Switching Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Define multiple static TOML configurations and select between them at compile time using conditional compilation (`cfg`). This allows for different settings based on the build environment (e.g., development vs. production). ```rust static_toml::static_toml! { /// Development configuration static DEV_CONFIG = include_toml!("config.dev.toml"); /// Production configuration static PROD_CONFIG = include_toml!("config.prod.toml"); /// Default settings pub const DEFAULTS = include_toml!("defaults.toml"); } // Use based on environment #[cfg(debug_assertions)] const CONFIG: &dyn ConfigProvider = &DEV_CONFIG; #[cfg(not(debug_assertions))] const CONFIG: &dyn ConfigProvider = &PROD_CONFIG; ``` -------------------------------- ### Configure static_toml! Macro with Custom Options Source: https://github.com/cptpiepmatz/static-toml/blob/main/README.md This snippet demonstrates how to use the static_toml! macro with several customization options. It shows how to set prefixes, suffixes, root modules, value identifiers, array slice preferences, automatic documentation generation, and Cow usage for dynamic data. ```rust static_toml! { #[static_toml( prefix = Prefix, suffix = Suffix, root_mod = cfg, values_ident = items, prefer_slices = false, auto_doc = true, cow )] static CONFIG = include_toml!("config.toml"); } ``` -------------------------------- ### Basic TOML Parsing with Static TOML Macro Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/static_toml-macro.md Illustrates the fundamental usage of the `static_toml` macro to parse a TOML file and generate associated Rust code. Ensure the TOML file exists at the specified path. ```rust #[macro_use] extern crate static_toml; static_toml! { #[doc = "Configuration file"] #[prefix = "Cfg"] #[suffix = "Config"] #[root_mod = "config"] #[values_ident = "Values"] #[prefer_slices = true] #[auto_doc = true] #[cow] // Replace &'static str slices and [T; N] arrays with Cow<'static, T> file = "config.toml" }; fn main() { // Access generated types and values here // For example, if config.toml contains: // [server] // ip = "127.0.0.1" // port = 8080 // // You might access them like: // let ip: CfgServerConfigIpConfig = config::server::ip::CfgServerConfigIpConfig; // let port: CfgServerConfigPortConfig = config::server::port::CfgServerConfigPortConfig; // println!("IP: {}", ip); // println!("Port: {}", port); } ``` -------------------------------- ### Define Static TOML Configuration with Doc Comments Source: https://github.com/cptpiepmatz/static-toml/blob/main/README.md Use the `static_toml!` macro to include TOML files at compile time. Supports derive attributes and visibility settings for enhanced type safety and organization. ```rust static_toml! { /// The configuration. #[derive(Debug)] #[allow(missing_docs)] pub static CONFIG = include_toml!("config.toml"); } ``` -------------------------------- ### Accessing Configuration Values in Rust Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/types.md Demonstrates how to access fields within the generated Rust configuration struct using dot notation and array indexing. ```rust static CONFIG = include_toml!("config.toml"); CONFIG.title; // &'static str CONFIG.server.host; // &'static str CONFIG.server.port; // i64 CONFIG.server.tls.cert; // &'static str CONFIG.logging.targets[0]; // &'static str CONFIG.logging.targets.len(); // usize = 2 ``` -------------------------------- ### Basic TOML Configuration Inclusion Source: https://github.com/cptpiepmatz/static-toml/blob/main/README.md Include a TOML configuration file using the `include_toml!` function within the `static_toml!` macro. This makes TOML data available as Rust data structures at compile time. ```rust static_toml! { static CONFIG = include_toml!("config.toml"); } ``` -------------------------------- ### Lint TOML Configuration Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Validate TOML syntax using the toml-cli tool. Ensure your TOML files adhere to the specification. ```bash # Using toml-cli (if installed) toml-lint config.toml # Using cargo (if toml-cli feature available) cargo check ``` -------------------------------- ### Valid static_toml! Macro Syntax Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Demonstrates the correct structure for invoking the `static_toml!` macro, including minimal usage, attributes, visibility, and configuration options. ```rust static_toml::static_toml! { // Required components: // [visibility] static|const NAME = include_toml!("path.toml"); // ✓ Minimal static CONFIG = include_toml!("config.toml"); // ✓ With attributes and visibility #[derive(Debug)] pub const MESSAGES = include_toml!("messages.toml"); // ✓ With configuration #[static_toml(prefix = App)] static SETTINGS = include_toml!("settings.toml"); } ``` -------------------------------- ### Verify TOML File Paths Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Check that the TOML configuration file exists at the expected path relative to your Cargo.toml. This command lists files in the current directory to help verify paths. ```bash # List files from Cargo.toml directory ls -la config.toml ls -la etc/settings.toml ``` -------------------------------- ### Generate Documentation for Static/Const TOML Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/api-reference.md Creates documentation comments for static or const values, including the file path and TOML content. This is useful for embedding configuration files directly into Rust documentation. ```rust pub fn gen_auto_doc( path: &str, content: &str, storage_class: &StorageClass ) -> TokenStream2 ``` ```rust #[doc = ""] #[doc = "Static inclusion of `config.toml`."] #[doc = ""] #[doc = "```toml"] #[doc = "...TOML content..."] #[doc = "```"] ``` ```rust use proc_macro2::TokenStream; use quote::quote; let tokens = gen_auto_doc("config.toml", "[app]\nname = \"test\"", &StorageClass::Static(...)); // Generates documentation tokens visible in rustdoc ``` -------------------------------- ### Static Value Generation Phase Output Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/architecture.md Illustrates the generation of static Rust values corresponding to the TOML data. ```rust Value::Table(...) ↓ static_tokens("config", ...) → config::Config { app: config::app::App { name: "MyApp" }, database: config::database::Database { connections: [1i64, 2i64, 3i64] } } ``` -------------------------------- ### Handle Compile-Time Configuration Errors Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/configuration.md This snippet demonstrates common compile-time errors related to static-toml configuration attributes and their correct usage. Ensure attributes are used with the correct syntax and valid names. ```rust // Error: cow cannot have a value #[static_toml(cow = true)] // ❌ // Correct #[static_toml(cow)] // ✅ // Error: invalid attribute #[static_toml(slice_preference = true)] // ❌ // Correct #[static_toml(prefer_slices = true)] // ✅ ``` -------------------------------- ### static_toml! Macro Invocation Syntax Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/static_toml-macro.md Demonstrates the syntax for invoking the static_toml! macro, including optional attributes and multiple item definitions. ```rust static_toml::static_toml! { [/// doc comments] [#[derive(...)]] [#[other_attributes]] [#[static_toml(options)]] [visibility] static|const NAME = include_toml!("path/to/file.toml"); // Multiple items allowed in single macro invocation [visibility] static|const NAME2 = include_toml!("path/to/file2.toml"); } ``` -------------------------------- ### Correct Relative Paths for include_toml! Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md When using `include_toml!`, verify that the file path is correct and relative to the `CARGO_MANIFEST_DIR`. Avoid using absolute paths or paths that navigate upwards using `..`. ```rust // If file is in same directory as Cargo.toml include_toml!("config.toml") // ✓ // If file is in subdirectory include_toml!("config/settings.toml") // ✓ // Do NOT use absolute paths or paths with .. include_toml!("/absolute/path/config.toml") // ✗ include_toml!("../config.toml") // ✗ ``` -------------------------------- ### Build with Cargo Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Always use `cargo` to build your project to ensure the `CARGO_MANIFEST_DIR` environment variable is correctly set. Building with raw `rustc` will cause this variable to be unset. ```bash cargo build # ✓ Sets CARGO_MANIFEST_DIR rustc src/lib.rs # ✗ Does not set CARGO_MANIFEST_DIR ``` -------------------------------- ### TOML Array Syntax Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Shows correct TOML array syntax. Ensure arrays are properly closed with brackets. ```toml # ✗ Invalid array mixing data = [1, "string", 2] # Heterogeneous — this is fine in TOML # ✓ But requires tuple struct in Rust (not an error, just different type generation) # ✗ Missing closing bracket array = [1, 2, 3 # ✓ Close the bracket array = [1, 2, 3] ``` -------------------------------- ### Namespace Management for Token Generation Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/architecture.md Explains how namespace tracking ensures proper module path qualification during the generation of Rust tokens for nested TOML structures. ```rust Root: [config] Table access: CONFIG.database Namespace becomes: [config, database] Generated paths: config::database::Database Nested table: CONFIG.database.ssl Namespace: [config, database, ssl] Generated path: config::database::ssl::Ssl ``` -------------------------------- ### Access TOML values using dot notation Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Access configuration values directly using dot notation, which also provides IDE autocomplete. ```rust let app_name: &str = CONFIG.app.name; // "My Application" let db_port: i64 = CONFIG.database.port; // 5432 ``` -------------------------------- ### Add static-toml to Cargo.toml Source: https://github.com/cptpiepmatz/static-toml/blob/main/README.md Add the static-toml crate to your project's dependencies using the cargo command line. ```shell cargo add static-toml ``` -------------------------------- ### Resolve TOML File Path with CARGO_MANIFEST_DIR Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/configuration.md Shows how the macro concatenates CARGO_MANIFEST_DIR with the TOML file path to locate the file. Ensure CARGO_MANIFEST_DIR is set by building with Cargo. ```rust let mut file_path = PathBuf::new(); file_path.push(env::var("CARGO_MANIFEST_DIR")?); file_path.push(static_toml.path.value()); ``` -------------------------------- ### Multiple TOML Files with static_toml! Macro Source: https://github.com/cptpiepmatz/static-toml/blob/main/doc/crate.md Include multiple TOML files by defining multiple static variables within a single `static_toml!` macro call. Supports custom visibility modifiers like `pub`. ```rust static_toml::static_toml! { [pub] static NAME_1 = include_toml!("file_1.toml"); [pub] static NAME_2 = include_toml!("file_2.toml"); ... [pub] static NAME_N = include_toml!("file_n.toml"); } ``` -------------------------------- ### TOML Duplicate Keys Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Illustrates handling of duplicate keys in TOML. Each key should appear only once per table. ```toml # ✗ Duplicate keys [server] port = 8000 port = 9000 # ✓ Each key once per table [server] port = 8000 ``` -------------------------------- ### Enable Cow for Configuration Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/configuration.md Use the `#[static_toml(cow)]` attribute to enable `std::borrow::Cow` for string slices and arrays in your static TOML configuration. ```rust #[static_toml(cow)] static CONFIG = include_toml!("config.toml"); ``` -------------------------------- ### Common static_toml! Macro Syntax Mistakes Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Illustrates frequent errors encountered when using the `static_toml!` macro, such as missing equals signs, incorrect macro names, or wrong storage classes. ```rust // ✗ Missing = static CONFIG include_toml!("config.toml"); ``` ```rust // ✗ Wrong macro name static CONFIG = include_json!("config.toml"); ``` ```rust // ✗ Missing parentheses static CONFIG = include_toml "config.toml"; ``` ```rust // ✗ Missing semicolon static CONFIG = include_toml!("config.toml") ``` ```rust // ✗ Wrong storage class auto CONFIG = include_toml!("config.toml"); ``` ```rust // ✗ Invalid visibility internal static CONFIG = include_toml!("config.toml"); ``` -------------------------------- ### Compile-Time Type Safety with static_toml! Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Demonstrates how static_toml! ensures type correctness at compile time, eliminating the need for runtime error handling of parsed values. Access configuration values directly with full type safety. ```rust static_toml::static_toml! { static CONFIG = include_toml!("config.toml"); } // Runtime handling of parsed values fn main() { // Access with full type safety let port: i64 = CONFIG.server.port; // No error handling needed — types guarantee correctness println!("Server listening on {}", port); } ``` -------------------------------- ### Basic TOML Inclusion and Access Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/static_toml-macro.md Include a TOML file and access its nested values using dot notation. ```rust static_toml::static_toml! { static CONFIG = include_toml!("config.toml"); } // Access nested values with dot notation let db_url = CONFIG.database.url; let port = CONFIG.database.port; ``` -------------------------------- ### Array Type Generation (with Cow) Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/architecture.md Demonstrates generating Rust tokens for TOML arrays when `Cow` is enabled, wrapping the array type in `std::borrow::Cow`. ```rust pub type ArrayName = std::borrow::Cow<'static, [values::Values]>; ``` -------------------------------- ### Add documentation to embedded TOML Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Add documentation comments (///) and derive attributes (#[derive(...)]) to the static configuration variable. ```rust static_toml::static_toml! { /// Application configuration loaded at compile-time #[derive(Debug)] pub static CONFIG = include_toml!("config.toml"); } ``` -------------------------------- ### Accessing Cow Values Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/configuration.md Demonstrates how to access and manipulate values stored as `std::borrow::Cow` within the static TOML configuration, including borrowing, converting to owned, and pattern matching. ```rust #[static_toml(cow)] static CONFIG = include_toml!("config.toml"); // Borrow as reference let name: &str = &*CONFIG.app.name; // Convert to owned let owned_name: String = CONFIG.app.name.clone().into_owned(); // Pattern match match CONFIG.app.name { std::borrow::Cow::Borrowed(s) => println!("Borrowed: {}", s), std::borrow::Cow::Owned(s) => println!("Owned: {}", s), } ``` -------------------------------- ### Add static-toml dependency in Cargo.toml Source: https://github.com/cptpiepmatz/static-toml/blob/main/README.md Alternatively, add the static-toml crate to your Cargo.toml file directly. ```toml [dependencies] static-toml = "1" ``` -------------------------------- ### Module Namespacing for Type Safety Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/architecture.md Demonstrates how organizing types into modules prevents name collisions with TOML keys or other types. This is crucial for maintaining clarity and avoiding conflicts in larger projects. ```Rust mod app { pub struct App { pub name: name::Name, ... } mod name { pub type Name = ...; } } mod other { pub struct Other { pub name: name::Name, ... } mod name { pub type Name = ...; } } ``` -------------------------------- ### Basic Macro Invocation Source: https://github.com/cptpiepmatz/static-toml/blob/main/doc/macro.md This snippet shows the fundamental way to invoke the static_toml macro, embedding a TOML file and defining a static value with custom attributes. ```rust static_toml::static_toml! { /// Example TOML file from [toml.io](https://toml.io/en). #[allow(missing_docs)] #[derive(Debug)] #[static_toml(suffix = Toml)] pub(crate) static EXAMPLE = include_toml!("example.toml"); } ``` -------------------------------- ### TOML String Quoting Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Demonstrates correct TOML string quoting. Unquoted strings can lead to parse errors. ```toml # ✗ Missing quotes on strings name = value # ✓ Strings must be quoted name = "value" ``` -------------------------------- ### Apply Derive Attributes to Generated Structs Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/configuration.md Demonstrates applying derive attributes like Debug, Clone, Copy, PartialEq, and Eq to all generated structs, including nested ones. ```rust static_toml::static_toml! { #[derive(Debug, Clone, Copy, PartialEq, Eq)] static CONFIG = include_toml!("config.toml"); } ``` -------------------------------- ### StaticToml Parsing Phase Representation Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/architecture.md Represents the initial parsing phase, defining the configuration item and its properties. ```rust StaticToml { items: [ StaticTomlItem { name: CONFIG, path: "config.toml", storage_class: Static, attrs: StaticTomlAttributes { root_mod: config // derived from CONFIG } } ] } ``` -------------------------------- ### Validate TOML Configuration Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Validate your TOML configuration file using `toml-lint`. ```bash # Online: https://www.toml-lint.com/ # Or with a tool: toml-lint config.toml ``` -------------------------------- ### table Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/api-reference.md Generates Rust tokens for TOML table values, specifically for struct initialization. It processes a TOML table and configuration to output Rust tokens representing the struct. ```APIDOC ## Function: table ### Description Generates Rust tokens for TOML table values (struct initialization). ### Parameters #### Path Parameters - **table** (Table) - Required - TOML table to generate values for - **key** (str) - Required - Table key name - **config** (StaticTomlAttributes) - Required - Configuration options - **namespace** (Vec) - Required - Current namespace path - **namespace_ts** (TokenStream2) - Required - Namespace path as tokens ### Returns Struct initialization expression with all fields ``` -------------------------------- ### Static TOML: `cow` Transformation - Without Cow Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/types.md Illustrates the declaration of a static string slice without the `cow` transformation enabled. ```rust // Without cow static VALUE: &'static str = "text"; ``` -------------------------------- ### TOML Inclusion with Attributes and Doc Comments Source: https://github.com/cptpiepmatz/static-toml/blob/main/doc/crate.md Demonstrates how to apply attributes, including doc comments and derive attributes, to generated static TOML data. Doc comments are attached to the static value, and derive attributes are propagated to all generated data types. ```rust static_toml::static_toml! { /// doc comments are supported #[allow(missing_docs)] #[derive(Debug)] static EXAMPLE = include_toml!("example.toml"); } ``` -------------------------------- ### TOML Inclusion with Configuration Options Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/static_toml-macro.md Use macro attributes to customize the generated Rust module and type names. Types are generated with the specified prefix and suffix. ```rust static_toml::static_toml! { #[static_toml( prefix = App, suffix = Config, root_mod = settings )] pub static SETTINGS = include_toml!("app-config.toml"); } // Types are named: AppDatabaseConfig, AppServerConfig, etc. let settings: settings::AppConfig = *SETTINGS; ``` -------------------------------- ### Expand Generated Types with Cargo Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Use `cargo expand` to view the types generated by the static-toml macro. ```bash cargo expand ``` -------------------------------- ### Rust Macro Core Implementation Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/architecture.md Core procedural macro logic for parsing input, resolving file paths, reading and parsing TOML, and generating Rust code tokens for types and static values. Uses proc_macro2 for testability and proc_macro_error for detailed error reporting. ```rust // 1. Parse macro input let static_toml_data: StaticToml = syn::parse2(input)?; // 2. For each embedded TOML file: // - Construct full file path let file_path = PathBuf::from(env::var("CARGO_MANIFEST_DIR")) .join(static_toml.path.value()); // - Read file content let content = fs::read_to_string(&file_path)?; // - Parse TOML let table: Table = toml::from_str(&content)?; // - Generate type definitions let type_tokens = value_table.type_tokens(...)?; // - Generate static value let static_tokens = value_table.static_tokens(...)?; // 3. Emit final code quote! { #visibility #storage_class #name: #type_name = #static_tokens; #type_tokens const _: &str = include_str!(#include_file_path); } ``` -------------------------------- ### Accessing TOML Configuration in Rust Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/types.md Shows how to access values from a loaded TOML configuration in Rust code, referencing nested fields through the generated struct accessors. ```rust let db_host: &str = CONFIG.database.host; // Type: database::host::Host let db_port: i64 = CONFIG.database.port; // Type: database::port::Port let ssl_enabled: bool = CONFIG.database.ssl.enabled; // Type: database::ssl::enabled::Enabled ``` -------------------------------- ### Control Automatic Documentation Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Use `auto_doc = false` to disable automatic documentation generation. ```rust #[static_toml(auto_doc = false)] ``` -------------------------------- ### Type Equality Algorithm Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/api-reference.md Illustrates the recursive algorithm used to determine if two values are type-equivalent. It handles primitive types, arrays, and tables. ```pseudocode Value::type_eq(other): String vs String → true Integer vs Integer → true Float vs Float → true Boolean vs Boolean → true Datetime vs Datetime → true Array(a) vs Array(b): - If lengths differ → false - If all a[i].type_eq(b[i]) → true, else false Table(a) vs Table(b): - Collect all keys from both tables - For each key, both must have it and values must be type_eq - All pairs must match → true, else false _ vs _ → false (different types) ``` -------------------------------- ### Export CARGO_MANIFEST_DIR in Custom Builds Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md If using a custom build system, ensure the `CARGO_MANIFEST_DIR` environment variable is exported before invoking `rustc`. This is crucial for `static_toml!` to locate manifest-related files. ```bash export CARGO_MANIFEST_DIR="$(pwd)" rustc --edition 2021 src/lib.rs ``` -------------------------------- ### Enable Mutable Owned Data Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Use the `cow` option to enable copy-on-write for mutable owned data. ```rust #[static_toml(cow)] ``` -------------------------------- ### Feature-Gated Configuration Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Conditionally include TOML configurations based on Rust features. This allows certain configurations to be enabled only when a specific feature flag is active. ```rust static_toml::static_toml! { #[cfg(feature = "extended")] static EXTENDED = include_toml!("extended.toml"); static BASIC = include_toml!("basic.toml"); } ``` -------------------------------- ### Enable mutable configuration with Cow Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Use the `#[static_toml(cow)]` attribute to enable mutable access to configuration values using `Cow` (Clone-on-Write). ```rust static_toml::static_toml! { #[static_toml(cow)] static DEFAULTS = include_toml!("defaults.toml"); } fn get_mutable_config() -> config::Config { config::Config { name: DEFAULTS.app.name.clone().into_owned(), port: DEFAULTS.app.port, } } ``` -------------------------------- ### Namespace Tracking for Code Generation Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/api-reference.md Explains how the namespace vector is used to track nested structures for proper module qualification in generated Rust code. ```pseudocode namespace = [root_mod, field_1, field_2] // References type at: root_mod::field_1::field_2::TypeName ``` -------------------------------- ### Including Multiple TOML Files Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/static_toml-macro.md Include multiple TOML files within a single macro invocation. Each included file is accessible as a separate static or const variable. ```rust static_toml::static_toml! { static MESSAGES = include_toml!("messages.toml"); #[derive(Debug)] pub const EXAMPLE = include_toml!("example.toml"); } println!("{}", MESSAGES.greeting); println!("{:?}", EXAMPLE); ``` -------------------------------- ### Include TOML Data with static_toml! Macro Source: https://github.com/cptpiepmatz/static-toml/blob/main/doc/crate.md Define static variables from TOML files at compile time. The `include_toml!` macro is used within `static_toml!` to parse and embed the TOML content. ```toml # messages.toml [info] welcome = "Welcome to our application!" update = "Your data has been updated successfully." [errors] file_not_found = "The requested file could not be found." permission_denied = "You do not have permission to perform this action." ``` ```rust static_toml::static_toml! { static MESSAGES = include_toml!("messages.toml"); } // print the message from the toml file println!("{}", MESSAGES.info.welcome); ``` -------------------------------- ### Mixing static and const with static_toml! Source: https://github.com/cptpiepmatz/static-toml/blob/main/doc/crate.md This snippet shows how to use both `static` and `const` variables within a single `static_toml!` macro call. Ensure all identifiers are unique within the scope. ```rust static_toml::static_toml! { static MESSAGES = include_toml!("messages.toml"); const EXAMPLE = include_toml!("example.toml"); } ``` -------------------------------- ### static_toml! Macro Signature Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/static_toml-macro.md The signature of the static_toml! procedural macro. It accepts and returns a proc_macro::TokenStream. ```rust #[proc_macro_error] #[proc_macro] pub fn static_toml(input: TokenStream) -> TokenStream ``` -------------------------------- ### Define StaticTomlAttributes Struct Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/api-reference.md Holds configuration options parsed from #[static_toml(...)] attributes, such as prefix, suffix, and auto-documentation settings. ```rust #[derive(Default)] pub struct StaticTomlAttributes { pub prefix: Option, pub suffix: Option, pub root_mod: Option, pub values_ident: Option, pub prefer_slices: Option, pub auto_doc: Option, pub cow: Option<()> } ``` -------------------------------- ### Valid TOML File Paths Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Ensure that the path string provided to `include_toml!` is a valid UTF-8 string and can be resolved as a filesystem path. Rust string literals are inherently valid UTF-8, making this error rare. ```rust // ✓ Valid UTF-8 path include_toml!("config.toml") include_toml!("etc/database.toml") include_toml!("./config/settings.toml") // ✗ Invalid path (non-UTF-8) — not possible in Rust string literals ``` -------------------------------- ### Embed TOML configuration with static_toml! macro Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Use the `static_toml!` macro to embed your TOML file into your Rust code as a static variable. ```rust static_toml::static_toml! { static CONFIG = include_toml!("config.toml"); } fn main() { println!("App: {}", CONFIG.app.name); println!("DB: {}:{}", CONFIG.database.host, CONFIG.database.port); } ``` -------------------------------- ### Embed TOML file using const with static-toml macro Source: https://github.com/cptpiepmatz/static-toml/blob/main/README.md Demonstrates using the `static_toml!` macro with `const` instead of `static` for embedding TOML data. This is useful when a constant value is required, such as in const functions or for const generics. ```rust static_toml::static_toml! { const MESSAGES = include_toml!("messages.toml"); } ``` -------------------------------- ### Embed TOML Configuration Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/quick-start.md Embed a TOML configuration file directly into your Rust code using the `include_toml!` macro. This is useful for application settings. ```toml # app.toml [app] name = "Example App" version = "1.0" debug = false [server] address = "127.0.0.1" port = 8080 [server.tls] enabled = false [database] url = "postgres://localhost/app" pool_size = 20 [logging] level = "info" ``` ```rust static_toml::static_toml! { #[derive(Debug)] pub static CONFIG = include_toml!("app.toml"); } fn main() { println!("App: {} v{}", CONFIG.app.name, CONFIG.app.version); println!("Server: {}:{}", CONFIG.server.address, CONFIG.server.port); println!("DB: {}", CONFIG.database.url); println!("Pool: {}", CONFIG.database.pool_size); } ``` -------------------------------- ### Final Emission of Static Configuration Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/architecture.md The final emitted Rust code, including the static configuration constant and the generated module. ```rust pub static CONFIG: config::Config = config::Config { app: config::app::App { name: "MyApp" }, database: config::database::Database { connections: [1i64, 2i64, 3i64] } }; pub mod config { // ... all generated types ... } const _: &str = include_str!("config.toml"); ``` -------------------------------- ### TOML Key Transformation with Underscores Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/errors.md Convert TOML keys with hyphens or dots to use underscores for valid Rust identifier compatibility. ```toml # ✓ Convert to underscores api_key = "secret" db_host = "localhost" max_connections = 100 ``` -------------------------------- ### Force Auto-doc with Manual Docs Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/configuration.md When `auto_doc = true` is explicitly set, auto-generated documentation comments are appended after any existing manual documentation comments. ```rust static_toml::static_toml! { /// Manual documentation #[static_toml(auto_doc = true)] static CONFIG = include_toml!("config.toml"); } ``` -------------------------------- ### Apply Public Visibility Modifiers Source: https://github.com/cptpiepmatz/static-toml/blob/main/_autodocs/configuration.md Shows how visibility modifiers like `pub` and `pub(crate)` are applied to both the static/const value and the generated root module. ```rust static_toml::static_toml! { pub static CONFIG = include_toml!("config.toml"); } // Equivalent to: // pub static CONFIG: config::Config = ...; // pub mod config { ... } static_toml::static_toml! { pub(crate) static CONFIG = include_toml!("config.toml"); } // Equivalent to: // pub(crate) static CONFIG: config::Config = ...; // pub(crate) mod config { ... } ```