koicore 0.2.3

core KoiLang module
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
//! Formatting utilities for KoiLang writer
//!
//! This module contains utilities for formatting different types of values
//! and parameters in KoiLang text generation.

use super::config::{FloatFormat, FormatterOptions};
use crate::command::{CompositeValue, Parameter, Value};

/// Formatting utilities for KoiLang values
pub struct Formatters;

impl Formatters {
    /// Format a number according to the specified format.
    ///
    /// # Arguments
    ///
    /// * `num` - The integer value to format
    /// * `options` - Formatting options determining the base (decimal, hex, etc.)
    pub fn format_number(num: &i64, options: &FormatterOptions) -> String {
        let fmt = options.number_format.to_string();
        if fmt.is_empty() {
            return num.to_string();
        }
        let (prefix, radix) = match fmt.chars().last() {
            Some('x') | Some('X') => ("0x", 16),
            Some('o') => ("0o", 8),
            Some('b') => ("0b", 2),
            _ => return num.to_string(),
        };
        let spec = &fmt[..fmt.len() - 1];
        let target_width: usize = if spec.starts_with('0') && spec.len() > 1 {
            spec[1..].parse().ok().unwrap_or(0)
        } else {
            0
        };
        let unprefixed = match radix {
            16 => format!("{:x}", num),
            8 => format!("{:o}", num),
            2 => format!("{:b}", num),
            _ => return num.to_string(),
        };
        let content = if target_width > 0 {
            let pad_len = if target_width > prefix.len() {
                target_width - prefix.len()
            } else {
                0
            };
            if pad_len > unprefixed.len() {
                format!("{:>width$}", unprefixed, width = pad_len)
            } else {
                unprefixed
            }
        } else {
            unprefixed
        };
        format!("{}{}", prefix, content)
    }

    pub fn format_float(f: &f64, options: &FormatterOptions) -> String {
        match &options.float_format {
            FloatFormat::Default => f.to_string(),
            FloatFormat::Fixed(precision) => {
                let p = precision.unwrap_or(6);
                format!("{:.p$}", f, p = p)
            }
            FloatFormat::Scientific => format!("{:e}", f),
            FloatFormat::General(precision) => {
                let p = precision.unwrap_or(6);
                format!("{:.*}", p, f)
            }
            FloatFormat::Custom(fmt) => Self::apply_custom_float_format(f, fmt),
        }
    }

    fn apply_custom_float_format(f: &f64, fmt: &str) -> String {
        if fmt.is_empty() {
            return f.to_string();
        }

        let mut precision = None;
        let mut specifier = 'f';
        let mut prefix = String::new();
        let mut chars = fmt.chars().peekable();

        while let Some(c) = chars.next() {
            if c == '.' {
                let mut prec_str = String::new();
                while let Some(&next_c) = chars.peek() {
                    if next_c.is_ascii_digit() {
                        prec_str.push(chars.next().unwrap());
                    } else {
                        break;
                    }
                }
                if !prec_str.is_empty() {
                    precision = Some(prec_str.parse::<usize>().unwrap_or(6));
                } else {
                    precision = Some(6);
                }
            } else if c == 'e' || c == 'E' {
                specifier = c;
                break;
            } else if c == '+' || c == ' ' || c == '#' || c == '0' {
                prefix.push(c);
            }
        }

        let result = match specifier {
            'e' | 'E' => {
                if let Some(p) = precision {
                    format!("{:.1$e}", f, p)
                } else {
                    format!("{:e}", f)
                }
            }
            _ => {
                if let Some(p) = precision {
                    format!("{:.1$}", f, p)
                } else {
                    format!("{}", f)
                }
            }
        };

        if prefix.is_empty() {
            result
        } else {
            let sign = if result.starts_with('-') {
                "-"
            } else {
                ""
            };
            let abs_result = result.trim_start_matches('-');
            format!("{}{}{}", sign, prefix, abs_result)
        }
    }

    /// Check if a string matches variable naming rules.
    ///
    /// Variable names must start with a letter or underscore, followed by letters, numbers, or underscores.
    ///
    /// # Arguments
    ///
    /// * `s` - The string to check
    pub fn is_valid_variable_name(s: &str) -> bool {
        if s.is_empty() {
            return false;
        }

        let mut chars = s.chars();
        let first_char = chars.next().unwrap();

        // First character must be a letter or underscore
        if !first_char.is_ascii_alphabetic() && first_char != '_' {
            return false;
        }

        // Remaining characters must be letters, numbers, or underscores
        for c in chars {
            if !c.is_ascii_alphanumeric() && c != '_' {
                return false;
            }
        }

        true
    }

    /// Format a string value with appropriate quoting.
    ///
    /// Adds double quotes if the string is not a valid variable name or if forced by options.
    ///
    /// # Arguments
    ///
    /// * `s` - The string to format
    /// * `options` - Formatting options
    pub fn format_string(s: &str, options: &FormatterOptions) -> String {
        // Check if the string needs quotes
        let needs_quotes = options.force_quotes_for_vars || !Self::is_valid_variable_name(s);

        if needs_quotes {
            let mut result = String::with_capacity(s.len() + 2);
            result.push('"');
            for c in s.chars() {
                match c {
                    '"' => result.push_str("\\\""),
                    '\\' => result.push_str("\\\\"),
                    '\n' => result.push_str("\\n"),
                    '\r' => result.push_str("\\r"),
                    '\t' => result.push_str("\\t"),
                    c => result.push(c),
                }
            }
            result.push('"');
            result
        } else {
            s.to_string()
        }
    }

    /// Format a composite value (List or Dictionary).
    ///
    /// Recursively formats the values inside the composite structure.
    ///
    /// # Arguments
    ///
    /// * `value` - The composite value
    /// * `options` - Formatting options
    pub fn format_composite_value(value: &CompositeValue, options: &FormatterOptions) -> String {
        match value {
            CompositeValue::Single(val) => {
                format!("({})", Self::format_value(val, options))
            }
            CompositeValue::List(values) => {
                let mut result = "(".to_string();
                let mut first = true;

                for val in values {
                    if !first {
                        result.push(',');
                        if !options.compact {
                            result.push(' ');
                        }
                    }
                    result.push_str(&Self::format_value(val, options));
                    first = false;
                }

                result.push(')');
                result
            }
            CompositeValue::Dict(entries) => {
                let mut result = "(".to_string();
                let mut first = true;

                for (key, val) in entries {
                    if !first {
                        result.push(',');
                        if !options.compact {
                            result.push(' ');
                        }
                    }
                    result.push_str(key);
                    result.push(':');
                    if !options.compact {
                        result.push(' ');
                    }
                    result.push_str(&Self::format_value(val, options));
                    first = false;
                }

                result.push(')');
                result
            }
        }
    }

    /// Format a basic value (Int, Float, String).
    ///
    /// # Arguments
    ///
    /// * `value` - The basic value to format
    /// * `options` - Formatting options
    pub fn format_value(value: &Value, options: &FormatterOptions) -> String {
        match value {
            Value::Int(i) => Self::format_number(i, options),
            Value::Float(f) => Self::format_float(f, options),
            Value::Bool(b) => b.to_string(),
            Value::String(s) => Self::format_string(s, options),
        }
    }

    /// Format a parameter (Basic or Composite).
    ///
    /// # Arguments
    ///
    /// * `param` - The parameter to format
    /// * `options` - Formatting options
    pub fn format_parameter(param: &Parameter, options: &FormatterOptions) -> String {
        // Space before is now handled by generators.rs to avoid double spaces

        let param_text = match param {
            Parameter::Basic(value) => Self::format_value(value, options),
            Parameter::Composite(name, composite_value) => {
                format!(
                    "{}{}",
                    name,
                    Self::format_composite_value(composite_value, options)
                )
            }
        };

        param_text.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{command::{CompositeValue, Parameter, Value}, writer::NumberFormat};

    #[test]
    fn test_format_number() {
        let options = FormatterOptions::default();

        // Test decimal format (default)
        let result = Formatters::format_number(&42, &options);
        assert_eq!(result, "42");

        // Test hex format
        let options = FormatterOptions {
            number_format: NumberFormat::Hex,
            ..Default::default()
        };
        let result = Formatters::format_number(&255, &options);
        assert_eq!(result, "0xff");

        // Test octal format
        let options = FormatterOptions {
            number_format: NumberFormat::Octal,
            ..Default::default()
        };
        let result = Formatters::format_number(&63, &options);
        assert_eq!(result, "0o77");

        // Test binary format
        let options = FormatterOptions {
            number_format: NumberFormat::Binary,
            ..Default::default()
        };
        let result = Formatters::format_number(&7, &options);
        assert_eq!(result, "0b111");

        // Test negative numbers
        let options = FormatterOptions::default();
        let result = Formatters::format_number(&-42, &options);
        assert_eq!(result, "-42");

        let options = FormatterOptions {
            number_format: NumberFormat::Hex,
            ..Default::default()
        };
        let result = Formatters::format_number(&-255, &options);
        // For i64, -255 in hex is 0xffffffffffffff01
        assert_eq!(result, "0xffffffffffffff01");
    }

    #[test]
    fn test_is_valid_variable_name() {
        // Valid names
        assert!(Formatters::is_valid_variable_name("valid_name"));
        assert!(Formatters::is_valid_variable_name("_valid"));
        assert!(Formatters::is_valid_variable_name("valid123"));
        assert!(Formatters::is_valid_variable_name("a"));
        assert!(Formatters::is_valid_variable_name("A"));

        // Invalid names
        assert!(!Formatters::is_valid_variable_name("123invalid"));
        assert!(!Formatters::is_valid_variable_name("invalid-name"));
        assert!(!Formatters::is_valid_variable_name("invalid name"));
        assert!(!Formatters::is_valid_variable_name("invalid.name"));
        assert!(!Formatters::is_valid_variable_name(""));
        assert!(!Formatters::is_valid_variable_name("!invalid"));
        assert!(!Formatters::is_valid_variable_name("invalid!"));
    }

    #[test]
    fn test_format_string() {
        // Test valid variable names (no quotes needed by default)
        let options = FormatterOptions::default();
        let result = Formatters::format_string("valid_name", &options);
        assert_eq!(result, "valid_name");

        // Test invalid variable names (need quotes)
        let result = Formatters::format_string("invalid-name", &options);
        assert_eq!(result, "\"invalid-name\"");

        // Test with spaces (need quotes)
        let result = Formatters::format_string("with_spaces", &options);
        assert_eq!(result, "with_spaces");

        // Test with force_quotes_for_vars
        let options = FormatterOptions {
            force_quotes_for_vars: true,
            ..Default::default()
        };
        let result = Formatters::format_string("valid_name", &options);
        assert_eq!(result, "\"valid_name\"");
    }

    #[test]
    fn test_format_composite_value() {
        let options = FormatterOptions::default();

        // Test Single composite value
        let single_value = CompositeValue::Single(Value::Int(42));
        let result = Formatters::format_composite_value(&single_value, &options);
        assert_eq!(result, "(42)");

        // Test List composite value
        let list_value = CompositeValue::List(vec![
            Value::Int(1),
            Value::String("two".to_string()),
            Value::Int(3),
        ]);
        let result = Formatters::format_composite_value(&list_value, &options);
        assert_eq!(result, "(1, two, 3)");

        // Test List composite value in compact mode
        let options_compact = FormatterOptions {
            compact: true,
            ..Default::default()
        };
        let result = Formatters::format_composite_value(&list_value, &options_compact);
        assert_eq!(result, "(1,two,3)");

        // Test Dict composite value
        let dict_entries = vec![
            ("key1".to_string(), Value::Int(1)),
            ("key2".to_string(), Value::String("value2".to_string())),
        ];
        let dict_value = CompositeValue::Dict(dict_entries);
        let result = Formatters::format_composite_value(&dict_value, &options);
        assert_eq!(result, "(key1: 1, key2: value2)");

        // Test Dict composite value in compact mode
        let result = Formatters::format_composite_value(&dict_value, &options_compact);
        assert_eq!(result, "(key1:1,key2:value2)");
    }

    #[test]
    fn test_format_value() {
        let options = FormatterOptions::default();

        // Test Int value
        let result = Formatters::format_value(&Value::Int(42), &options);
        assert_eq!(result, "42");

        // Test Float value
        let result = Formatters::format_value(&Value::Float(3.14), &options);
        assert_eq!(result, "3.14");

        // Test String value
        let result = Formatters::format_value(&Value::String("test".to_string()), &options);
        assert_eq!(result, "test");

        // Test invalid String value (needs quotes)
        let result =
            Formatters::format_value(&Value::String("test-with-dash".to_string()), &options);
        assert_eq!(result, "\"test-with-dash\"");

        // Test negative Int
        let result = Formatters::format_value(&Value::Int(-42), &options);
        assert_eq!(result, "-42");
    }

    #[test]
    fn test_format_parameter() {
        let options = FormatterOptions::default();

        // Test Basic parameter with Int value
        let basic_param = Parameter::from(42);
        let result = Formatters::format_parameter(&basic_param, &options);
        assert_eq!(result, "42");

        // Test Basic parameter with String value
        let basic_param = Parameter::from("test");
        let result = Formatters::format_parameter(&basic_param, &options);
        assert_eq!(result, "test");

        // Test Composite parameter
        let composite_param = Parameter::Composite(
            "test_name".to_string(),
            CompositeValue::Single(Value::Int(42)),
        );
        let result = Formatters::format_parameter(&composite_param, &options);
        assert_eq!(result, "test_name(42)");

        // Test Composite parameter with List
        let composite_param = Parameter::Composite(
            "list_param".to_string(),
            CompositeValue::List(vec![Value::Int(1), Value::Int(2), Value::Int(3)]),
        );
        let result = Formatters::format_parameter(&composite_param, &options);
        assert_eq!(result, "list_param(1, 2, 3)");

        // Test Composite parameter with Dict
        let dict_entries = vec![("key".to_string(), Value::String("value".to_string()))];
        let composite_param =
            Parameter::Composite("dict_param".to_string(), CompositeValue::Dict(dict_entries));
        let result = Formatters::format_parameter(&composite_param, &options);
        assert_eq!(result, "dict_param(key: value)");
    }

    #[test]
    fn test_format_value_with_number_formats() {
        // Test different number formats for Int values
        let hex_options = FormatterOptions {
            number_format: NumberFormat::Hex,
            ..Default::default()
        };
        let result = Formatters::format_value(&Value::Int(255), &hex_options);
        assert_eq!(result, "0xff");

        let oct_options = FormatterOptions {
            number_format: NumberFormat::Octal,
            ..Default::default()
        };
        let result = Formatters::format_value(&Value::Int(63), &oct_options);
        assert_eq!(result, "0o77");

        let bin_options = FormatterOptions {
            number_format: NumberFormat::Binary,
            ..Default::default()
        };
        let result = Formatters::format_value(&Value::Int(7), &bin_options);
        assert_eq!(result, "0b111");
    }

    #[test]
    fn test_format_float() {
        // Test Default format
        let options = FormatterOptions::default();
        let result = Formatters::format_float(&3.14159, &options);
        assert_eq!(result, "3.14159");

        // Test Fixed format with precision 2
        let options = FormatterOptions {
            float_format: FloatFormat::Fixed(Some(2)),
            ..Default::default()
        };
        let result = Formatters::format_float(&3.14159, &options);
        assert_eq!(result, "3.14");

        // Test Fixed format with precision 4
        let options = FormatterOptions {
            float_format: FloatFormat::Fixed(Some(4)),
            ..Default::default()
        };
        let result = Formatters::format_float(&3.14159, &options);
        assert_eq!(result, "3.1416");

        // Test Fixed format with None (default 6)
        let options = FormatterOptions {
            float_format: FloatFormat::Fixed(None),
            ..Default::default()
        };
        let result = Formatters::format_float(&3.1415926535, &options);
        assert_eq!(result, "3.141593");

        // Test Scientific format
        let options = FormatterOptions {
            float_format: FloatFormat::Scientific,
            ..Default::default()
        };
        let result = Formatters::format_float(&0.001, &options);
        assert_eq!(result, "1e-3");

        // Test Custom format with precision
        let options = FormatterOptions {
            float_format: FloatFormat::Custom(".3f".to_string()),
            ..Default::default()
        };
        let result = Formatters::format_float(&3.14159, &options);
        assert_eq!(result, "3.142");

        // Test Custom format with sign prefix
        let options = FormatterOptions {
            float_format: FloatFormat::Custom("+.0f".to_string()),
            ..Default::default()
        };
        let result = Formatters::format_float(&3.7, &options);
        assert_eq!(result, "+4");

        // Test Custom format with scientific notation
        let options = FormatterOptions {
            float_format: FloatFormat::Custom(".2e".to_string()),
            ..Default::default()
        };
        let result = Formatters::format_float(&3.14159, &options);
        assert_eq!(result, "3.14e0");
    }

    #[test]
    fn test_format_value_with_float_formats() {
        // Test Float value with Fixed format
        let fixed_options = FormatterOptions {
            float_format: FloatFormat::Fixed(Some(2)),
            ..Default::default()
        };
        let result = Formatters::format_value(&Value::Float(3.14159), &fixed_options);
        assert_eq!(result, "3.14");

        // Test Float value with Scientific format
        let sci_options = FormatterOptions {
            float_format: FloatFormat::Scientific,
            ..Default::default()
        };
        let result = Formatters::format_value(&Value::Float(0.001), &sci_options);
        assert_eq!(result, "1e-3");

        // Test Float value with Custom format
        let custom_options = FormatterOptions {
            float_format: FloatFormat::Custom("+.0f".to_string()),
            ..Default::default()
        };
        let result = Formatters::format_value(&Value::Float(3.7), &custom_options);
        assert_eq!(result, "+4");
    }
}