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
use koicore::writer::{NumberFormat, ParamFormatSelector};
use koicore::{
    Command, FormatterOptions, Parameter, Writer, WriterConfig,
    parser::{Parser, ParserConfig, StringInputSource},
};

use std::collections::HashMap;

// Test Writer-Parser compatibility for various formatting options
#[test]
fn test_writer_parser_compatibility() {
    let test_cases = vec![
        Command::new(
            "test1",
            vec![
                Parameter::from("string"),
                Parameter::from(42),
                Parameter::from(3.14),
            ],
        ),
        Command::new(
            "test2",
            vec![Parameter::from("no_quotes"), Parameter::from(0xff)],
        ),
        Command::new(
            "test3",
            vec![Parameter::from("with spaces"), Parameter::from(1000)],
        ),
    ];

    let config = WriterConfig::default();

    // Test with default options
    for command in test_cases {
        // Generate text with writer
        let mut output = Vec::new();
        let mut writer = Writer::new(&mut output, config.clone());
        writer
            .write_command(&command)
            .expect("Failed to write command");
        let generated = String::from_utf8(output).unwrap();

        // Parse it back directly
        let input = StringInputSource::new(generated.as_str());
        let parser_config = ParserConfig::default();
        let mut parser = Parser::new(input, parser_config);

        let parsed = parser.next_command();
        assert!(
            parsed.is_ok(),
            "Failed to parse generated command: {}",
            generated
        );
        let parsed_command = parsed.unwrap();
        assert!(
            parsed_command.is_some(),
            "No command parsed from: {}",
            generated
        );
        let parsed_command = parsed_command.unwrap();

        // Check if the parsed command matches the original
        assert_eq!(parsed_command, command);
    }
}

// Test Parser-Writer compatibility for various formatting options
#[test]
fn test_parser_writer_compatibility() {
    let test_cases: Vec<(&str, WriterConfig)> = vec![
        (
            "#simple param1 param2",
            WriterConfig::default(),
        ),
        (
            "#cmd \"Hello World\"",
            WriterConfig::default(),
        ),
        (
            "#cmd 123",
            WriterConfig::default(),
        ),
        (
            "#cmd key(value)",
            WriterConfig::default(),
        ),
        (
            "#cmd pos(x: 10, y: 20)",
            WriterConfig::default(),
        ),
        (
            "#hex_cmd 0xff",
            WriterConfig {
                command_options: vec![(
                    "hex_cmd".to_string(),
                    FormatterOptions {
                        number_format: NumberFormat::Hex,
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
                ..Default::default()
            },
        ),
        (
            "#hex_cmd 0x2a 0x10",
            WriterConfig {
                command_options: vec![(
                    "hex_cmd".to_string(),
                    FormatterOptions {
                        number_format: NumberFormat::Hex,
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
                ..Default::default()
            },
        ),
        (
            "#bin_cmd 0b1010",
            WriterConfig {
                command_options: vec![(
                    "bin_cmd".to_string(),
                    FormatterOptions {
                        number_format: NumberFormat::Binary,
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
                ..Default::default()
            },
        ),
        (
            "#oct_cmd 0o77",
            WriterConfig {
                command_options: vec![(
                    "oct_cmd".to_string(),
                    FormatterOptions {
                        number_format: NumberFormat::Octal,
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
                ..Default::default()
            },
        ),
        (
            "#quoted_cmd \"var1\" \"var2\"",
            WriterConfig {
                command_options: vec![(
                    "quoted_cmd".to_string(),
                    FormatterOptions {
                        force_quotes_for_vars: true,
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
                ..Default::default()
            },
        ),
        (
            "#cmd true false",
            WriterConfig::default(),
        ),
        (
            "#cmd 3.14",
            WriterConfig::default(),
        ),
        (
            "Just plain text",
            WriterConfig::default(),
        ),
        (
            "## This is an annotation",
            WriterConfig::default(),
        ),
        (
            "#123 extra_param",
            WriterConfig::default(),
        ),
        (
            "#cmd a b c d e",
            WriterConfig::default(),
        ),
        (
            "#cmd",
            WriterConfig::default(),
        ),
        (
            "#cmd 42 string_var true false 3.14",
            WriterConfig::default(),
        ),
        (
            "#cmd color(255, 255, 255)",
            WriterConfig::default(),
        ),
        (
            "#cmd with_underscore and123number",
            WriterConfig::default(),
        ),
        (
            "#cmd \"with space\" \"and tab\"",
            WriterConfig::default(),
        ),
        (
            "#cmd \"escaped\\\\backslash\" \"newline\\nhere\"",
            WriterConfig::default(),
        ),
        (
            "#cmd -42 -3.14",
            WriterConfig::default(),
        ),
    ];

    let parser_config = ParserConfig::default();

    for (original, config) in test_cases {
        let input = StringInputSource::new(original);
        let mut parser = Parser::new(input, parser_config.clone());

        let parsed = parser.next_command();
        assert!(
            parsed.is_ok(),
            "Failed to parse: {}",
            original
        );
        let parsed_command = parsed.unwrap();
        assert!(
            parsed_command.is_some(),
            "No command parsed from: {}",
            original
        );
        let parsed_command = parsed_command.unwrap();

        let mut output = Vec::new();
        let mut writer = Writer::new(&mut output, config);
        writer
            .write_command(&parsed_command)
            .expect("Failed to write command");
        let generated = String::from_utf8(output).unwrap();

        assert_eq!(
            generated.trim_end(),
            original,
            "Generated text does not match original:\n  original: {:?}\n  generated: {:?}",
            original,
            generated.trim_end()
        );
    }
}

// Test Writer-Parser compatibility with parameter-specific formatting
#[test]
fn test_writer_parser_param_specific() {
    let command = Command::new(
        "param_test",
        vec![
            Parameter::from(42),
            Parameter::from(255),
            Parameter::from(100),
        ],
    );

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

    // Set different formats for different parameters
    let mut param_options = HashMap::new();

    // First parameter in hex
    let hex_options = FormatterOptions {
        number_format: NumberFormat::Hex,
        ..Default::default()
    };
    param_options.insert(ParamFormatSelector::Position(0), &hex_options);

    // Second parameter in binary with space before
    let bin_options = FormatterOptions {
        number_format: NumberFormat::Binary,
        ..Default::default()
    };
    param_options.insert(ParamFormatSelector::Position(1), &bin_options);

    // Third parameter in octal
    let oct_options = FormatterOptions {
        number_format: NumberFormat::Octal,
        ..Default::default()
    };
    param_options.insert(ParamFormatSelector::Position(2), &oct_options);

    writer
        .write_command_with_options(&command, None, Some(&param_options))
        .expect("Failed to write with parameter-specific options");
    let generated = String::from_utf8(output).unwrap();

    // Parse it back
    let input = StringInputSource::new(generated.as_str());
    let parser_config = ParserConfig::default();
    let mut parser = Parser::new(input, parser_config);

    let parsed = parser.next_command();
    assert!(
        parsed.is_ok(),
        "Failed to parse generated command: {}",
        generated
    );
    let parsed_command = parsed.unwrap();
    assert!(
        parsed_command.is_some(),
        "No command parsed from: {}",
        generated
    );
    let parsed_command = parsed_command.unwrap();

    // Check if the parsed command matches the original
    assert_eq!(parsed_command.name(), command.name());
    assert_eq!(parsed_command.params.len(), command.params.len());
}

// Test Writer-Parser compatibility with newline formatting
#[test]
fn test_writer_parser_newlines() {
    let command = Command::new(
        "newline_test",
        vec![
            Parameter::from("param1"),
            Parameter::from("param2"),
            Parameter::from("param3"),
        ],
    );

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

    // Set newline after each parameter
    let mut param_options = HashMap::new();

    let newline_options = FormatterOptions {
        newline_after_param: true,
        ..Default::default()
    };

    param_options.insert(ParamFormatSelector::Position(0), &newline_options);
    param_options.insert(ParamFormatSelector::Position(1), &newline_options);
    param_options.insert(ParamFormatSelector::Position(2), &newline_options);

    writer
        .write_command_with_options(&command, None, Some(&param_options))
        .expect("Failed to write with newlines");
    let generated = String::from_utf8(output).unwrap();

    // Parse it back
    let input = StringInputSource::new(generated.as_str());
    let parser_config = ParserConfig::default();
    let mut parser = Parser::new(input, parser_config);

    // Check that we can parse the command without errors
    let parsed = parser.next_command();
    assert!(
        parsed.is_ok(),
        "Failed to parse generated command with newlines: {}",
        generated
    );
    let parsed_command = parsed.unwrap();
    assert!(
        parsed_command.is_some(),
        "No command parsed from: {}",
        generated
    );
    let parsed_command = parsed_command.unwrap();

    // Check if the parsed command matches the original
    assert_eq!(parsed_command.name(), command.name());
}

// Test Writer-Parser compatibility with compact formatting
#[test]
fn test_writer_parser_compact() {
    let command = Command::new(
        "compact_test",
        vec![
            Parameter::from("string"),
            Parameter::from(42),
            Parameter::from(3.14),
        ],
    );

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

    let mut compact_options = FormatterOptions::default();
    compact_options.compact = true;
    writer
        .write_command_with_options(&command, Some(&compact_options), None)
        .expect("Failed to write compact");
    let generated = String::from_utf8(output).unwrap();

    // Parse it back
    let input = StringInputSource::new(generated.as_str());
    let parser_config = ParserConfig::default();
    let mut parser = Parser::new(input, parser_config);

    let parsed = parser.next_command();
    assert!(
        parsed.is_ok(),
        "Failed to parse generated compact command: {}",
        generated
    );
    let parsed_command = parsed.unwrap();
    assert!(
        parsed_command.is_some(),
        "No command parsed from compact output: {}",
        generated
    );
    let parsed_command = parsed_command.unwrap();

    // Check if the parsed command matches the original
    assert_eq!(parsed_command.name(), command.name());
    assert_eq!(parsed_command.params.len(), command.params.len());
}

// Test Writer-Parser compatibility with force quotes
#[test]
fn test_writer_parser_force_quotes() {
    let command = Command::new(
        "quote_test",
        vec![
            Parameter::from("valid_name"),
            Parameter::from("valid123"),
            Parameter::from("invalid-name"),
        ],
    );

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

    let mut force_quote_options = FormatterOptions::default();
    force_quote_options.force_quotes_for_vars = true;
    writer
        .write_command_with_options(&command, Some(&force_quote_options), None)
        .expect("Failed to write with force quotes");
    let generated = String::from_utf8(output).unwrap();

    // Parse it back
    let input = StringInputSource::new(generated.as_str());
    let parser_config = ParserConfig::default();
    let mut parser = Parser::new(input, parser_config);

    let parsed = parser.next_command();
    assert!(
        parsed.is_ok(),
        "Failed to parse generated command with force quotes: {}",
        generated
    );
    let parsed_command = parsed.unwrap();
    assert!(
        parsed_command.is_some(),
        "No command parsed from: {}",
        generated
    );
    let parsed_command = parsed_command.unwrap();

    // Check if the parsed command matches the original
    assert_eq!(parsed_command.name(), command.name());
    assert_eq!(parsed_command.params.len(), command.params.len());
}

#[test]
fn test_write_duplicate_keys() {
    let mut entries = Vec::new();
    entries.push(("k".to_string(), koicore::Value::Int(1)));
    entries.push(("k".to_string(), koicore::Value::Int(2)));

    let param = Parameter::Composite(
        "p".to_string(),
        koicore::command::CompositeValue::Dict(entries),
    );
    let command = Command::new("dup_test", vec![param]);

    let config = WriterConfig::default();
    let mut output = Vec::new();
    let mut writer = Writer::new(&mut output, config);
    writer
        .write_command(&command)
        .expect("Failed to write duplicate keys");

    let generated = String::from_utf8(output).unwrap();
    println!("{}", generated);
    // Should contain p(k: 1, k: 2)
    assert!(generated.contains("p(k: 1, k: 2)"));
}

#[test]
fn test_write_special_strings() {
    // Strings with quotes, newlines, etc.
    let special = vec![
        "normal",
        "with space",
        "with \"quote\"",
        "with \n newline",
        "", // empty
    ];

    let mut params = Vec::new();
    for s in &special {
        params.push(Parameter::from(*s));
    }

    let command = Command::new("str_test", params);

    let config = WriterConfig::default();
    let mut output = Vec::new();
    let mut writer = Writer::new(&mut output, config);
    writer
        .write_command(&command)
        .expect("Failed to write special strings");

    let generated = String::from_utf8(output).unwrap();
    println!("{}", generated);

    // Parse back
    let input = StringInputSource::new(generated.as_str());
    let parser_config = ParserConfig::default();
    let mut parser = Parser::new(input, parser_config);

    let parsed = parser
        .next_command()
        .expect("Failed to parse back")
        .unwrap();
    assert_eq!(parsed.params.len(), special.len());

    // Check specific values
    if let Parameter::Basic(koicore::Value::String(s)) = &parsed.params[2] {
        assert_eq!(s, "with \"quote\"");
    } else {
        panic!("Wrong type for quote test");
    }

    if let Parameter::Basic(koicore::Value::String(s)) = &parsed.params[3] {
        assert_eq!(s, "with \n newline");
    } else {
        panic!("Wrong type for newline test");
    }

    if let Parameter::Basic(koicore::Value::String(s)) = &parsed.params[4] {
        assert_eq!(s, "");
    } else {
        panic!("Wrong type for empty string");
    }
}