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
use crate::error::{ConfigError, ParseResult};
use std::collections::HashMap;
use std::rc::Rc;

/// Type alias for handler functions
type HandlerFn = Rc<dyn Fn(&HandlerContext) -> ParseResult<()>>;

/// Context for handler execution
pub struct HandlerContext {
    /// The category path where this handler is being called
    pub category: Vec<String>,

    /// The keyword that triggered this handler
    pub keyword: String,

    /// The value passed to the handler
    pub value: String,

    /// Optional flags (e.g., "flagsabc" from "keywordflagsabc = value")
    pub flags: Option<String>,
}

impl HandlerContext {
    pub fn new(keyword: String, value: String) -> Self {
        Self {
            category: Vec::new(),
            keyword,
            value,
            flags: None,
        }
    }

    pub fn with_category(mut self, category: Vec<String>) -> Self {
        self.category = category;
        self
    }

    pub fn with_flags(mut self, flags: String) -> Self {
        self.flags = Some(flags);
        self
    }

    /// Get the full category path as a string
    pub fn category_path(&self) -> String {
        self.category.join(":")
    }
}

/// Trait for implementing custom keyword handlers
pub trait Handler: std::fmt::Debug {
    /// Handle a keyword with the given context
    fn handle(&self, context: &HandlerContext) -> ParseResult<()>;

    /// Get the handler name
    fn name(&self) -> &str;

    /// Check if this handler accepts flags
    fn accepts_flags(&self) -> bool {
        false
    }
}

/// Function-based handler wrapper
#[derive(Clone)]
pub struct FunctionHandler {
    name: String,
    accepts_flags: bool,
    handler: HandlerFn,
}

impl FunctionHandler {
    pub fn new<F>(name: impl Into<String>, handler: F) -> Self
    where
        F: Fn(&HandlerContext) -> ParseResult<()> + 'static,
    {
        Self {
            name: name.into(),
            accepts_flags: false,
            handler: Rc::new(handler),
        }
    }

    pub fn with_flags<F>(name: impl Into<String>, handler: F) -> Self
    where
        F: Fn(&HandlerContext) -> ParseResult<()> + 'static,
    {
        Self {
            name: name.into(),
            accepts_flags: true,
            handler: Rc::new(handler),
        }
    }
}

impl Handler for FunctionHandler {
    fn handle(&self, context: &HandlerContext) -> ParseResult<()> {
        (self.handler)(context)
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn accepts_flags(&self) -> bool {
        self.accepts_flags
    }
}

impl std::fmt::Debug for FunctionHandler {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FunctionHandler")
            .field("name", &self.name)
            .field("accepts_flags", &self.accepts_flags)
            .finish()
    }
}

/// Handler scope type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HandlerScope {
    /// Global handler (available everywhere)
    Global,
    /// Category-specific handler
    Category,
}

pub struct ResolvedHandlerCall<'a> {
    pub handler: &'a dyn Handler,
    pub handler_keyword: String,
    pub actual_keyword: String,
    pub flags: Option<String>,
}

/// Manager for keyword handlers
pub struct HandlerManager {
    /// Global handlers
    global_handlers: HashMap<String, Box<dyn Handler>>,

    /// Category-scoped handlers: category_path -> keyword -> handler
    category_handlers: HashMap<String, HashMap<String, Box<dyn Handler>>>,
}

impl HandlerManager {
    pub fn new() -> Self {
        Self {
            global_handlers: HashMap::new(),
            category_handlers: HashMap::new(),
        }
    }

    /// Register a global handler
    pub fn register_global<H>(&mut self, keyword: impl Into<String>, handler: H)
    where
        H: Handler + 'static,
    {
        self.global_handlers
            .insert(keyword.into(), Box::new(handler));
    }

    /// Register a category-scoped handler
    pub fn register_category<H>(
        &mut self,
        category: impl Into<String>,
        keyword: impl Into<String>,
        handler: H,
    ) where
        H: Handler + 'static,
    {
        self.category_handlers
            .entry(category.into())
            .or_default()
            .insert(keyword.into(), Box::new(handler));
    }

    /// Find a handler for a keyword in a given category
    pub fn find_handler(&self, category_path: &[String], keyword: &str) -> Option<&dyn Handler> {
        // First try category-specific handlers (most specific to least specific)
        for i in (0..=category_path.len()).rev() {
            let path = category_path[..i].join(":");
            if let Some(handlers) = self.category_handlers.get(&path)
                && let Some(handler) = handlers.get(keyword)
            {
                return Some(handler.as_ref());
            }
        }

        // Fall back to global handlers
        self.global_handlers.get(keyword).map(|h| h.as_ref())
    }

    fn resolve_in_map<'a>(
        handlers: &'a HashMap<String, Box<dyn Handler>>,
        keyword: &str,
    ) -> Option<ResolvedHandlerCall<'a>> {
        if let Some(handler) = handlers.get(keyword) {
            return Some(ResolvedHandlerCall {
                handler: handler.as_ref(),
                handler_keyword: keyword.to_string(),
                actual_keyword: keyword.to_string(),
                flags: None,
            });
        }

        if keyword.contains(':') {
            return None;
        }

        let mut best_match: Option<(&str, &dyn Handler)> = None;
        for (name, handler) in handlers {
            if !handler.accepts_flags() || !keyword.starts_with(name) {
                continue;
            }

            match best_match {
                Some((best_name, _)) if best_name.len() >= name.len() => {}
                _ => best_match = Some((name.as_str(), handler.as_ref())),
            }
        }

        best_match.map(|(name, handler)| ResolvedHandlerCall {
            handler,
            handler_keyword: name.to_string(),
            actual_keyword: keyword.to_string(),
            flags: Some(keyword[name.len()..].to_string()),
        })
    }

    pub fn resolve_invocation<'a>(
        &'a self,
        category_path: &[String],
        keyword: &str,
    ) -> Option<ResolvedHandlerCall<'a>> {
        for i in (0..=category_path.len()).rev() {
            let path = category_path[..i].join(":");
            if let Some(handlers) = self.category_handlers.get(&path)
                && let Some(resolved) = Self::resolve_in_map(handlers, keyword)
            {
                return Some(resolved);
            }
        }

        Self::resolve_in_map(&self.global_handlers, keyword)
    }

    /// Check if a handler exists for a keyword
    pub fn has_handler(&self, category_path: &[String], keyword: &str) -> bool {
        self.resolve_invocation(category_path, keyword).is_some()
    }

    /// Execute a handler
    pub fn execute(
        &self,
        category_path: &[String],
        keyword: &str,
        value: &str,
        flags: Option<String>,
    ) -> ParseResult<()> {
        let handler = self
            .find_handler(category_path, keyword)
            .ok_or_else(|| ConfigError::handler(keyword, "handler not found"))?;

        // Check if flags are provided but not accepted
        if flags.is_some() && !handler.accepts_flags() {
            return Err(ConfigError::handler(
                keyword,
                "handler does not accept flags",
            ));
        }

        let context = HandlerContext::new(keyword.to_string(), value.to_string())
            .with_category(category_path.to_vec());

        let context = if let Some(flags) = flags {
            context.with_flags(flags)
        } else {
            context
        };

        handler.handle(&context)
    }

    pub fn execute_resolved(
        &self,
        category_path: &[String],
        resolved: &ResolvedHandlerCall<'_>,
        value: &str,
    ) -> ParseResult<()> {
        if resolved.flags.is_some() && !resolved.handler.accepts_flags() {
            return Err(ConfigError::handler(
                &resolved.actual_keyword,
                "handler does not accept flags",
            ));
        }

        let context = HandlerContext::new(resolved.actual_keyword.clone(), value.to_string())
            .with_category(category_path.to_vec());

        let context = if let Some(flags) = resolved.flags.clone() {
            context.with_flags(flags)
        } else {
            context
        };

        resolved.handler.handle(&context)
    }

    /// Unregister a global handler by keyword
    pub fn unregister_global(&mut self, keyword: &str) -> bool {
        self.global_handlers.remove(keyword).is_some()
    }

    /// Unregister a category-scoped handler
    pub fn unregister_category(&mut self, category: &str, keyword: &str) -> bool {
        if let Some(handlers) = self.category_handlers.get_mut(category) {
            handlers.remove(keyword).is_some()
        } else {
            false
        }
    }

    /// Clear all handlers
    pub fn clear(&mut self) {
        self.global_handlers.clear();
        self.category_handlers.clear();
    }

    /// Get all registered global handler keywords
    pub fn global_keywords(&self) -> Vec<&str> {
        self.global_handlers.keys().map(|s| s.as_str()).collect()
    }

    /// Get all registered category handler keywords for a category
    pub fn category_keywords(&self, category: &str) -> Vec<&str> {
        self.category_handlers
            .get(category)
            .map(|handlers| handlers.keys().map(|s| s.as_str()).collect())
            .unwrap_or_default()
    }
}

impl Default for HandlerManager {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_function_handler() {
        let mut manager = HandlerManager::new();

        let handler = FunctionHandler::new("test", |ctx| {
            assert_eq!(ctx.keyword, "test");
            assert_eq!(ctx.value, "value");
            Ok(())
        });

        manager.register_global("test", handler);

        assert!(manager.has_handler(&[], "test"));
        manager.execute(&[], "test", "value", None).unwrap();
    }

    #[test]
    fn test_handler_with_flags() {
        let mut manager = HandlerManager::new();

        let handler = FunctionHandler::with_flags("flagged", |ctx| {
            assert_eq!(ctx.flags, Some("abc".to_string()));
            Ok(())
        });

        manager.register_global("flagged", handler);

        manager
            .execute(&[], "flagged", "value", Some("abc".to_string()))
            .unwrap();
    }

    #[test]
    fn test_category_scoped_handler() {
        let mut manager = HandlerManager::new();

        let handler = FunctionHandler::new("scoped", |ctx| {
            assert_eq!(ctx.category_path(), "category");
            Ok(())
        });

        manager.register_category("category", "scoped", handler);

        assert!(manager.has_handler(&["category".to_string()], "scoped"));
        assert!(!manager.has_handler(&[], "scoped"));

        manager
            .execute(&["category".to_string()], "scoped", "value", None)
            .unwrap();
    }

    #[test]
    fn test_handler_precedence() {
        let mut manager = HandlerManager::new();

        // Global handler
        let global = FunctionHandler::new("keyword", |_| {
            panic!("Should not call global handler");
        });
        manager.register_global("keyword", global);

        // Category handler (should take precedence)
        let category = FunctionHandler::new("keyword", |_| Ok(()));
        manager.register_category("cat", "keyword", category);

        manager
            .execute(&["cat".to_string()], "keyword", "value", None)
            .unwrap();
    }
}