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
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
//! Command structures for KoiLang parsing
//!
//! This module defines the data structures used to represent parsed commands
//! and their arguments in a unified format. Commands are the fundamental building
//! blocks of KoiLang files, representing actions, text content, and annotations.
//!
//! ## Core Types
//!
//! - [`Value`] - Basic value types (integers, floats, strings)
//! - [`CompositeValue`] - Complex value types (lists, dictionaries)
//! - [`Parameter`] - Command parameters that can be basic or composite
//! - [`Command`] - Complete commands with name and parameters
//!
//! ## Examples
//!
//! ```rust
//! use koicore::command::{Command, Parameter, Value, CompositeValue};
//!
//! // Create a simple command
//! let cmd = Command::new("character", vec![
//!     Parameter::from("Alice"),
//!     Parameter::from("Hello, world!")
//! ]);
//!
//! // Create a command with composite parameters
//! let cmd = Command::new("action", vec![
//!     Parameter::from(("type", "walk")),
//!     Parameter::from(("direction", "left")),
//!     Parameter::Composite("speed".to_string(), CompositeValue::Single(Value::Int(5)))
//! ]);
//!
//! // Create text and annotation commands
//! let text_cmd = Command::new_text("Hello, world!");
//! let annotation_cmd = Command::new_annotation("This is an annotation");
//! ```

use std::{collections::HashMap, fmt};

#[cfg(feature = "serde")]
use serde::{
    Deserialize, Deserializer, Serialize, Serializer,
    de::{self, Visitor},
};

/// Basic value types supported by KoiLang
///
/// Represents the fundamental data types that can appear as command parameters
/// or within composite values.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(untagged))]
pub enum Value {
    /// Integer values (64-bit signed)
    Int(i64),
    /// Floating-point values (64-bit)
    Float(f64),
    /// Boolean values
    Bool(bool),
    /// String values (UTF-8 encoded)
    String(String),
}

impl From<i64> for Value {
    fn from(i: i64) -> Self {
        Self::Int(i)
    }
}

impl From<f64> for Value {
    fn from(f: f64) -> Self {
        Self::Float(f)
    }
}

impl From<bool> for Value {
    fn from(v: bool) -> Self {
        Value::Bool(v)
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Self::String(s)
    }
}

impl From<&'_ str> for Value {
    fn from(s: &'_ str) -> Self {
        Self::String(s.to_string())
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Int(i) => write!(f, "{}", i),
            Value::Float(fl) => write!(f, "{}", fl),
            Value::Bool(b) => write!(f, "{}", b),
            Value::String(s) => {
                // Check if the string needs to be quoted
                // It needs quoting if:
                // 1. It is empty
                // 2. It contains characters that are not allowed in unquoted identifiers (alphanumeric + '_')
                // 3. It starts with a digit (which would be parsed as a number)
                let needs_quotes = s.is_empty()
                    || !s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
                    || s.chars()
                        .next()
                        .map(|c| c.is_ascii_digit())
                        .unwrap_or(false);

                if needs_quotes {
                    write!(f, "\"")?;
                    for c in s.chars() {
                        match c {
                            '"' => write!(f, "\\\"")?,
                            '\\' => write!(f, "\\\\")?,
                            '\n' => write!(f, "\\n")?,
                            '\r' => write!(f, "\\r")?,
                            '\t' => write!(f, "\\t")?,
                            // We don't strictly need to escape other control chars for valid parsing,
                            // but we could. For now, just basic text escapes.
                            c => write!(f, "{}", c)?,
                        }
                    }
                    write!(f, "\"")
                } else {
                    write!(f, "{}", s)
                }
            }
        }
    }
}

/// Composite value types that can contain multiple basic values
///
/// Represents complex data structures that can appear as command parameters,
/// including lists and dictionaries.
#[derive(Debug, Clone, PartialEq)]
pub enum CompositeValue {
    /// Single basic value
    Single(Value),
    /// List of basic values
    List(Vec<Value>),
    /// Dictionary mapping strings to values
    Dict(Vec<(String, Value)>),
}

impl<T: Into<Value>> From<T> for CompositeValue {
    fn from(v: T) -> Self {
        Self::Single(v.into())
    }
}

impl<T: Into<Value>> From<Vec<T>> for CompositeValue {
    fn from(v: Vec<T>) -> Self {
        Self::List(v.into_iter().map(|item| item.into()).collect())
    }
}

impl<T: Into<Value>> From<HashMap<String, T>> for CompositeValue {
    fn from(v: HashMap<String, T>) -> Self {
        Self::Dict(v.into_iter().map(|(k, v)| (k, v.into())).collect())
    }
}

impl<T: Into<Value>> FromIterator<T> for CompositeValue {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Self::List(iter.into_iter().map(|item| item.into()).collect())
    }
}

impl<T: Into<Value>> FromIterator<(String, T)> for CompositeValue {
    fn from_iter<I: IntoIterator<Item = (String, T)>>(iter: I) -> Self {
        Self::Dict(iter.into_iter().map(|(k, v)| (k, v.into())).collect())
    }
}

impl fmt::Display for CompositeValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CompositeValue::Single(value) => write!(f, "{}", value),
            CompositeValue::List(values) => {
                for (i, value) in values.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", value)?;
                }
                Ok(())
            }
            CompositeValue::Dict(entries) => {
                for (i, (key, value)) in entries.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}: {}", key, value)?;
                }
                Ok(())
            }
        }
    }
}

/// Command parameter types
///
/// Parameters can be either basic values or composite values with names.
/// This allows for flexible command structures in KoiLang.
#[derive(Debug, Clone, PartialEq)]
pub enum Parameter {
    /// Basic parameter containing only a value
    Basic(Value),
    /// Named composite parameter (e.g., `name(value)` or `name(list)`)
    Composite(String, CompositeValue),
}

impl<T: Into<Value>> From<T> for Parameter {
    fn from(v: T) -> Self {
        Self::Basic(v.into())
    }
}

impl<K: Into<String>, V: Into<CompositeValue>> From<(K, V)> for Parameter {
    fn from(v: (K, V)) -> Self {
        Self::Composite(v.0.into(), v.1.into())
    }
}

impl fmt::Display for Parameter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Parameter::Basic(value) => write!(f, "{}", value),
            Parameter::Composite(name, value) => write!(f, "{}({})", name, value),
        }
    }
}

/// Represents a complete KoiLang command
///
/// Commands are the fundamental units of KoiLang files, consisting of a name
/// and zero or more parameters. They can represent actions, text content, or annotations.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Command {
    /// The command name (e.g., "character", "background", "@text")
    pub name: String,
    /// List of command parameters
    pub params: Vec<Parameter>,
}

impl Command {
    /// Create a new command with the specified name and parameters
    ///
    /// # Arguments
    /// * `name` - The command name (can be `&str` or `String`)
    /// * `params` - Vector of command parameters
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::command::{Command, Parameter, Value};
    ///
    /// // Using &str
    /// let cmd = Command::new("character", vec![
    ///     Parameter::from("Alice"),
    ///     Parameter::from("Hello!")
    /// ]);
    ///
    /// // Using String
    /// let cmd = Command::new("character".to_string(), vec![
    ///     Parameter::from("Alice"),
    ///     Parameter::from("Hello!")
    /// ]);
    /// ```
    pub fn new(name: impl Into<String>, params: Vec<Parameter>) -> Self {
        Self {
            name: name.into(),
            params,
        }
    }

    /// Create a text command representing regular content
    ///
    /// Text commands are created for lines that don't start with the command prefix.
    /// They use the special "@text" command name.
    ///
    /// # Arguments
    /// * `content` - The text content (can be `&str` or `String`)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::command::Command;
    ///
    /// // Using &str
    /// let text_cmd = Command::new_text("Hello, world!");
    ///
    /// // Using String
    /// let text_cmd = Command::new_text("Hello, world!".to_string());
    /// ```
    pub fn new_text(content: impl Into<String>) -> Self {
        Self::new("@text", vec![Parameter::from(content.into())])
    }

    /// Create an annotation command
    ///
    /// Annotation commands are created for lines with more `#` characters than
    /// the command threshold. They use the special "@annotation" command name.
    ///
    /// # Arguments
    /// * `content` - The annotation content (can be `&str` or `String`)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::command::Command;
    ///
    /// // Using &str
    /// let annotation_cmd = Command::new_annotation("This is an annotation");
    ///
    /// // Using String
    /// let annotation_cmd = Command::new_annotation("This is an annotation".to_string());
    /// ```
    pub fn new_annotation(content: impl Into<String>) -> Self {
        Self::new("@annotation", vec![Parameter::from(content.into())])
    }

    /// Create a number command with integer value and additional parameters
    ///
    /// This is a convenience method for creating commands that start with a number.
    ///
    /// # Arguments
    /// * `value` - The integer value
    /// * `args` - Additional parameters
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::command::{Command, Parameter};
    ///
    /// let num_cmd = Command::new_number(114, vec![]);
    /// let num_cmd_with_args = Command::new_number(42, vec![Parameter::from("extra")]);
    /// ```
    pub fn new_number(value: i64, args: Vec<Parameter>) -> Self {
        let mut all_args = vec![Parameter::from(value)];
        all_args.extend(args);
        Self::new("@number", all_args)
    }

    /// Get the command name
    ///
    /// Returns a reference to the command name string.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the command parameters
    ///
    /// Returns a slice of all parameters associated with this command.
    pub fn params(&self) -> &[Parameter] {
        &self.params
    }
}

impl fmt::Display for Command {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name)?;
        for param in self.params.iter() {
            write!(f, " ")?;
            write!(f, "{}", param)?;
        }
        Ok(())
    }
}

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

    #[test]
    fn test_command_display() {
        let cmd = Command::new("hello", vec![Parameter::Basic("world".to_string().into())]);
        assert_eq!(format!("{}", cmd), "hello world");
    }

    #[test]
    fn test_command_display_text() {
        let cmd = Command::new_text("hello world");
        assert_eq!(format!("{}", cmd), "@text \"hello world\"");
    }

    #[test]
    fn test_command_display_annotation() {
        let cmd = Command::new_annotation("hello world".to_string());
        assert_eq!(format!("{}", cmd), "@annotation \"hello world\"");
    }

    #[test]
    fn test_convert_value() {
        let cv = Parameter::from(10);
        assert_eq!(format!("{}", cv), "10");
        let cv = Parameter::from(("a", 10));
        assert_eq!(format!("{}", cv), "a(10)");
    }

    #[test]
    fn test_value_display_escaping() {
        let v = Value::String("quote \" and backslash \\".to_string());
        assert_eq!(format!("{}", v), "\"quote \\\" and backslash \\\\\"");

        let v = Value::String("newline \n and tab \t".to_string());
        assert_eq!(format!("{}", v), "\"newline \\n and tab \\t\"");
    }

    #[test]
    fn test_float_display() {
        let v = Value::Float(1.23);
        assert_eq!(format!("{}", v), "1.23");
    }

    #[test]
    fn test_composite_value_conversions() {
        // Test From<Vec<T>>
        let vec_int = vec![1, 2, 3];
        let cv: CompositeValue = CompositeValue::from(vec_int);
        if let CompositeValue::List(list) = cv {
            assert_eq!(list.len(), 3);
            assert_eq!(list[0], Value::Int(1));
        } else {
            panic!("Expected List");
        }

        // Test FromIterator
        let iter = vec![4, 5, 6].into_iter();
        let cv: CompositeValue = iter.collect();
        if let CompositeValue::List(list) = cv {
            assert_eq!(list.len(), 3);
            assert_eq!(list[0], Value::Int(4));
        } else {
            panic!("Expected List");
        }

        // Test From<HashMap> - HashMap iteration order is random, so check existence
        let mut map = HashMap::new();
        map.insert("k1".to_string(), 1);
        let cv: CompositeValue = CompositeValue::from(map);
        if let CompositeValue::Dict(entries) = cv {
            assert_eq!(entries.len(), 1);
            assert_eq!(entries[0].0, "k1");
            assert_eq!(entries[0].1, Value::Int(1));
        } else {
            panic!("Expected Dict");
        }

        // Test FromIterator for Dict
        let map_iter = vec![("k2".to_string(), 2)].into_iter();
        let cv: CompositeValue = map_iter.collect();
        if let CompositeValue::Dict(entries) = cv {
            assert_eq!(entries.len(), 1);
            assert_eq!(entries[0].0, "k2");
        } else {
            panic!("Expected Dict");
        }
    }

    #[test]
    fn test_composite_value_display() {
        // Test List display
        let list = CompositeValue::List(vec![Value::Int(1), Value::Int(2), Value::Int(3)]);
        assert_eq!(format!("{}", list), "1, 2, 3");

        // Test Dict display
        let dict = CompositeValue::Dict(vec![
            ("key1".to_string(), Value::Int(1)),
            ("key2".to_string(), Value::String("value".to_string())),
        ]);
        assert_eq!(format!("{}", dict), "key1: 1, key2: value");

        // Test Single display (already covered but for completeness)
        let single = CompositeValue::Single(Value::Int(42));
        assert_eq!(format!("{}", single), "42");
    }
}

#[cfg(feature = "serde")]
impl Serialize for CompositeValue {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            CompositeValue::Single(v) => v.serialize(serializer),
            CompositeValue::List(l) => l.serialize(serializer),
            CompositeValue::Dict(d) => {
                use serde::ser::SerializeMap;
                let mut map = serializer.serialize_map(Some(d.len()))?;
                for (k, v) in d {
                    map.serialize_entry(k, v)?;
                }
                map.end()
            }
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for CompositeValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct CompositeValueVisitor;

        impl<'de> Visitor<'de> for CompositeValueVisitor {
            type Value = CompositeValue;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a value, list, or dictionary")
            }

            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(CompositeValue::Single(Value::Int(v)))
            }

            fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(CompositeValue::Single(Value::Float(v)))
            }

            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(CompositeValue::Single(Value::Bool(v)))
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(CompositeValue::Single(Value::String(v.to_string())))
            }

            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(CompositeValue::Single(Value::String(v)))
            }

            fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
            where
                V: de::SeqAccess<'de>,
            {
                let mut values = Vec::new();
                while let Some(value) = visitor.next_element()? {
                    values.push(value);
                }
                Ok(CompositeValue::List(values))
            }

            fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
            where
                M: de::MapAccess<'de>,
            {
                let mut entries = Vec::new();
                while let Some((key, value)) = access.next_entry()? {
                    entries.push((key, value));
                }
                Ok(CompositeValue::Dict(entries))
            }
        }

        deserializer.deserialize_any(CompositeValueVisitor)
    }
}

#[cfg(feature = "serde")]
impl Serialize for Parameter {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Parameter::Basic(v) => v.serialize(serializer),
            Parameter::Composite(k, v) => {
                use serde::ser::SerializeMap;
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry(k, v)?;
                map.end()
            }
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Parameter {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ParameterVisitor;

        impl<'de> Visitor<'de> for ParameterVisitor {
            type Value = Parameter;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a basic value or a named composite parameter")
            }

            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(Parameter::Basic(Value::Int(v)))
            }

            fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(Parameter::Basic(Value::Float(v)))
            }

            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(Parameter::Basic(Value::Bool(v)))
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(Parameter::Basic(Value::String(v.to_string())))
            }

            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(Parameter::Basic(Value::String(v)))
            }

            fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
            where
                M: de::MapAccess<'de>,
            {
                if let Some((key, value)) = access.next_entry()? {
                    // Ensure only one entry for Composite parameter
                    if access.next_entry::<String, CompositeValue>()?.is_some() {
                        return Err(de::Error::custom(
                            "Composite parameter map must have exactly one entry",
                        ));
                    }
                    Ok(Parameter::Composite(key, value))
                } else {
                    Err(de::Error::custom("Composite parameter map cannot be empty"))
                }
            }
        }

        deserializer.deserialize_any(ParameterVisitor)
    }
}