ferronconf 0.2.0

A Rust library for parsing `ferron.conf` configuration files — a domain-specific language for Ferron web server configurations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# `ferronconf`

A Rust library for parsing `ferron.conf` configuration files — a domain-specific language for [Ferron web server](https://ferron.sh) configurations.

## Overview

This crate provides a reference implementation of the `ferron.conf` format, including:

- **Lexer** — Tokenizes configuration files with support for comments, strings, numbers, booleans, and interpolation
- **Parser** — Builds an AST from tokens with full error reporting
- **AST** — Type-safe representation of configuration structures

This crate is published to simplify parsing `ferron.conf` files for Ferron web server configurations; this can be useful when building tooling around Ferron.

For the complete format specification, see [SPECIFICATION.md](./SPECIFICATION.md).

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
ferronconf = "0.2.0"
```

## Quick start

```rust
use ferronconf::Config;
use std::str::FromStr;

let input = r#"
example.com {
    root /var/www/example
    tls {
        provider "acme"
        challenge http-01
        contact "admin@example.com"
    }
}

api.example.com:8080 {
    proxy http://localhost:3000
}
"#;

let config = Config::from_str(input)?;
```

## Configuration format

The `ferron.conf` format supports five statement types:

### 1. Directives

Key-value pairs with optional nested blocks:

```ferron
server_name example.com
max_connections 1000
enabled true
cert "{{env.TLS_CERT}}"
```

### 2. Host blocks

Configuration scoped to specific hosts (top-level only):

```ferron
# Simple hostname
example.com {
    root /var/www/example
}

# Wildcard subdomains
*.example.com {
    tls {
        provider "acme"
        challenge http-01
        contact "admin@example.com"
    }
}

# With protocol and port
http api.example.com:8080 {
    proxy http://localhost:3000
}

# IPv6
[2001:db8::1]:8080 {
    root /ipv6-only
}

# Multiple hosts (comma-separated)
example.com, www.example.com {
    root /var/www/shared
}
```

### 3. Global blocks

Global configuration applied to all hosts (top-level only):

```ferron
{
    runtime {
        io_uring true
    }

    tcp {
        listen "::"
        send_buf 65536
    }

    default_http_port 8080
    default_https_port 8443
}
```

### 4. Snippet blocks

Reusable configuration fragments:

```ferron
snippet tls_defaults {
    tls {
        provider "acme"
        challenge http-01
        contact "admin@example.com"
    }

    http {
        protocols h1 h2
    }
}
```

### 5. Match blocks

Conditional logic based on request attributes:

```ferron
match api_request {
    request.uri.path ~ "/api"
    request.method in "GET,POST"
}

match curl_client {
    request.header.user_agent ~ "curl"
}
```

Supported operators: `==`, `!=`, `~` (regex), `!~` (negated regex), `in`

### Comments

```ferron
# This is a comment
server_name example.com  # inline comment
```

## Data types

| Type | Example | Description |
|------|---------|-------------|
| String (quoted) | `"hello world"` | Supports escape sequences (`\n`, `\t`, `\\`, `\"`) |
| String (bare) | `example.com` | Unquoted alphanumeric with `_-.:/+*` |
| Number | `80`, `3.14`, `-10` | Integer or decimal |
| Boolean | `true`, `false` | Case-sensitive literals |
| Interpolation | `{{env.TLS_CERT}}` | Variable reference with dotted path |

## Library API

### Parsing

```rust
use ferronconf::Config;
use std::str::FromStr;

let config = Config::from_str(input)?;
```

### AST navigation

```rust
use ferronconf::Statement;

// Find all directives with a given name
let roots = config.find_directives("root");

// Find all host blocks
let hosts = config.find_host_blocks();

// Find all match blocks
let matchers = config.find_match_blocks();

// Navigate statements
for stmt in &config.statements {
    match stmt {
        Statement::Directive(d) => {
            println!("Directive: {}", d.name);
            if let Some(root) = d.get_string_arg(0) {
                println!("  Root: {}", root);
            }
        }
        Statement::HostBlock(hb) => {
            for pattern in &hb.hosts {
                println!("Host: {}", pattern.as_str());
            }
        }
        Statement::MatchBlock(mb) => {
            println!("Matcher: {}", mb.matcher);
        }
        Statement::GlobalBlock(gb) => {
            // Access global configuration
        }
        Statement::SnippetBlock(sb) => {
            println!("Snippet: {}", sb.name);
        }
    }
}
```

### Block helpers

```rust
// Find directive inside a block
if let Some(block) = directive.block {
    if let Some(nested) = block.find_directive("ssl") {
        // ...
    }
}
```

### Value extraction

```rust
use ferronconf::Value;

// From directive arguments
if let Some(root) = directive.get_string_arg(0) {
    // ...
}

if let Some(port) = directive.get_integer_arg(1) {
    // ...
}

if let Some(enabled) = directive.get_boolean_arg(2) {
    // ...
}

// From Value directly
match &value {
    Value::String(s, _) => { /* ... */ }
    Value::Integer(i, _) => { /* ... */ }
    Value::Float(f, _) => { /* ... */ }
    Value::Boolean(b, _) => { /* ... */ }
    Value::InterpolatedString(parts, _) => {
        for part in parts {
            match part {
                StringPart::Literal(s) => { /* ... */ }
                StringPart::Expression(path) => { /* ... */ }
            }
        }
    }
}
```

### Host pattern matching

```rust
use ferronconf::ast::HostLabels;

for host_block in config.find_host_blocks() {
    for pattern in &host_block.hosts {
        match &pattern.labels {
            HostLabels::Wildcard => { /* matches any host */ }
            HostLabels::Hostname(labels) => { /* e.g., ["example", "com"] */ }
            HostLabels::IpAddr(ip) => { /* IPv4 or IPv6 */ }
        }
        
        if let Some(port) = pattern.port {
            // ...
        }
        
        if let Some(protocol) = &pattern.protocol {
            // e.g., "http", "tcp"
        }
    }
    
    // Check if block matches a specific host
    if host_block.matches_host("example.com") {
        // ...
    }
}
```

### Match block inspection

```rust
for match_block in config.find_match_blocks() {
    println!("Matcher: {}", match_block.matcher);
    
    for expr in &match_block.expr {
        match &expr.left {
            Operand::Identifier(path, _) => {
                println!("  Path: {}", path.join("."));
            }
            Operand::String(s, _) => {
                println!("  String: {}", s);
            }
            _ => {}
        }
        
        println!("  Operator: {}", expr.op.as_str());
        
        // Check operator type
        if expr.is_equality() { /* ... */ }
        if expr.is_regex() { /* ... */ }
    }
}
```

## Error handling

Parse errors include line and column information:

```rust
use ferronconf::{Config, ParseError};
use std::str::FromStr;

match Config::from_str(input) {
    Ok(config) => { /* ... */ }
    Err(ParseError { message, span }) => {
        eprintln!("Error at line {}, column {}: {}", 
                  span.line, span.column, message);
    }
}
```

## Syntax highlighting

A TextMate grammar is provided in `ferron.tmLanguage.json` for editor syntax highlighting. Copy it to your editor's grammar directory or use it with tools like [`bat`](https://github.com/sharkdp/bat) or [`syntect`](https://github.com/trishume/syntect).

## Example configuration

```ferron
# Global defaults
{
    runtime {
        io_uring true
    }

    tcp {
        listen "::"
    }

    default_http_port 80
    default_https_port 443

    admin {
        listen 127.0.0.1:8081
        health true
        status true
    }
}

# Reusable TLS configuration
snippet tls_acme {
    tls {
        provider "acme"
        challenge http-01
        contact "admin@example.com"
    }
}

# Reusable HTTP settings
snippet common_http {
    http {
        protocols h1 h2
    }
}

# Main site with static file serving
example.com:443 {
    use tls_acme
    use common_http

    root /var/www/example
    index index.html index.htm
    directory_listing
    compressed

    log "access" {
        format "combined"
    }
}

# Wildcard subdomains with ACME TLS
*.example.com {
    tls {
        provider "acme"
        challenge dns-01
        contact "admin@example.com"
        dns "cloudflare" {
            api_key "EXAMPLE_API_KEY"
        }
    }

    root /var/www/multi-tenant
}

# API reverse proxy
api.example.com {
    proxy http://localhost:3000 http://localhost:3001 {
        lb_algorithm two_random
        keepalive true
        http2 true

        request_header +X-Real-IP "{{remote_address}}"
        request_header X-Forwarded-Proto "{{scheme}}"
    }

    rate_limit {
        rate 100
        burst 50
        key remote_address
    }

    cors {
        origins "https://app.example.com"
        methods GET POST PUT DELETE
        headers "Content-Type" "Authorization"
        credentials true
    }
}

# Conditional routing
match api_request {
    request.uri.path ~ "/api"
    request.method in "GET,POST"
}

match curl_client {
    request.header.user_agent ~ "curl"
}

# Location-based configuration
example.com {
    root /var/www/example

    location /static {
        file_cache_control "public, max-age=31536000"
    }

    location /admin {
        if curl_client {
            status 403 {
                body "Forbidden"
            }
        }
    }
}

# Protocol-specific configuration
http * {
    header X-Powered-By "Ferron"
}

# TCP service
tcp *:5432 {
    proxy localhost:5432
}
```

## License

MIT