hlx 1.2.5

Configuration language designed specifically for ml/ai/data systems
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use crate::hel::error::HlxError;
use crate::dna::atp::value::Value;
use crate::hel::dispatch::{HelixDispatcher, DispatchResult};
use crate::HelixConfig;
use crate::ops::engine::OperatorEngine;

/// Trait for converting Rust types into DnaValue
pub trait IntoValue {
    fn into_value(self) -> Value;
}

impl IntoValue for Value {
    fn into_value(self) -> Value {
        self
    }
}

impl IntoValue for &str {
    fn into_value(self) -> Value {
        Value::String(self.to_string())
    }
}

impl IntoValue for String {
    fn into_value(self) -> Value {
        Value::String(self)
    }
}

impl IntoValue for &String {
    fn into_value(self) -> Value {
        Value::String(self.clone())
    }
}

impl IntoValue for bool {
    fn into_value(self) -> Value {
        Value::Bool(self)
    }
}

impl IntoValue for i8 {
    fn into_value(self) -> Value {
        Value::Number(self as f64)
    }
}

impl IntoValue for i16 {
    fn into_value(self) -> Value {
        Value::Number(self as f64)
    }
}

impl IntoValue for i32 {
    fn into_value(self) -> Value {
        Value::Number(self as f64)
    }
}

impl IntoValue for i64 {
    fn into_value(self) -> Value {
        Value::Number(self as f64)
    }
}

impl IntoValue for u8 {
    fn into_value(self) -> Value {
        Value::Number(self as f64)
    }
}

impl IntoValue for u16 {
    fn into_value(self) -> Value {
        Value::Number(self as f64)
    }
}

impl IntoValue for u32 {
    fn into_value(self) -> Value {
        Value::Number(self as f64)
    }
}

impl IntoValue for u64 {
    fn into_value(self) -> Value {
        Value::Number(self as f64)
    }
}

impl IntoValue for f32 {
    fn into_value(self) -> Value {
        Value::Number(self as f64)
    }
}

impl IntoValue for f64 {
    fn into_value(self) -> Value {
        Value::Number(self)
    }
}

// Array support for Vec of IntoValue types
impl<T: IntoValue> IntoValue for Vec<T> {
    fn into_value(self) -> Value {
        Value::Array(self.into_iter().map(|v| v.into_value()).collect())
    }
}

pub struct Hlx {
    pub config: Option<HelixConfig>,
    pub data: HashMap<String, HashMap<String, Value>>,
    pub file_path: Option<PathBuf>,
    pub dispatcher: HelixDispatcher,
    pub operator_engine: OperatorEngine,
}
impl Hlx {
    pub async fn load<P: AsRef<Path>>(path: P) -> Result<Self, HlxError> {
        let path = path.as_ref().to_path_buf();
        let mut hlx = Self {
            config: None,
            data: HashMap::new(),
            file_path: Some(path.clone()),
            dispatcher: HelixDispatcher::new(),
            operator_engine: OperatorEngine::new().await?,
        };
        hlx.dispatcher.initialize().await?;
        if path.extension().and_then(|s| s.to_str()) == Some("hlxb") {
            #[cfg(feature = "compiler")]
            {
                let loader = crate::mds::loader::BinaryLoader::new();
                let binary = loader
                    .load_file(&path)
                    .map_err(|e| HlxError::compilation_error(
                        format!("Failed to load binary: {:?}", e),
                        "Ensure file is a valid HLXB file",
                    ))?;
                // Convert binary to config if needed
                hlx.config = Some(crate::HelixConfig::default());
            }
            #[cfg(not(feature = "compiler"))]
            {
                return Err(
                    HlxError::compilation_error(
                        "Binary file support not available",
                        "Compile with 'compiler' feature enabled",
                    ),
                );
            }
        } else {
            let content = std::fs::read_to_string(&path)
                .map_err(|e| HlxError::io_error(
                    format!("Failed to read file: {}", e),
                    "Ensure file exists and is readable",
                ))?;
            match hlx.dispatcher.parse_and_execute(&content).await? {
                DispatchResult::Executed(value) => {
                    if let Value::Object(obj) = value {
                        for (section, section_data) in obj {
                            if let Value::Object(section_obj) = section_data {
                                let mut section_map = HashMap::new();
                                for (key, val) in section_obj {
                                    section_map.insert(key, val);
                                }
                                hlx.data.insert(section, section_map);
                            }
                        }
                    }
                }
                DispatchResult::Parsed(ast) => {
                    hlx.config = Some(
                        crate::ast_to_config(ast)
                            .map_err(|e| HlxError::config_conversion(
                                "conversion".to_string(),
                                e,
                            ))?,
                    );
                }
                _ => {}
            }
        }
        Ok(hlx)
    }
    pub async fn new() -> Result<Self, HlxError> {
        Ok(Self {
            config: None,
            data: HashMap::new(),
            file_path: None,
            dispatcher: HelixDispatcher::new(),
            operator_engine: OperatorEngine::new().await?,
        })
    }
    pub fn get(&self, section: &str, key: &str) -> Option<&Value> {
        self.data.get(section)?.get(key)
    }
    /// Set a value in a section - automatically converts Rust types to DnaValue
    /// 
    /// # Examples
    /// ```
    /// // String values
    /// hlx.set("project", "name", "MyProject");
    /// hlx.set("project", "version", String::from("1.0.0"));
    /// 
    /// // Numeric values
    /// hlx.set("config", "port", 8080);
    /// hlx.set("config", "timeout", 30.5);
    /// 
    /// // Boolean values
    /// hlx.set("features", "debug", true);
    /// 
    /// // Explicit DnaValue for complex types
    /// hlx.set("data", "items", DnaValue::Array(vec![
    ///     DnaValue::String("item1".to_string()),
    ///     DnaValue::String("item2".to_string()),
    /// ]));
    /// ```
    pub fn set<T: IntoValue>(&mut self, section: &str, key: &str, value: T) {
        self.data
            .entry(section.to_string())
            .or_insert_with(HashMap::new)
            .insert(key.to_string(), value.into_value());
    }
    
    // Keep old method names for backward compatibility (delegates to new set)
    pub fn set_str(&mut self, section: &str, key: &str, value: &str) {
        self.set(section, key, value);
    }
    
    pub fn set_num(&mut self, section: &str, key: &str, value: f64) {
        self.set(section, key, value);
    }
    
    pub fn set_bool(&mut self, section: &str, key: &str, value: bool) {
        self.set(section, key, value);
    }
    
    /// Increase a numeric value by the specified amount
    /// If the key doesn't exist, it will be initialized to 0 + amount
    /// If the value is not a number, it will be converted to 0 + amount
    pub fn increase(&mut self, section: &str, key: &str, amount: f64) -> Result<f64, HlxError> {
        let current_value = self.get(section, key)
            .and_then(|v| v.as_number())
            .unwrap_or(0.0);
        
        let new_value = current_value + amount;
        
        self.set(section, key, Value::Number(new_value));
        Ok(new_value)
    }
    pub fn index(&self, section: &str) -> Option<&HashMap<String, Value>> {
        self.data.get(section)
    }
    pub fn index_mut(&mut self, section: &str) -> Option<&mut HashMap<String, Value>> {
        self.data.get_mut(section)
    }
    pub async fn server(&mut self) -> Result<(), HlxError> {
        if self.dispatcher.is_ready() {
            Ok(())
        } else {
            self.dispatcher.initialize().await
        }
    }
    pub async fn watch(&mut self) -> Result<(), HlxError> {
        #[cfg(feature = "compiler")]
        {
            if let Some(path) = &self.file_path {
                println!("Watching {} for changes...", path.display());
                Ok(())
            } else {
                Err(
                    HlxError::invalid_input(
                        "No file loaded for watching",
                        "Load a file first with Hlx::load()",
                    ),
                )
            }
        }
        #[cfg(not(feature = "compiler"))]
        {
            Err(
                HlxError::compilation_error(
                    "Watch mode not available",
                    "Compile with 'compiler' feature enabled",
                ),
            )
        }
    }
    pub async fn process(&mut self) -> Result<(), HlxError> {
        if let Some(path) = &self.file_path {
            let content = std::fs::read_to_string(path)
                .map_err(|e| HlxError::io_error(
                    format!("Failed to read file: {}", e),
                    "Ensure file exists and is readable",
                ))?;
            match self.dispatcher.parse_and_execute(&content).await? {
                DispatchResult::Executed(value) => {
                    println!("Processed successfully: {:?}", value);
                    Ok(())
                }
                _ => Ok(()),
            }
        } else {
            Err(
                HlxError::invalid_input(
                    "No file loaded for processing",
                    "Load a file first with Hlx::load()",
                ),
            )
        }
    }
    pub async fn compile(&mut self) -> Result<(), HlxError> {
        #[cfg(feature = "compiler")]
        {
            if let Some(path) = &self.file_path {
                use crate::dna::compiler::{Compiler, OptimizationLevel};
                let compiler = Compiler::builder()
                    .optimization_level(OptimizationLevel::Two)
                    .compression(true)
                    .cache(true)
                    .verbose(false)
                    .build();
                let binary = compiler
                    .compile_file(path)
                    .map_err(|e| HlxError::compilation_error(
                        format!("Compilation failed: {}", e),
                        "Check file syntax and try again",
                    ))?;
                let binary_path = path.with_extension("hlxb");
                let serializer = crate::mds::serializer::BinarySerializer::new(true);
                serializer
                    .write_to_file(&binary, &binary_path)
                    .map_err(|e| HlxError::io_error(
                        format!("Failed to write binary file: {}", e),
                        "Ensure output directory is writable",
                    ))?;
                println!(
                    "✅ Successfully compiled {} to {}", path.display(), binary_path
                    .display()
                );
                Ok(())
            } else {
                Err(
                    HlxError::invalid_input(
                        "No file loaded for compilation",
                        "Load a file first with Hlx::load()",
                    ),
                )
            }
        }
        #[cfg(not(feature = "compiler"))]
        {
            Err(
                HlxError::compilation_error(
                    "Compilation not available",
                    "Compile with 'compiler' feature enabled",
                ),
            )
        }
    }
    pub async fn execute(&mut self, code: &str) -> Result<Value, HlxError> {
        if !self.dispatcher.is_ready() {
            self.dispatcher.initialize().await?;
        }
        match self.dispatcher.parse_and_execute(code).await {
            Ok(DispatchResult::Executed(value)) => Ok(value),
            Ok(DispatchResult::ParseError(err)) => {
                Err(
                    HlxError::invalid_input(
                        format!("Parse error: {}", err),
                        "Check syntax",
                    ),
                )
            }
            Ok(DispatchResult::ExecutionError(err)) => Err(err),
            Ok(DispatchResult::Parsed(_)) => {
                Err(
                    HlxError::execution_error(
                        "Parsed but not executed",
                        "Use process() for file processing",
                    ),
                )
            }
            Err(e) => Err(e),
        }
    }
    pub async fn execute_operator(
        &self,
        operator: &str,
        params: &str,
    ) -> Result<Value, HlxError> {
        self.operator_engine.execute_operator(operator, params).await
    }
    pub fn sections(&self) -> Vec<&String> {
        self.data.keys().collect()
    }
    pub fn keys(&self, section: &str) -> Option<Vec<&String>> {
        self.data.get(section).map(|s| s.keys().collect())
    }
    pub fn save(&self) -> Result<(), HlxError> {
        if let Some(path) = &self.file_path {
            let mut content = String::new();
            
            // Generate proper HLX format with colon/semicolon syntax
            for (section, keys) in &self.data {
                // Use section name directly with colon syntax
                content.push_str(&format!("{} :\n", section));
                
                for (key, value) in keys {
                    // Format value appropriately
                    let formatted_value = match value {
                        Value::String(s) => format!("\"{}\"", s),
                        Value::Number(n) => n.to_string(),
                        Value::Bool(b) => b.to_string(),
                        Value::Array(arr) => {
                            let items: Vec<String> = arr.iter().map(|v| {
                                match v {
                                    Value::String(s) => format!("\"{}\"", s),
                                    Value::Number(n) => n.to_string(),
                                    Value::Bool(b) => b.to_string(),
                                    _ => format!("{}", v),
                                }
                            }).collect();
                            format!("[{}]", items.join(", "))
                        },
                        Value::Object(obj) => {
                            let pairs: Vec<String> = obj.iter().map(|(k, v)| {
                                format!("{} = {}", k, v)
                            }).collect();
                            format!("{{\n        {}\n    }}", pairs.join("\n        "))
                        },
                        _ => format!("{}", value),
                    };
                    
                    content.push_str(&format!("    {} = {}\n", key, formatted_value));
                }
                
                content.push_str(";\n\n");
            }
            
            std::fs::write(path, content)
                .map_err(|e| HlxError::io_error(
                    format!("Failed to save file: {}", e),
                    "Ensure write permissions",
                ))
        } else {
            Err(
                HlxError::invalid_input(
                    "No file path set",
                    "Load a file first or set file_path manually",
                ),
            )
        }
    }

    /// Generate HLX content as a string without writing to file
    /// 
    /// # Example
    /// ```
    /// let mut hlx = Hlx::new().await?;
    /// hlx.set("project", "name", Value::String("MyProject".to_string()));
    /// hlx.set("project", "version", Value::String("1.0.0".to_string()));
    /// let content = hlx.make()?;
    /// println!("Generated HLX content:\n{}", content);
    /// ```
    pub fn make(&self) -> Result<String, HlxError> {
        let mut content = String::new();
        
        // Generate proper HLX format with colon/semicolon syntax
        for (section, keys) in &self.data {
            // Use section name directly with colon syntax
            content.push_str(&format!("{} :\n", section));
            
            for (key, value) in keys {
                // Format value appropriately
                let formatted_value = match value {
                    Value::String(s) => format!("\"{}\"", s),
                    Value::Number(n) => n.to_string(),
                    Value::Bool(b) => b.to_string(),
                    Value::Array(arr) => {
                        let items: Vec<String> = arr.iter().map(|v| {
                            match v {
                                Value::String(s) => format!("\"{}\"", s),
                                Value::Number(n) => n.to_string(),
                                Value::Bool(b) => b.to_string(),
                                _ => format!("{}", v),
                            }
                        }).collect();
                        format!("[{}]", items.join(", "))
                    },
                    Value::Object(obj) => {
                        let pairs: Vec<String> = obj.iter().map(|(k, v)| {
                            format!("{} = {}", k, v)
                        }).collect();
                        format!("{{\n        {}\n    }}", pairs.join("\n        "))
                    },
                    _ => format!("{}", value),
                };
                
                content.push_str(&format!("    {} = {}\n", key, formatted_value));
            }
            
            content.push_str(";\n\n");
        }
        
        Ok(content)
    }
}
impl std::ops::Index<&str> for Hlx {
    type Output = HashMap<String, Value>;
    fn index(&self, section: &str) -> &Self::Output {
        self.data
            .get(section)
            .unwrap_or_else(|| panic!("Section '{}' not found", section))
    }
}
impl std::ops::IndexMut<&str> for Hlx {
    fn index_mut(&mut self, section: &str) -> &mut Self::Output {
        self.data.entry(section.to_string()).or_insert_with(HashMap::new)
    }
}
pub mod test_operators {
    use super::*;
    pub async fn test_fundamental_operators() -> Result<(), HlxError> {
        let mut hlx = Hlx::new().await?;
        println!("Testing fundamental operators...");
        let result = hlx.execute(r#"@var(name="test_var", value="hello")"#).await?;
        println!("@var result: {:?}", result);
        let result = hlx.execute(r#"@env(key="HOME")"#).await?;
        println!("@env result: {:?}", result);
        let result = hlx.execute(r#"@date("Y-m-d")"#).await?;
        println!("@date result: {:?}", result);
        let result = hlx.execute(r#"@time("H:i:s")"#).await?;
        println!("@time result: {:?}", result);
        let result = hlx.execute("@uuid()").await?;
        println!("@uuid result: {:?}", result);
        let result = hlx.execute(r#"@string("hello world", "upper")"#).await?;
        println!("@string result: {:?}", result);
        let result = hlx.execute(r#"@math("5 + 3")"#).await?;
        println!("@math result: {:?}", result);
        let result = hlx.execute(r#"@calc("a = 10; b = 5; a + b")"#).await?;
        println!("@calc result: {:?}", result);
        let result = hlx
            .execute(r#"@if(condition="true", then="yes", else="no")"#)
            .await?;
        println!("@if result: {:?}", result);
        let result = hlx
            .execute(r#"@array(values="[1,2,3]", operation="length")"#)
            .await?;
        println!("@array result: {:?}", result);
        let result = hlx.execute(r#"@json('{"name":"test"}', "parse")"#).await?;
        println!("@json result: {:?}", result);
        let result = hlx.execute(r#"@base64("hello", "encode")"#).await?;
        println!("@base64 result: {:?}", result);
        let result = hlx.execute(r#"@hash("password", "sha256")"#).await?;
        println!("@hash result: {:?}", result);
        println!("All fundamental operators tested successfully!");
        Ok(())
    }
    pub async fn test_conditional_operators() -> Result<(), HlxError> {
        let mut hlx = Hlx::new().await?;
        println!("Testing conditional operators...");
        let result = hlx
            .execute(r#"@if(condition="@math('5 > 3')", then="greater", else="less")"#)
            .await?;
        println!("@if with expression: {:?}", result);
        let result = hlx
            .execute(
                r#"@switch(value="2", cases="{'1':'one','2':'two','3':'three'}", default="unknown")"#,
            )
            .await?;
        println!("@switch result: {:?}", result);
        let result = hlx
            .execute(r#"@filter(array="[1,2,3,4,5]", condition="@math('value > 3')")"#)
            .await?;
        println!("@filter result: {:?}", result);
        let result = hlx
            .execute(r#"@map(array="[1,2,3]", transform="@math('value * 2')")"#)
            .await?;
        println!("@map result: {:?}", result);
        let result = hlx
            .execute(
                r#"@reduce(array="[1,2,3,4]", initial="0", operation="@math('acc + value')")"#,
            )
            .await?;
        println!("@reduce result: {:?}", result);
        println!("All conditional operators tested successfully!");
        Ok(())
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    #[tokio::test]
    async fn test_hlx_interface() {
        let mut hlx = Hlx::new().await.unwrap();
        hlx.data.insert("database".to_string(), HashMap::new());
        hlx.index_mut("database")
            .unwrap()
            .insert(
                "host".to_string(),
                crate::dna::atp::value::Value::String("localhost".to_string()),
            );
        hlx.index_mut("database")
            .unwrap()
            .insert("port".to_string(), crate::dna::atp::value::Value::Number(5432.0));
        assert_eq!(
            hlx.get("database", "host"), Some(& crate::dna::atp::value::Value::String("localhost"
            .to_string()))
        );
        assert_eq!(hlx.get("database", "port"), Some(& Value::Number(5432.0)));
        let sections = hlx.sections();
        assert!(sections.iter().any(| s | * s == "database"));
        let keys = hlx.keys("database").unwrap();
        assert!(keys.iter().any(| k | * k == "host"));
    }
    #[tokio::test]
    async fn test_operator_execution() {
        let hlx = Hlx::new().await.unwrap();
        let result = hlx.execute_operator("date", "{\"format\":\"Y-m-d\"}").await;
        println!("Direct operator execution result: {:?}", result);
        assert!(result.is_ok());
        let result = hlx.execute_operator("uuid", "").await;
        println!("UUID operator execution result: {:?}", result);
        assert!(result.is_ok());
        let result = hlx.execute_operator("nonexistent", "{}").await;
        println!("Invalid operator result: {:?}", result);
        assert!(result.is_err());
    }
    #[tokio::test]
    async fn test_operator_integration() {
        use crate::ops::OperatorParser;
        let mut ops_parser = OperatorParser::new().await;
        let result = ops_parser.parse_value("@date(\"Y-m-d\")").await.unwrap();
        match result {
            crate::dna::atp::value::Value::String(date_str) => {
                assert!(! date_str.is_empty());
                println!("✅ @date operator working: {}", date_str);
            }
            _ => panic!("Expected string result from @date"),
        }
        let result = ops_parser.parse_value("@uuid()").await.unwrap();
        match result {
            crate::dna::atp::value::Value::String(uuid_str) => {
                assert!(! uuid_str.is_empty());
                println!(
                    "✅ @uuid operator working: {} (length: {})", uuid_str, uuid_str
                    .len()
                );
            }
            _ => panic!("Expected string result from @uuid"),
        }
        use dna::ops::OperatorEngine;
        let operator_engine = OperatorEngine::new().await.unwrap();
        let result = operator_engine
            .execute_operator("date", "{\"format\":\"%Y-%m-%d\"}")
            .await
            .unwrap();
        match result {
            crate::dna::atp::value::Value::String(date_str) => {
                assert!(! date_str.is_empty());
                println!("✅ Direct date operator working: {}", date_str);
            }
            _ => panic!("Expected string result from direct date operator"),
        }
        let result = operator_engine.execute_operator("uuid", "").await.unwrap();
        match result {
            crate::dna::atp::value::Value::String(uuid_str) => {
                assert!(! uuid_str.is_empty());
                println!(
                    "✅ Direct uuid operator working: {} (length: {})", uuid_str,
                    uuid_str.len()
                );
            }
            _ => panic!("Expected string result from direct uuid operator"),
        }
        println!("✅ ops.rs and operators/ integration fully working!");
    }
    #[tokio::test]
    async fn test_comprehensive_operator_testing() {
        assert!(true);
    }
}