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
//! Writer module for KoiLang
//!
//! This module provides functionality to generate KoiLang text from parsed commands.
//! It supports flexible formatting options and can write to any output that implements
//! the `Write` trait.

use crate::command::Command;
use std::collections::HashMap;
use std::io::Write;

// Re-export configuration types
pub use self::config::{FloatFormat, FormatterOptions, NumberFormat, ParamFormatSelector, WriterConfig};

// Internal modules
mod config;
mod formatters;
mod generators;

/// KoiLang writer that can write to any output implementing the `Write` trait
pub struct Writer<T: Write> {
    writer: T,
    config: WriterConfig,
    current_indent: usize,
    last_was_newline: bool,
}

impl<T: Write> Writer<T> {
    /// Create a new KoiLang writer
    ///
    /// # Arguments
    /// * `writer` - Output to write to
    /// * `config` - Configuration for the writer
    pub fn new(writer: T, config: WriterConfig) -> Self {
        Self {
            writer,
            config,
            current_indent: 0,
            last_was_newline: false,
        }
    }

    /// Write a command using the default formatting options
    pub fn write_command(&mut self, command: &Command) -> std::io::Result<()> {
        self.write_command_with_options(command, None, None)
    }

    /// Write a command with custom formatting options, including parameter-specific options
    pub fn write_command_with_options(
        &mut self,
        command: &Command,
        options: Option<&FormatterOptions>,
        param_options: Option<&HashMap<ParamFormatSelector, &FormatterOptions>>,
    ) -> std::io::Result<()> {
        // Get the appropriate formatting options
        let effective_options =
            generators::Generators::get_effective_options(&command.name, options, &self.config);

        // Write additional newline before if needed and not already at start of line
        if effective_options.newline_before && !self.last_was_newline {
            self.newline()?;
        }

        // Write indentation
        generators::Generators::write_indent(
            &mut self.writer,
            self.current_indent,
            &effective_options,
        )?;

        // Write the command with parameter-specific formatting
        generators::Generators::write_command_with_param_options(
            &mut self.writer,
            command,
            &self.config,
            &effective_options,
            param_options,
            self.current_indent,
        )?;

        // Add a newline after the command
        writeln!(self.writer)?;

        // Write additional newline after if needed and not already at end of line
        if effective_options.newline_after {
            self.newline()?;
        } else {
            // Update last_was_newline based on the command content
            // For simplicity, we'll assume non-newline ending for now
            self.last_was_newline = false;
        }

        Ok(())
    }

    /// Increase the indentation level by 1
    pub fn inc_indent(&mut self) {
        self.current_indent += 1;
    }

    /// Decrease the indentation level by 1, but not below 0
    pub fn dec_indent(&mut self) {
        if self.current_indent > 0 {
            self.current_indent -= 1;
        }
    }

    /// Get the current indentation level
    pub fn get_indent(&self) -> usize {
        self.current_indent
    }

    pub fn newline(&mut self) -> std::io::Result<()> {
        writeln!(self.writer)?;
        self.last_was_newline = true;
        Ok(())
    }
}

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

    #[test]
    fn test_write_basic_command() {
        let cmd = Command::new(
            "character",
            vec![Parameter::from("Alice"), Parameter::from("Hello, world!")],
        );

        let config = WriterConfig::default();
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        writer.write_command(&cmd).unwrap();

        let result = String::from_utf8(buffer).unwrap();
        assert_eq!(result, "#character Alice \"Hello, world!\"\n");
    }

    #[test]
    fn test_write_text_command() {
        let cmd = Command::new_text("Hello, world!");

        let config = WriterConfig::default();
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        writer.write_command(&cmd).unwrap();

        let result = String::from_utf8(buffer).unwrap();
        assert_eq!(result, "Hello, world!\n");
    }

    #[test]
    fn test_write_annotation_command() {
        let cmd = Command::new_annotation("This is an annotation");

        let config = WriterConfig::default();
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        writer.write_command(&cmd).unwrap();

        let result = String::from_utf8(buffer).unwrap();
        assert_eq!(result, "## This is an annotation\n");
    }

    #[test]
    fn test_write_number_command() {
        let cmd = Command::new_number(123, vec![Parameter::from("extra")]);

        let config = WriterConfig::default();
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        writer.write_command(&cmd).unwrap();

        let result = String::from_utf8(buffer).unwrap();
        assert_eq!(result, "#123 extra\n");
    }

    #[test]
    fn test_write_with_custom_options() {
        let cmd = Command::new("character", vec![Parameter::from("Alice")]);

        let config = WriterConfig::default();
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        let custom_options = FormatterOptions {
            newline_before: true,
            newline_after: true,
            ..Default::default()
        };

        writer
            .write_command_with_options(&cmd, Some(&custom_options), None)
            .unwrap();

        let result = String::from_utf8(buffer).unwrap();
        assert_eq!(result, "\n#character Alice\n\n");
    }

    #[test]
    fn test_write_with_force_quotes() {
        let cmd = Command::new(
            "character",
            vec![Parameter::from("Alice"), Parameter::from("Bob")],
        );

        let config = WriterConfig {
            global_options: FormatterOptions {
                force_quotes_for_vars: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        writer.write_command(&cmd).unwrap();

        let result = String::from_utf8(buffer).unwrap();
        assert_eq!(result, "#character \"Alice\" \"Bob\"\n");
    }

    #[test]
    fn test_write_with_invalid_var_names() {
        let cmd = Command::new(
            "character",
            vec![
                Parameter::from("123invalid"),
                Parameter::from("with spaces"),
            ],
        );

        let config = WriterConfig::default();
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        writer.write_command(&cmd).unwrap();

        let result = String::from_utf8(buffer).unwrap();
        assert_eq!(result, "#character \"123invalid\" \"with spaces\"\n");
    }

    #[test]
    fn test_write_with_number_formats() {
        let cmd = Command::new(
            "test",
            vec![
                Parameter::from(42),
                Parameter::from(255),
                Parameter::from(7),
            ],
        );

        // Test parameter-specific number formats
        let mut param_options = HashMap::new();

        // Set first parameter to hex
        let hex_opt = FormatterOptions {
            number_format: NumberFormat::Hex,
            ..Default::default()
        };
        param_options.insert(ParamFormatSelector::Position(0), &hex_opt);

        // Set second parameter to octal
        let octal_opt = FormatterOptions {
            number_format: NumberFormat::Octal,
            ..Default::default()
        };
        param_options.insert(ParamFormatSelector::Position(1), &octal_opt);

        // Set third parameter to binary
        let binary_opt = FormatterOptions {
            number_format: NumberFormat::Binary,
            ..Default::default()
        };
        param_options.insert(ParamFormatSelector::Position(2), &binary_opt);

        let config = WriterConfig::default();
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        writer
            .write_command_with_options(&cmd, None, Some(&param_options))
            .unwrap();

        let result = String::from_utf8(buffer).unwrap();
        assert_eq!(result, "#test 0x2a 0o377 0b111\n");
    }

    #[test]
    fn test_write_with_param_newlines() {
        let cmd = Command::new(
            "test",
            vec![
                Parameter::from("param1"),
                Parameter::from("param2"),
                Parameter::from("param3"),
            ],
        );

        // Test parameter-specific newlines
        let mut param_options = HashMap::new();

        // Add newline after first parameter
        let nl_after = FormatterOptions {
            newline_after_param: true,
            ..Default::default()
        };
        param_options.insert(ParamFormatSelector::Position(0), &nl_after);

        // Add newline before third parameter
        let nl_before = FormatterOptions {
            newline_before_param: true,
            ..Default::default()
        };
        param_options.insert(ParamFormatSelector::Position(2), &nl_before);

        let config = WriterConfig::default();
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        writer
            .write_command_with_options(&cmd, None, Some(&param_options))
            .unwrap();

        let result = String::from_utf8(buffer).unwrap();
        assert_eq!(result, "#test param1\n    param2\n    param3\n");
    }

    #[test]
    fn test_write_without_repeat_newlines() {
        let cmd = Command::new(
            "test",
            vec![Parameter::from("param1"), Parameter::from("param2")],
        );

        // Test that consecutive newlines are not repeated
        let mut param_options = HashMap::new();

        // Add newline after first parameter
        let nl_after = FormatterOptions {
            newline_after_param: true,
            ..Default::default()
        };
        param_options.insert(ParamFormatSelector::Position(0), &nl_after);

        // Add newline before second parameter (should not create double newline)
        let nl_before = FormatterOptions {
            newline_before_param: true,
            ..Default::default()
        };
        param_options.insert(ParamFormatSelector::Position(1), &nl_before);

        let config = WriterConfig::default();
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        writer
            .write_command_with_options(&cmd, None, Some(&param_options))
            .unwrap();

        let result = String::from_utf8(buffer).unwrap();
        // Should only have one newline between parameters, not two
        assert_eq!(result, "#test param1\n    param2\n");
    }

    #[test]
    fn test_write_with_composite_param_formatting() {
        let cmd = Command::new(
            "test",
            vec![
                Parameter::from("regular"),
                Parameter::from(("composite", 42)),
                Parameter::from("another"),
            ],
        );

        // Test formatting composite parameters by name
        let mut param_options = HashMap::new();

        // Format composite parameter to hex
        let hex_opt = FormatterOptions {
            number_format: NumberFormat::Hex,
            ..Default::default()
        };
        param_options.insert(ParamFormatSelector::Name("composite".to_string()), &hex_opt);

        let config = WriterConfig::default();
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        writer
            .write_command_with_options(&cmd, None, Some(&param_options))
            .unwrap();

        let result = String::from_utf8(buffer).unwrap();
        assert_eq!(result, "#test regular composite(0x2a) another\n");
    }

    #[test]
    fn test_mutliline_command() {
        let cmd = Command::new(
            "test",
            vec![
                Parameter::from("regular"),
                Parameter::from(("composite", 42)),
                Parameter::from("another"),
            ],
        );

        let config = WriterConfig::default();
        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer, config);

        writer.write_command(&cmd).unwrap();
        writer.write_command(&cmd).unwrap();

        let result = String::from_utf8(buffer).unwrap();
        assert_eq!(
            result,
            "#test regular composite(42) another\n#test regular composite(42) another\n"
        );
    }
}