hyprlang 0.5.0

A scripting language interpreter and parser for Hyprlang and Hyprland configuration files.
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use crate::error::ParseResult;
use crate::types::{Color, Vec2};
use pest::Parser;
use pest_derive::Parser;

#[derive(Parser)]
#[grammar = "hyprlang.pest"]
pub struct HyprlangParser;

/// Parse result containing all statements from a config file
#[derive(Debug)]
pub struct ParsedConfig {
    pub statements: Vec<Statement>,
}

/// A statement in the configuration
#[derive(Debug, Clone)]
pub enum Statement {
    /// Variable definition: $VAR = value
    VariableDef { name: String, value: String },

    /// Assignment: key = value
    Assignment { key: Vec<String>, value: Value },

    /// Category block: category { statements }
    CategoryBlock {
        name: String,
        statements: Vec<Statement>,
    },

    /// Special category block: category[key] { statements }
    SpecialCategoryBlock {
        name: String,
        key: Option<String>,
        statements: Vec<Statement>,
    },

    /// Handler call: keyword [flags] = value
    HandlerCall {
        keyword: String,
        flags: Option<String>,
        value: String,
    },

    /// Source directive: source = path
    Source { path: String },

    /// Comment directive: # hyprlang if/endif/noerror
    CommentDirective {
        directive_type: String,
        args: Option<String>,
    },
}

/// Parsed value types
#[derive(Debug, Clone)]
#[allow(dead_code)] // Variants are constructed by parser, not explicitly in code
pub enum Value {
    /// Expression: {{expr}}
    Expression(String),

    /// Variable reference: $VAR
    Variable(String),

    /// Color value
    Color(Color),

    /// Vec2 value
    Vec2(Vec2),

    /// Number (int or float)
    Number(String),

    /// Boolean
    Boolean(bool),

    /// String value
    String(String),

    /// Multiline value
    Multiline(Vec<String>),
}

impl HyprlangParser {
    /// Parse a configuration string
    pub fn parse_config(input: &str) -> ParseResult<ParsedConfig> {
        let pairs = HyprlangParser::parse(Rule::file, input)?;

        let mut statements = Vec::new();

        for pair in pairs {
            if pair.as_rule() == Rule::file {
                for inner in pair.into_inner() {
                    if let Some(stmt) = Self::parse_statement(inner)? {
                        statements.push(stmt);
                    }
                }
            }
        }

        Ok(ParsedConfig { statements })
    }

    fn parse_statement(pair: pest::iterators::Pair<Rule>) -> ParseResult<Option<Statement>> {
        match pair.as_rule() {
            Rule::variable_def => {
                let mut inner = pair.into_inner();
                let name = inner.next().unwrap().as_str().to_string();
                let value_pair = inner.next().unwrap();
                let value = Self::parse_value_to_string(value_pair)?;
                Ok(Some(Statement::VariableDef { name, value }))
            }

            Rule::assignment => {
                let mut inner = pair.into_inner();
                let key_path = inner.next().unwrap();
                let key = Self::parse_key_path(key_path)?;

                // Value is optional (e.g., "kb_variant =" with empty value)
                let value = if let Some(value_pair) = inner.next() {
                    Self::parse_value(value_pair)?
                } else {
                    Value::String(String::new())
                };

                Ok(Some(Statement::Assignment { key, value }))
            }

            Rule::category_block => {
                let mut inner = pair.into_inner();
                let name = inner.next().unwrap().as_str().to_string();
                let mut statements = Vec::new();

                for stmt_pair in inner {
                    if let Some(stmt) = Self::parse_statement(stmt_pair)? {
                        statements.push(stmt);
                    }
                }

                Ok(Some(Statement::CategoryBlock { name, statements }))
            }

            Rule::special_category_block => {
                let mut inner = pair.into_inner();
                let name = inner.next().unwrap().as_str().to_string();

                // Check for optional category_key
                let mut key = None;
                let mut statements = Vec::new();

                for pair in inner {
                    if pair.as_rule() == Rule::category_key {
                        let key_inner = pair.into_inner().next().unwrap();
                        key = Some(key_inner.as_str().to_string());
                    } else if let Some(stmt) = Self::parse_statement(pair)? {
                        statements.push(stmt);
                    }
                }

                Ok(Some(Statement::SpecialCategoryBlock {
                    name,
                    key,
                    statements,
                }))
            }

            Rule::handler_call => {
                let mut inner = pair.into_inner();
                let keyword = inner.next().unwrap().as_str().to_string();

                // Check for flags
                let next = inner.next().unwrap();
                let (flags, value_pair) = if next.as_rule() == Rule::flags {
                    let flags_str = next.as_str().to_string();
                    (Some(flags_str), inner.next().unwrap())
                } else {
                    (None, next)
                };

                let value = Self::parse_value_to_string(value_pair)?;
                Ok(Some(Statement::HandlerCall {
                    keyword,
                    flags,
                    value,
                }))
            }

            Rule::directive => {
                let mut inner = pair.into_inner();
                let value_pair = inner.next().unwrap();
                let path = Self::parse_value_to_string(value_pair)?;
                Ok(Some(Statement::Source { path }))
            }

            Rule::comment => {
                let comment_text = pair.as_str().trim_start_matches('#').trim_start();

                // Check if this is a hyprlang directive
                if let Some(directive_text) = comment_text.strip_prefix("hyprlang") {
                    let directive_text = directive_text.trim_start();

                    // Parse directive type and args
                    if let Some((directive_type, args)) =
                        directive_text.split_once(char::is_whitespace)
                    {
                        return Ok(Some(Statement::CommentDirective {
                            directive_type: directive_type.trim().to_string(),
                            args: Some(args.trim().to_string()),
                        }));
                    } else if !directive_text.is_empty() {
                        // No args, just the directive type
                        return Ok(Some(Statement::CommentDirective {
                            directive_type: directive_text.trim().to_string(),
                            args: None,
                        }));
                    }
                }

                // Regular comments are ignored
                Ok(None)
            }

            Rule::EOI => Ok(None),

            _ => Ok(None),
        }
    }

    fn parse_key_path(pair: pest::iterators::Pair<Rule>) -> ParseResult<Vec<String>> {
        let mut path = Vec::new();
        for inner in pair.into_inner() {
            path.push(inner.as_str().to_string());
        }
        Ok(path)
    }

    fn parse_value(pair: pest::iterators::Pair<Rule>) -> ParseResult<Value> {
        let inner = pair.into_inner().next().unwrap();

        match inner.as_rule() {
            Rule::single_value => Self::parse_single_value(inner.into_inner().next().unwrap()),
            Rule::multiline_value => {
                let lines: Result<Vec<_>, _> = inner
                    .into_inner()
                    .map(|p| Self::parse_value_to_string(p))
                    .collect();
                Ok(Value::Multiline(lines?))
            }
            _ => Self::parse_single_value(inner),
        }
    }

    fn parse_single_value(pair: pest::iterators::Pair<Rule>) -> ParseResult<Value> {
        match pair.as_rule() {
            Rule::expression => {
                let expr = pair.into_inner().next().unwrap().as_str().to_string();
                Ok(Value::Expression(expr))
            }

            Rule::string_value => {
                let s = pair.as_str();
                if s.starts_with('"') && s.ends_with('"') {
                    Ok(Value::String(s.to_string()))
                } else {
                    // Unquoted: unescape ## -> # (comment escaping)
                    Ok(Value::String(s.replace("##", "#")))
                }
            }

            _ => Ok(Value::String(pair.as_str().to_string())),
        }
    }

    fn parse_value_to_string(pair: pest::iterators::Pair<Rule>) -> ParseResult<String> {
        let value = Self::parse_value(pair)?;
        Ok(match value {
            Value::String(s) => s,
            Value::Number(n) => n,
            Value::Boolean(b) => b.to_string(),
            Value::Expression(e) => format!("{{{{{}}}}}", e),
            Value::Variable(v) => format!("${}", v),
            Value::Color(c) => c.to_string(),
            Value::Vec2(v) => v.to_string(),
            Value::Multiline(lines) => lines.join(" "),
        })
    }

    /// Parse configuration and build document tree (for mutation feature)
    #[cfg(feature = "mutation")]
    pub fn parse_with_document(
        input: &str,
    ) -> ParseResult<(ParsedConfig, crate::document::ConfigDocument)> {
        use crate::document::ConfigDocument;

        let pairs = HyprlangParser::parse(Rule::file, input)?;
        let mut statements = Vec::new();
        let mut doc_nodes = Vec::new();

        for pair in pairs {
            if pair.as_rule() == Rule::file {
                for inner in pair.into_inner() {
                    if let Some((stmt, node)) = Self::parse_statement_with_node(inner, input)? {
                        statements.push(stmt);
                        if let Some(n) = node {
                            doc_nodes.push(n);
                        }
                    }
                }
            }
        }

        let document = ConfigDocument::with_nodes(doc_nodes);
        Ok((ParsedConfig { statements }, document))
    }

    #[cfg(feature = "mutation")]
    #[allow(clippy::only_used_in_recursion)]
    fn parse_statement_with_node(
        pair: pest::iterators::Pair<Rule>,
        input: &str,
    ) -> ParseResult<Option<(Statement, Option<crate::document::DocumentNode>)>> {
        use crate::document::DocumentNode;

        let line = pair.line_col().0;
        let raw = pair.as_str().to_string();

        match pair.as_rule() {
            Rule::variable_def => {
                let mut inner = pair.into_inner();
                let name = inner.next().unwrap().as_str().to_string();
                let value_pair = inner.next().unwrap();
                let value = Self::parse_value_to_string(value_pair)?;

                let stmt = Statement::VariableDef {
                    name: name.clone(),
                    value: value.clone(),
                };
                let node = DocumentNode::VariableDef {
                    name,
                    value,
                    raw,
                    line,
                };
                Ok(Some((stmt, Some(node))))
            }

            Rule::assignment => {
                let mut inner = pair.into_inner();
                let key_path = inner.next().unwrap();
                let key = Self::parse_key_path(key_path)?;

                let value = if let Some(value_pair) = inner.next() {
                    Self::parse_value(value_pair)?
                } else {
                    Value::String(String::new())
                };

                let value_str = match &value {
                    Value::String(s) => s.clone(),
                    Value::Number(n) => n.clone(),
                    Value::Boolean(b) => b.to_string(),
                    Value::Expression(e) => format!("{{{{{}}}}}", e),
                    Value::Variable(v) => format!("${}", v),
                    Value::Color(c) => c.to_string(),
                    Value::Vec2(v) => v.to_string(),
                    Value::Multiline(lines) => lines.join(" "),
                };

                let stmt = Statement::Assignment {
                    key: key.clone(),
                    value,
                };
                let node = DocumentNode::Assignment {
                    key,
                    value: value_str,
                    raw,
                    line,
                };
                Ok(Some((stmt, Some(node))))
            }

            Rule::category_block => {
                let mut inner = pair.clone().into_inner();
                let name = inner.next().unwrap().as_str().to_string();
                let mut statements = Vec::new();
                let mut nodes = Vec::new();

                for stmt_pair in inner {
                    if let Some((stmt, node)) = Self::parse_statement_with_node(stmt_pair, input)? {
                        statements.push(stmt);
                        if let Some(n) = node {
                            nodes.push(n);
                        }
                    }
                }

                let stmt = Statement::CategoryBlock {
                    name: name.clone(),
                    statements,
                };

                // Extract just the opening line
                let raw_open = if let Some(first_line) = raw.lines().next() {
                    first_line.to_string()
                } else {
                    format!("{} {{", name)
                };

                let close_line = pair.line_col().1;
                let node = DocumentNode::CategoryBlock {
                    name,
                    nodes,
                    open_line: line,
                    close_line,
                    raw_open,
                };
                Ok(Some((stmt, Some(node))))
            }

            Rule::special_category_block => {
                let mut inner = pair.clone().into_inner();
                let name = inner.next().unwrap().as_str().to_string();

                let mut key = None;
                let mut statements = Vec::new();
                let mut nodes = Vec::new();

                for p in inner {
                    if p.as_rule() == Rule::category_key {
                        let key_inner = p.into_inner().next().unwrap();
                        key = Some(key_inner.as_str().to_string());
                    } else if let Some((stmt, node)) = Self::parse_statement_with_node(p, input)? {
                        statements.push(stmt);
                        if let Some(n) = node {
                            nodes.push(n);
                        }
                    }
                }

                let stmt = Statement::SpecialCategoryBlock {
                    name: name.clone(),
                    key: key.clone(),
                    statements,
                };

                let raw_open = if let Some(first_line) = raw.lines().next() {
                    first_line.to_string()
                } else if let Some(k) = &key {
                    format!("{}[{}] {{", name, k)
                } else {
                    format!("{} {{", name)
                };

                let close_line = pair.line_col().1;
                let node = DocumentNode::SpecialCategoryBlock {
                    name,
                    key,
                    nodes,
                    open_line: line,
                    close_line,
                    raw_open,
                };
                Ok(Some((stmt, Some(node))))
            }

            Rule::handler_call => {
                let mut inner = pair.into_inner();
                let keyword = inner.next().unwrap().as_str().to_string();

                let next = inner.next().unwrap();
                let (flags, value_pair) = if next.as_rule() == Rule::flags {
                    let flags_str = next.as_str().to_string();
                    (Some(flags_str.clone()), inner.next().unwrap())
                } else {
                    (None, next)
                };

                let value = Self::parse_value_to_string(value_pair)?;

                let stmt = Statement::HandlerCall {
                    keyword: keyword.clone(),
                    flags: flags.clone(),
                    value: value.clone(),
                };
                let node = DocumentNode::HandlerCall {
                    keyword,
                    flags,
                    value,
                    raw,
                    line,
                };
                Ok(Some((stmt, Some(node))))
            }

            Rule::directive => {
                let mut inner = pair.into_inner();
                let value_pair = inner.next().unwrap();
                let path = Self::parse_value_to_string(value_pair)?;

                let stmt = Statement::Source { path: path.clone() };
                let node = DocumentNode::Source { path, raw, line, resolved_path: None };
                Ok(Some((stmt, Some(node))))
            }

            Rule::comment => {
                let comment_text = pair.as_str().trim_start_matches('#').trim_start();

                // Check if this is a hyprlang directive
                if let Some(directive_text) = comment_text.strip_prefix("hyprlang") {
                    let directive_text = directive_text.trim_start();

                    // Parse directive type and args
                    let (directive_type, args) =
                        if let Some((dt, a)) = directive_text.split_once(char::is_whitespace) {
                            (dt.trim().to_string(), Some(a.trim().to_string()))
                        } else if !directive_text.is_empty() {
                            (directive_text.trim().to_string(), None)
                        } else {
                            return Ok(None);
                        };

                    let stmt = Statement::CommentDirective {
                        directive_type: directive_type.clone(),
                        args: args.clone(),
                    };
                    let node = DocumentNode::CommentDirective {
                        directive_type,
                        args,
                        raw,
                        line,
                    };
                    return Ok(Some((stmt, Some(node))));
                }

                // Regular comments are ignored
                Ok(None)
            }

            Rule::EOI => Ok(None),

            _ => Ok(None),
        }
    }
}