INI Parser
This example shows how to parse INI configuration files, which are commonly used for application settings. The parser handles sections, properties, comments, and various whitespace patterns.INI File Format
INI files consist of:- Sections:
[section_name] - Properties:
key = value - Comments: Lines starting with
;or# - Whitespace: Spaces, tabs, and blank lines
Complete Implementation
How It Works
Whitespace Handling
The parser carefully distinguishes between different types of whitespace:- Horizontal whitespace: Spaces and tabs within a line
- Line breaks:
\n,\r, or\r\n - Blank lines: Lines containing only whitespace
- Comments: Lines starting with
;or#
token() helper automatically skips horizontal whitespace and comments before parsing.
Property Parsing
Properties follow the patternkey = value:
- Uses
commit()after seeing=to provide better error messages - Wraps in
atomic()to ensure the parser either fully succeeds or backtracks - Trims whitespace from values
Section Parsing
Sections start with[section_name] and contain multiple properties:
Usage Example
Output
Error Handling
The parser provides helpful error messages:[database (missing closing bracket):
Key Features
- Flexible whitespace: Handles various whitespace patterns gracefully
- Comments: Supports both
;and#comment styles - Error recovery: Uses
commit()andatomic()for better error messages - Type safety: Returns strongly-typed AST with sections and properties
- Blank lines: Allows arbitrary blank lines between sections and properties