### Quick Start: Parse TOML and Access Data in Zig Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Demonstrates basic TOML parsing and accessing nested values. Ensure the 'toml' and 'std' libraries are imported. ```zig const toml = @import("toml"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const input = \\[server] \host = "localhost" \port = 8080 ; var doc = try toml.parse(allocator, input, .{}); defer doc.deinit(); if (doc.root.get("server")) |server| { if (server.get("host")) |host| { std.debug.print("Host: {s} ", .{host.string}); } } } ``` -------------------------------- ### Get Value by Key Path in Zig Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Retrieves a TOML value using a path of keys. Ensure the document is loaded and the path is valid. ```zig pub fn getPath(self: *const Document, path: []const []const u8) ?*const Value ``` ```zig const path = &[_][]const u8{ "server", "database", "url" }; if (doc.getPath(path)) |url| { std.debug.print("URL: {s}\n", .{url.string}); } ``` -------------------------------- ### TOML Parse Flow (Diagram) Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/ARCHITECTURE.md Visualizes the data flow for parsing a TOML string, starting from UTF-8 validation, through lexing and tokenization, to building the parse tree and the final Document structure. ```text Input String │ ▼ ┌──────────┐ ┌────────────┐ ┌──────────────┐ │ UTF-8 │────▶│ Lexer │────▶│ Parser │ │ Validate │ │ Tokenize │ │ Build Tree │ └──────────┘ └────────────┘ └──────────────┘ │ ▼ ┌──────────────┐ │ Document │ │ + Values │ └──────────────┘ ``` -------------------------------- ### Get Value by Key in Zig Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Retrieves a value from a TOML table using a single key. Returns null if the key is not found or if the value is not a table. ```zig pub fn get(self: *const Value, key: []const u8) ?*const Value ``` ```zig if (doc.root.get("server")) |server| { if (server.get("port")) |port| { const p: u16 = @intCast(port.integer); } } ``` -------------------------------- ### Document.getPath - Access Nested Values by Path Source: https://context7.com/devnw/zig/llms.txt Retrieve values from deeply nested tables using an array of key segments, avoiding multiple chained `get()` calls. ```APIDOC ## Document.getPath - Access Nested Values by Path ### Description Retrieve values from deeply nested tables using an array of key segments, avoiding multiple chained `get()` calls. ### Method GET (or equivalent for library function call) ### Endpoint N/A (Method on Document object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **path** (array of strings) - Required - An array of key segments representing the path to the desired value. ### Request Example ```zig const toml = @import("toml"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const input = \[server] \host = "localhost" \ \[server.database] \url = "postgres://localhost/db" \ \[server.database.pool] \size = 25 ; var doc = try toml.parse(allocator, input, .{}); defer doc.deinit(); // Access deeply nested value using path const db_url_path = &[_][]const u8{ "server", "database", "url" }; if (doc.getPath(db_url_path)) |url| { std.debug.print("Database URL: {s}\\n", .{url.string}); // Output: Database URL: postgres://localhost/db } const pool_size_path = &[_][]const u8{ "server", "database", "pool", "size" }; if (doc.getPath(pool_size_path)) |size| { std.debug.print("Pool size: {d}\\n", .{size.integer}); // Output: Pool size: 25 } } ``` ### Response #### Success Response (200) - **Value** (enum/struct) - The value found at the specified path. Type depends on the TOML value (e.g., string, integer). #### Response Example (See Request Example for usage and output) ``` -------------------------------- ### TOML Error Categories Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/ARCHITECTURE.md Lists the categories of errors that can occur during TOML parsing, with examples for each category, including lexical, syntactic, semantic, version, and limits. ```text Lexical | InvalidUtf8, UnterminatedString, InvalidControlCharacter Syntactic | UnexpectedToken, UnexpectedEof Semantic | DuplicateKey, TableRedefined, KeyRedefinesNonTable Version | InlineTableNewlineNotAllowed, LocalTimeSecondsOmittedNotAllowed Limits | LimitExceeded (depth, bytes) ``` -------------------------------- ### Access Nested TOML Values by Path Source: https://context7.com/devnw/zig/llms.txt Use the `Document.getPath` method to retrieve values from deeply nested tables by providing an array of key segments. This method simplifies accessing nested data compared to chaining multiple `get()` calls. ```zig const toml = @import("toml"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const input = \[server] \host = "localhost" \ \[server.database] \url = "postgres://localhost/db" \ \[server.database.pool] \size = 25 ; var doc = try toml.parse(allocator, input, .{}); defer doc.deinit(); // Access deeply nested value using path const db_url_path = &[_][]const u8{ "server", "database", "url" }; if (doc.getPath(db_url_path)) |url| { std.debug.print("Database URL: {s}\n", .{url.string}); // Output: Database URL: postgres://localhost/db } const pool_size_path = &[_][]const u8{ "server", "database", "pool", "size" }; if (doc.getPath(pool_size_path)) |size| { std.debug.print("Pool size: {d}\n", .{size.integer}); // Output: Pool size: 25 } } ``` -------------------------------- ### Clone and Build the Repository Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/CONTRIBUTING.md Initial steps to set up the local development environment. ```bash git clone https://gitlab.com/YOUR_USERNAME/toml.git cd toml ``` ```bash zig build test ``` -------------------------------- ### Running Tests and Build Commands Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Commands to verify the environment and execute the build process. ```bash # Verify Zig version zig version # must be 0.15.2 # Run all tests zig build test # Build CLI only zig build ``` -------------------------------- ### Load Configuration Files Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Reads a TOML file from the filesystem and parses it into a configuration structure using an allocator. ```zig const std = @import("std"); const toml = @import("toml"); pub fn loadConfig(allocator: std.mem.Allocator, path: []const u8) !Config { const content = try std.fs.cwd().readFileAlloc(allocator, path, 1024 * 1024); defer allocator.free(content); var doc = try toml.parse(allocator, content, .{}); defer doc.deinit(); return Config{ .host = doc.getPath(&.{ "server", "host" }).?.string, .port = @intCast(doc.getPath(&.{ "server", "port" }).?.integer), }; } ``` -------------------------------- ### Build the CLI binary Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Build the TOML parser's CLI binary using the Zig build system. ```bash zig build ``` -------------------------------- ### Project File Structure Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Overview of the repository layout and source file organization. ```text /toml build.zig LICENSE README.md src/ toml.zig # Public API parser.zig # TOML parser lexer.zig # Tokenizer value.zig # Value types and Document error.zig # Error types json_tagged.zig # Tagged JSON emitter bin/ toml_test_decoder.zig # CLI binary tests/ accept.zig # Acceptance tests ``` -------------------------------- ### Verify Code Formatting Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/CONTRIBUTING.md Check source files for adherence to Zig style guidelines. ```bash zig fmt --check src/ build.zig ``` -------------------------------- ### Basic TOML Parsing in Zig Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Demonstrates basic TOML parsing and accessing values by key or path. Ensure to deinitialize the document when done. ```zig const toml = @import("toml"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const input = \\[server] \host = "localhost" \port = 8080 \ \[database] \url = "postgres://localhost/db" ; var doc = try toml.parse(allocator, input, .{}); defer doc.deinit(); // Access values if (doc.root.get("server")) |server| { if (server.get("host")) |host| { std.debug.print("Host: {s}\n", .{host.string}); } if (server.get("port")) |port| { std.debug.print("Port: {d}\n", .{port.integer}); } } // Path-based lookup const path = &[_][]const u8{ "database", "url" }; if (doc.getPath(path)) |url| { std.debug.print("DB URL: {s}\n", .{url.string}); } } ``` -------------------------------- ### Run Tests and Formatting Checks Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/CONTRIBUTING.md Commands for executing test suites and verifying code style. ```bash # Run all tests zig build test # Run with optimization zig build test -Doptimize=ReleaseSafe # Check for formatting issues zig fmt --check src/ build.zig ``` -------------------------------- ### Import toml in build.zig Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Import the toml module in your build.zig file after adding it as a dependency. ```zig const toml_dep = b.dependency("toml", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("toml", toml_dep.module("toml")); ``` -------------------------------- ### Add toml to build.zig.zon Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Add the toml dependency to your build.zig.zon file to include it in your project. ```zig .dependencies = .{ .toml = .{ .url = "https://gitlab.com/devnw/zig/toml/-/archive/main/toml-main.tar.gz", // .hash = "...", }, }, ``` -------------------------------- ### Create a Feature Branch Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/CONTRIBUTING.md Command to initialize a new branch for issue resolution. ```bash git checkout -b feature/issue-N-description ``` -------------------------------- ### Project Directory Structure Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/CONTRIBUTING.md Overview of the file organization within the zigtoml repository. ```text /zigtoml build.zig # Build configuration README.md # Project overview src/ toml.zig # Public API parser.zig # TOML parser lexer.zig # Tokenizer value.zig # Value types error.zig # Error types json_tagged.zig # Tagged JSON output bin/ toml_test_decoder.zig # CLI binary tests/ accept.zig # Acceptance tests docs/ ROADMAP.md # Development roadmap CONTRIBUTING.md # This file API.md # API reference ``` -------------------------------- ### Run Unit and Compliance Tests Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/ARCHITECTURE.md Execute unit tests with 'zig build test'. For TOML spec compliance, run the toml-test decoder using the provided command. ```bash # Unit tests zig build test ``` ```bash # toml-test compliance toml-test ./zig-out/bin/toml-test-decoder ``` -------------------------------- ### Add TOML as a Dependency in build.zig.zon Source: https://context7.com/devnw/zig/llms.txt Add the TOML library as a dependency to your Zig project by specifying its URL in the build.zig.zon file. You can add a hash after the first fetch for reproducible builds. ```zig // In build.zig.zon: .dependencies = .{ .toml = .{ .url = "https://gitlab.com/devnw/zig/toml/-/archive/main/toml-main.tar.gz", // .hash = "...", // Add hash after first fetch }, }, // In build.zig: const toml_dep = b.dependency("toml", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("toml", toml_dep.module("toml")); ``` -------------------------------- ### Run toml-test-decoder CLI Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Execute the `toml-test-decoder` CLI tool, which reads TOML from stdin and outputs tagged JSON to stdout. It exits with 0 on success and 1 on failure. ```bash # Run decoder echo 'a = 42' | ./zig-out/bin/toml-test-decoder # Output: {"a":{"type":"integer","value":"42"}} # Use with toml-test toml-test ./zig-out/bin/toml-test-decoder ``` -------------------------------- ### Load TOML Configuration into Zig Structs Source: https://context7.com/devnw/zig/llms.txt Illustrates mapping TOML configuration data into typed Zig structs, including handling default values for missing keys. This pattern is useful for application settings. ```zig const toml = @import("toml"); const std = @import("std"); const Config = struct { app_name: []const u8, server: ServerConfig, database: DatabaseConfig, }; const ServerConfig = struct { host: []const u8, port: u16, workers: u16, }; const DatabaseConfig = struct { url: []const u8, pool_size: u16, }; fn loadConfig(doc: *const toml.Document) Config { var config: Config = undefined; // Top-level with defaults config.app_name = if (doc.root.get("name")) |v| v.string else "unnamed"; // Server configuration with defaults if (doc.root.get("server")) |server| { config.server = .{ .host = if (server.get("host")) |v| v.string else "127.0.0.1", .port = if (server.get("port")) |v| @intCast(v.integer) else 8080, .workers = if (server.get("workers")) |v| @intCast(v.integer) else 4, }; } else { config.server = .{ .host = "127.0.0.1", .port = 8080, .workers = 4 }; } // Database configuration with defaults if (doc.root.get("database")) |db| { config.database = .{ .url = if (db.get("url")) |v| v.string else "sqlite://data.db", .pool_size = if (db.get("pool_size")) |v| @intCast(v.integer) else 10, }; } else { config.database = .{ .url = "sqlite://data.db", .pool_size = 10 }; } return config; } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const config_toml = \name = "MyService" \ \\[server] \host = "0.0.0.0" \port = 3000 \workers = 8 \ \\[database] \url = "postgres://localhost:5432/production" \pool_size = 25 ; var doc = try toml.parse(allocator, config_toml, .{}); defer doc.deinit(); const config = loadConfig(&doc); std.debug.print("App: {s}\n", .{config.app_name}); std.debug.print("Server: {s}:{d} ({d} workers)\n", .{ config.server.host, config.server.port, config.server.workers, }); std.debug.print("Database: {s} (pool: {d})\n", .{ config.database.url, config.database.pool_size, }); } ``` -------------------------------- ### Handle Optional Values Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Provides default values when a key is missing from the TOML document. ```zig const host = if (doc.root.get("host")) |h| h.string else "localhost"; const port: u16 = if (doc.root.get("port")) |p| @intCast(p.integer) else 8080; ``` -------------------------------- ### Parse TOML Input with Basic Options Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Parses TOML input into a Document. Use this for straightforward parsing when detailed error information is not immediately needed. Ensure a valid Allocator and input string are provided. ```zig var doc = try toml.parse(allocator, "key = \"value\"", .{}); defer doc.deinit(); const val = doc.root.get("key").?.string; ``` -------------------------------- ### Memory Management Lifecycle Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Demonstrates the invalidation of references after calling deinit on the document. ```zig var doc = try toml.parse(allocator, input, .{}); const host = doc.root.get("host").?.string; // Valid doc.deinit(); // host is now invalid - do not use! ``` -------------------------------- ### Zig TOML File Structure Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/ARCHITECTURE.md Overview of the Zig TOML parser's directory structure, highlighting key modules for API, parsing, lexing, value handling, error management, JSON output, and testing. ```plaintext src/ ├── toml.zig # Public API and re-exports ├── parser.zig # TOML parser implementation ├── lexer.zig # Tokenizer ├── value.zig # Value types and Document ├── error.zig # Error types ├── json_tagged.zig # Tagged JSON emitter └── bin/ └── toml_test_decoder.zig # CLI for toml-test ``` -------------------------------- ### TOML Lookup Flow (Diagram) Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/ARCHITECTURE.md Illustrates the data flow for looking up a value in a TOML document using a path, showing how the parser traverses the nested table entries to find the target value. ```text doc.getPath(["server", "db", "host"]) │ ▼ ┌─────────────────────────────────────────────────┐ │ root.table.entries │ │ ├── "server" ─────────────────┐ │ │ │ │ │ │ │ │ ▼ │ │ │ │ table.entries │ │ │ │ └── "db" ───────────────┤ │ │ │ │ │ │ │ │ ▼ │ │ │ │ table.entries │ │ │ │ └── "host" ─────────┴──▶ Value │ └─────────────────────────────────────────────────┘ ``` -------------------------------- ### TOML Version Selection in Zig Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Selects the TOML version for parsing. Use `.v1_1_0` for full compliance or `.v1_0_0` for strict compatibility. ```zig // TOML v1.1.0 (default) var doc = try toml.parse(allocator, input, .{ .version = .v1_1_0 }); // TOML v1.0.0 strict mode var doc = try toml.parse(allocator, input, .{ .version = .v1_0_0 }); ``` -------------------------------- ### TOML Parse Options Structure Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Defines configuration options for the TOML parser, including TOML version, maximum nesting depth, and maximum input size. Defaults are provided for convenience. ```zig pub const ParseOptions = struct { version: TomlVersion = .v1_1_0, max_depth: u16 = 128, max_bytes: usize = 16 * 1024 * 1024, }; ``` -------------------------------- ### Access All TOML Value Types in Zig Source: https://context7.com/devnw/zig/llms.txt Demonstrates accessing various TOML value types including strings, integers (decimal, hex, octal, binary), floats (inf, nan), booleans, datetime types, arrays, and tables. ```zig const toml = @import("toml"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const input = \# Strings \name = "Hello, World!" \path = 'C:\\Users\\file.txt' \ \# Numbers \decimal = 1_000_000 \hex = 0xDEADBEEF \octal = 0o755 \binary = 0b11010110 \pi = 3.14159 \infinity = inf \ \# Boolean \enabled = true \ \# Datetime types \timestamp = 2024-01-15T10:30:00Z \local_dt = 2024-01-15T10:30:00 \date = 2024-01-15 \time = 10:30:00.123 \ \# Arrays \numbers = [1, 2, 3] \nested = [[1, 2], [3, 4]] \ \# Inline table \point = { x = 10, y = 20 } ; var doc = try toml.parse(allocator, input, .{}); defer doc.deinit(); // Strings const name = doc.root.get("name").?.string; std.debug.print("Name: {s}\n", .{name}); // Integers const hex = doc.root.get("hex").?.integer; std.debug.print("Hex: 0x{X}\n", .{@as(u64, @intCast(hex))}); // Floats const pi = doc.root.get("pi").?.float; std.debug.print("Pi: {d:.5}\n", .{pi}); // Boolean const enabled = doc.root.get("enabled").?.bool; std.debug.print("Enabled: {}\n", .{enabled}); // Datetime const dt = doc.root.get("timestamp").?.datetime; std.debug.print("Year: {d}, Month: {d}, Day: {d}\n", .{ dt.year, dt.month, dt.day }); // Arrays const numbers = doc.root.get("numbers").?.array; for (numbers.items) |item| { std.debug.print("Number: {d}\n", .{item.integer}); } // Inline tables const point = doc.root.get("point").?; std.debug.print("Point: ({d}, {d})\n", .{ point.get("x").?.integer, point.get("y").?.integer, }); } ``` -------------------------------- ### Arena Allocator Strategy (Zig) Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/ARCHITECTURE.md Diagram showing how the Document owns an ArenaAllocator that manages all parsed data, including the root value, nested values, string contents, and table/array items. ```zig Document └── ArenaAllocator ├── Root Value (Table) ├── All nested Values ├── String contents (copied from input) └── Table entries and array items ``` -------------------------------- ### Parse and Iterate Array of Tables in Zig Source: https://context7.com/devnw/zig/llms.txt Demonstrates parsing TOML data containing arrays of tables and iterating over them to access structured data. Ensure the TOML data is correctly formatted with `[[table]]` syntax. ```zig const toml = @import("toml"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const input = \\[[products]] \name = "Hammer" \price = 9.99 \in_stock = true \ \\[[products]] \name = "Nail" \price = 0.05 \in_stock = true \ \\[[products]] \name = "Screwdriver" \price = 12.50 \in_stock = false ; var doc = try toml.parse(allocator, input, .{}); defer doc.deinit(); if (doc.root.get("products")) |products| { std.debug.print("Found {d} products:\n", .{products.array.items.len}); for (products.array.items, 0..) |product, i| { const name = product.get("name").?.string; const price = product.get("price").?.float; const in_stock = product.get("in_stock").?.bool; std.debug.print(" {d}. {s} - ${d:.2} (in stock: {}\n", .{ i + 1, name, price, in_stock, }); } } // Output: // Found 3 products: // 1. Hammer - $9.99 (in stock: true) // 2. Nail - $0.05 (in stock: true) // 3. Screwdriver - $12.50 (in stock: false) } ``` -------------------------------- ### Use toml-test-decoder CLI for TOML Validation Source: https://context7.com/devnw/zig/llms.txt The `toml-test-decoder` CLI tool reads TOML from stdin and outputs tagged JSON to stdout, useful for integration with the `toml-test` validation suite. It exits with code 1 on parse failure. ```bash # Build the project zig build # Run the decoder directly echo 'name = "test"' | ./zig-out/bin/toml-test-decoder # Output: {"name":{"type":"string","value":"test"}} # Parse a configuration file echo '[server] host = "localhost" port = 8080' | ./zig-out/bin/toml-test-decoder # Output: {"server":{"host":{"type":"string","value":"localhost"},"port":{"type":"integer","value":"8080"}}} # Use with toml-test validation suite toml-test ./zig-out/bin/toml-test-decoder # Error handling (exits with code 1 on parse failure) echo 'invalid = ' | ./zig-out/bin/toml-test-decoder # Stderr: parse error at line 1, column 11: unexpected end of input # Exit code: 1 ``` -------------------------------- ### Configure TOML Parser Behavior with ParseOptions Source: https://context7.com/devnw/zig/llms.txt Use ParseOptions to set the TOML version mode (v1.0.0 strict or v1.1.0 permissive), maximum nesting depth, and maximum input size. Defaults to v1.1.0. ```zig const toml = @import("toml"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); // TOML v1.1.0 with inline table trailing commas (default) const v11_input = "point = { x = 1, y = 2, }"; var doc_v11 = try toml.parse(allocator, v11_input, .{ .version = .v1_1_0, // Default .max_depth = 64, .max_bytes = 1024 * 1024, // 1MB limit }); defer doc_v11.deinit(); // TOML v1.0.0 strict mode (trailing commas not allowed) const v10_input = "point = { x = 1, y = 2 }"; var doc_v10 = try toml.parse(allocator, v10_input, .{ .version = .v1_0_0, }); defer doc_v10.deinit(); std.debug.print("Both parsed successfully\n", .{}); } ``` -------------------------------- ### Configuring Parsing Limits in Zig Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Sets limits for TOML parsing, such as maximum nesting depth and input size, to prevent excessive resource consumption. Defaults are provided. ```zig var doc = try toml.parse(allocator, input, .{ .max_depth = 64, // Maximum nesting depth (default: 128) .max_bytes = 1024 * 1024, // Maximum input size (default: 16MB) }); ``` -------------------------------- ### TOML Version Differences (v1.0.0 vs v1.1.0) Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/ARCHITECTURE.md Compares features between TOML versions 1.0.0 and 1.1.0, highlighting differences in handling inline table trailing commas, newlines, and time formats without seconds. ```text Feature | v1.0.0 | v1.1.0 | Inline table trailing comma | Error | Allowed | Inline table newlines | Error | Allowed | Time without seconds | Error | Assumes `:00` ``` -------------------------------- ### Public Types and API Functions Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Defines the core data structures and parsing functions available in the library. ```zig pub const TomlVersion = enum { v1_0_0, v1_1_0 }; pub const ParseOptions = struct { version: TomlVersion = .v1_1_0, max_depth: u16 = 128, max_bytes: usize = 16 * 1024 * 1024, }; pub const ErrorCode = enum { InvalidUtf8, UnexpectedToken, InvalidEscape, InvalidUnicodeScalar, DuplicateKey, KeyRedefinesNonTable, TableRedefined, ArrayOfTablesConflict, InlineTableNewlineNotAllowed, InlineTableTrailingCommaNotAllowed, LocalTimeSecondsOmittedNotAllowed, LimitExceeded, // ... }; pub const ParseError = struct { code: ErrorCode, byte_index: usize, line: u32, // 1-based column: u32, // 1-based (bytes, not graphemes) message: []const u8, }; pub const ValueTag = enum { table, array, string, integer, float, bool, datetime, datetime_local, date_local, time_local, }; pub const Value = union(ValueTag) { /* ... */ }; pub const Document = struct { pub fn deinit(self: *Document) void; pub fn getPath(self: *const Document, path: []const []const u8) ?*const Value; }; pub fn parse(alloc: Allocator, input: []const u8, opts: ParseOptions) !Document; pub fn parseWithError(alloc: Allocator, input: []const u8, opts: ParseOptions) ParseResult; pub fn writeTaggedJson(doc: *const Document, writer: anytype) !void; ``` -------------------------------- ### TOML Parser Resource Limits (Zig) Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/ARCHITECTURE.md Defines the `ParseOptions` struct in Zig, which configures resource limits for TOML parsing, including maximum depth to prevent stack overflows and maximum bytes to prevent memory exhaustion. ```zig pub const ParseOptions = struct { max_depth: u16 = 128, // Prevents stack overflow max_bytes: usize = 16MB, // Prevents memory exhaustion }; ``` -------------------------------- ### getPath Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Retrieves a value from a document using a sequence of key segments. ```APIDOC ## getPath ### Description Retrieves a value by key path (array of key segments) from a Document. ### Parameters #### Path Parameters - **path** ([]const []const u8) - Required - An array of key segments representing the path to the desired value. ### Response - **Value** (?*const Value) - Returns the value if found, otherwise null. ``` -------------------------------- ### TOML Version Enum Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Enumerates the supported TOML specification versions. Use '.v1_0_0' for strict compliance or '.v1_1_0' for relaxed syntax (default). ```zig pub const TomlVersion = enum { v1_0_0, // Strict TOML v1.0.0 compliance v1_1_0, // TOML v1.1.0 with relaxed syntax (default) }; ``` -------------------------------- ### Value.get Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Retrieves a value from a table by a specific key. ```APIDOC ## Value.get ### Description Retrieves a value from a table by key. Returns null if not found or if the value is not a table. ### Parameters #### Query Parameters - **key** ([]const u8) - Required - The key to look up in the table. ### Response - **Value** (?*const Value) - Returns the value if found, otherwise null. ``` -------------------------------- ### Parse TOML into a Document Source: https://context7.com/devnw/zig/llms.txt Use the `parse` function to convert TOML input into a typed Document structure. The Document manages memory using an ArenaAllocator, requiring a single `deinit()` call to free all associated memory. Access values using `table.get()`. ```zig const toml = @import("toml"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const input = \\[server] \host = "localhost" \port = 8080 \timeout_ms = 30000 \ \[database] \url = "postgres://localhost:5432/mydb" \max_connections = 100 ; // Parse the TOML document var doc = try toml.parse(allocator, input, .{}); defer doc.deinit(); // Access values via table.get() if (doc.root.get("server")) |server| { if (server.get("host")) |host| { std.debug.print("Host: {s} ", .{host.string}); // Output: Host: localhost } if (server.get("port")) |port| { std.debug.print("Port: {d} ", .{port.integer}); // Output: Port: 8080 } } } ``` -------------------------------- ### toml.parse Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Parses TOML input into a Document structure. ```APIDOC ## Function: parse ### Description Parses TOML input into a Document. ### Parameters - **alloc** (Allocator) - Required - Memory allocator for the parsed document - **input** ([]const u8) - Required - TOML source text (must be valid UTF-8) - **opts** (ParseOptions) - Required - Configuration options for parsing ### Returns - **Document** - The parsed document containing the root table ### Errors - **error.ParseFailed** - Parse error occurred - **error.OutOfMemory** - Memory allocation failed ``` -------------------------------- ### Version-Specific Parsing Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Configures the parser to adhere to specific TOML version standards. ```zig // TOML v1.0.0 strict mode var doc_v1 = try toml.parse(allocator, input, .{ .version = .v1_0_0 }); // TOML v1.1.0 (default, allows trailing commas in inline tables) var doc_v11 = try toml.parse(allocator, input, .{ .version = .v1_1_0 }); ``` -------------------------------- ### Commit Message Format Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/CONTRIBUTING.md Standard structure for descriptive commit messages. ```text feat: add streaming parser support - Implement StreamParser struct - Add event-based output - Include benchmarks Fixes #14 ``` -------------------------------- ### Document Structure for Parsed TOML Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Represents a parsed TOML document, holding the root value and an arena allocator for memory management. The arena must be deinitialized when the document is no longer needed. ```zig pub const Document = struct { root: *Value, arena: std.heap.ArenaAllocator, pub fn deinit(self: *Document) void; pub fn getPath(self: *const Document, path: []const []const u8) ?*const Value; pub fn allocator(self: *Document) Allocator; }; ``` -------------------------------- ### TOML Table Flags (Zig) Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/ARCHITECTURE.md Describes the flags used to denote specific properties of TOML tables, such as whether they were defined inline, as part of an array, explicitly, or via dotted keys. ```zig is_inline | Was defined with `{ }` syntax is_array_of_tables | Part of `[[name]]` array defined_explicitly | Has a `[name]` header defined_by_dotted_key | Created via `a.b.c = val` is_closed_inline | Inline table that cannot be extended ``` -------------------------------- ### Serialize TOML Document to Tagged JSON Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Writes a parsed TOML document to a writer in toml-test compatible tagged JSON format. Keys are lexicographically sorted for deterministic output. Ensure the document is valid and the writer implements the standard Writer interface. ```zig var doc = try toml.parse(allocator, "a = 42", .{}); defer doc.deinit(); const stdout = std.io.getStdOut().writer(); try toml.writeTaggedJson(&doc, stdout); // Output: {"a":{"type":"integer","value":"42"}} ``` -------------------------------- ### Export Parsed TOML to Tagged JSON Source: https://context7.com/devnw/zig/llms.txt Write parsed TOML documents to a writer in toml-test compatible tagged JSON format. Keys are deterministically sorted lexicographically at every level. ```zig const toml = @import("toml"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const input = \name = "example" \count = 42 \enabled = true \ \[server] \host = "localhost" ; var doc = try toml.parse(allocator, input, .{}); defer doc.deinit(); const stdout = std.io.getStdOut().writer(); try toml.writeTaggedJson(&doc, stdout); // Output: {"count":{"type":"integer","value":"42"},"enabled":{"type":"bool","value":"true"},"name":{"type":"string","value":"example"},"server":{"host":{"type":"string","value":"localhost"}}} } ``` -------------------------------- ### Document Operations Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Methods for interacting with a parsed TOML Document. ```APIDOC ## Document.getPath(self: *const Document, path: []const []const u8) ?*const Value ### Description Retrieves a value from the document based on a path of keys. ### Parameters - **path** ([]const []const u8) - Required - An array of keys representing the path to the desired value. ### Response - **?*const Value** (Value) - Returns the value if found, otherwise null. ## Document.deinit(self: *Document) void ### Description Frees all memory associated with the document using the internal arena allocator. ``` -------------------------------- ### Tagged JSON Output in Zig Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Writes the parsed TOML document to a writer in the toml-test tagged JSON format. This is useful for deterministic output and testing. ```zig var doc = try toml.parse(allocator, input, .{}); defer doc.deinit(); const stdout = std.io.getStdOut().writer(); try toml.writeTaggedJson(&doc, stdout); ``` -------------------------------- ### TOML Parsing with Error Handling in Zig Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Parses TOML input and handles potential errors, printing diagnostic information if parsing fails. The document must be deinitialized if parsing is successful. ```zig const result = toml.parseWithError(allocator, input, .{}); switch (result) { .ok => |*doc| { defer doc.deinit(); // Use document... }, .err => |e| { std.debug.print("Parse error at line {d}, column {d}: {s}\n", .{ e.line, e.column, e.message, }); }, } ``` -------------------------------- ### Tagged JSON Format for TOML Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/ARCHITECTURE.md Illustrates the tagged JSON format used for serializing parsed TOML documents, showing how different value types like strings and integers are represented. ```json { "key": {"type": "string", "value": "text"}, "num": {"type": "integer", "value": "42"} } ``` -------------------------------- ### JSON Serialization Source: https://gitlab.com/devnw/zig/toml/-/blob/main/README.md Utility for exporting a parsed TOML document to tagged JSON. ```APIDOC ## writeTaggedJson(doc: *const Document, writer: anytype) !void ### Description Serializes the document to a tagged JSON format, ensuring keys are sorted lexicographically for deterministic output. ### Parameters - **doc** (*const Document) - Required - The document to serialize. - **writer** (anytype) - Required - The output stream writer. ``` -------------------------------- ### Zig TOML DateTimeLocal Struct Definition Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Represents a local date and time without timezone information. ```zig pub const DateTimeLocal = struct { year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8, nanosecond: u32 = 0, pub fn format(self: DateTimeLocal, writer: anytype) !void; }; ``` -------------------------------- ### Zig TOML DateTime Struct Definition Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Represents a date and time with an optional timezone offset, conforming to RFC 3339. ```zig pub const DateTime = struct { year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8, nanosecond: u32 = 0, offset_minutes: ?i16, // null for Z (UTC) pub fn format(self: DateTime, writer: anytype) !void; }; ``` -------------------------------- ### Zig TOML TimeLocal Struct Definition Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Represents a local time. ```zig pub const TimeLocal = struct { hour: u8, minute: u8, second: u8, nanosecond: u32 = 0, pub fn format(self: TimeLocal, writer: anytype) !void; }; ``` -------------------------------- ### Zig TOML DateLocal Struct Definition Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Represents a local date. ```zig pub const DateLocal = struct { year: u16, month: u8, day: u8, pub fn format(self: DateLocal, writer: anytype) !void; }; ``` -------------------------------- ### Parse with Detailed Error Reporting Source: https://context7.com/devnw/zig/llms.txt Returns either a Document or a ParseError with precise location information including line number, column, error code, and descriptive message. ```APIDOC ## parseWithError - Parse with Detailed Error Reporting ### Description Returns either a Document or a ParseError with precise location information including line number, column, error code, and descriptive message. ### Method POST (or equivalent for library function call) ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **allocator** (Allocator) - Required - The allocator to use for memory management. - **input** (string) - Required - The TOML string to parse. - **options** (struct) - Optional - Parsing options. ### Request Example ```zig const toml = @import("toml"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const input = \name = "first" \name = "second" ; const result = toml.parseWithError(allocator, input, .{}); switch (result) { .ok => |*doc| { var d = @constCast(doc); defer d.deinit(); std.debug.print("Parsed successfully\\n", .{}); }, .err => |e| { std.debug.print("Parse error at line {d}, column {d}\\n", .{ e.line, e.column }); std.debug.print("Error code: {s}\\n", .{@tagName(e.code)}); std.debug.print("Message: {s}\\n", .{e.message}); // Output: Parse error at line 2, column 1 // Output: Error code: DuplicateKey // Output: Message: duplicate key 'name' }, } } ``` ### Response #### Success Response (200) - **Document** (struct) - The parsed TOML document. #### Error Response - **ParseError** (struct) - Contains error details: `line`, `column`, `code`, `message`. #### Response Example (See Request Example for usage and output) ``` -------------------------------- ### Iterate Over Arrays Source: https://gitlab.com/devnw/zig/toml/-/blob/main/docs/API.md Accesses an array field in the TOML document and iterates through its items. ```zig if (doc.root.get("items")) |items| { for (items.array.items) |item| { const name = item.get("name").?.string; const value = item.get("value").?.integer; std.debug.print("{s}: {d}\n", .{ name, value }); } } ```