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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! KoiLang parser module
//!
//! This module provides the core parsing functionality for KoiLang files.
//!
//! ## Features
//!
//! - **Streaming Processing**: Parse files of any size with constant memory usage
//! - **Multiple Input Sources**: Parse from strings, files, or custom sources
//! - **Encoding Support**: Handle various text encodings through `DecodeBufReader`
//! - **Comprehensive Error Handling**: Detailed error messages with source locations
//! - **Configurable Parsing**: Customizable command thresholds and parsing rules
//!
//! ## Usage
//!
//! ```rust
//! use koicore::parser::{Parser, ParserConfig, StringInputSource};
//!
//! let input = StringInputSource::new("#name \"Test\"\nHello World");
//! let config = ParserConfig::default();
//! let mut parser = Parser::new(input, config);
//!
//! while let Some(command) = parser.next_command()? {
//!     println!("Command: {}", command.name());
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

pub mod command_parser;
pub mod decode_buf_reader;
pub mod error;
pub mod input;
pub mod traceback;

use super::command::Command;
pub use error::{ErrorInfo, ParseError, ParseResult, ParserLineSource};
pub use input::{BufReadWrapper, FileInputSource, StringInputSource, TextInputSource};
use nom::Offset;
pub use traceback::TracebackEntry;

use input::Input;
use traceback::NomErrorNode;

/// Configuration for the line processor
///
/// Controls how the parser interprets different types of lines in the input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParserConfig {
    /// The command threshold (number of # required for commands)
    ///
    /// Lines with fewer # characters than this threshold are treated as text.
    /// Lines with exactly this many # characters are treated as commands.
    /// Lines with more # characters are treated as annotations.
    pub command_threshold: usize,
    /// Whether to skip annotation lines (lines starting with #)
    ///
    /// If set to true, annotation lines will be skipped and not processed as commands.
    /// If set to false, annotation lines will be included in the output as special commands.
    pub skip_annotations: bool,
    /// Whether to convert number commands to special commands
    ///
    /// If set to true, commands with names that are valid integers will be converted
    /// to special number commands. If set to false, they will be treated as regular commands.
    pub convert_number_command: bool,
    /// Whether to preserve indentation in text and annotation lines
    ///
    /// If set to true, leading whitespace (indentation) will be preserved in text and
    /// annotation content. If set to false, leading whitespace will be trimmed.
    pub preserve_indent: bool,
    /// Whether to preserve empty lines as text commands
    ///
    /// If set to true, empty lines will be preserved and returned as empty text commands.
    /// If set to false, empty lines will be skipped.
    pub preserve_empty_lines: bool,
}

impl Default for ParserConfig {
    fn default() -> Self {
        Self {
            command_threshold: 1,
            skip_annotations: false,
            convert_number_command: true,
            preserve_indent: false,
            preserve_empty_lines: false,
        }
    }
}

impl ParserConfig {
    /// Create a new parser configuration with the specified command threshold
    ///
    /// # Arguments
    /// * `threshold` - Number of # characters required to identify a command line
    /// * `skip_annotations` - Whether to skip annotation lines
    /// * `convert_number_command` - Whether to convert number commands
    /// * `preserve_indent` - Whether to preserve leading whitespace in text/annotations
    /// * `preserve_empty_lines` - Whether to preserve empty lines as text commands
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::parser::ParserConfig;
    ///
    /// // Default configuration (threshold = 1)
    /// let config = ParserConfig::default();
    ///
    /// // Custom configuration
    /// let config = ParserConfig::new(2, true, true, false, false);
    /// ```
    pub fn new(
        threshold: usize,
        skip_annotations: bool,
        convert_number_command: bool,
        preserve_indent: bool,
        preserve_empty_lines: bool,
    ) -> Self {
        Self {
            command_threshold: threshold,
            skip_annotations,
            convert_number_command,
            preserve_indent,
            preserve_empty_lines,
        }
    }

    /// Set the command threshold for this configuration
    ///
    /// # Arguments
    /// * `threshold` - New number of # characters required to identify a command line
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::parser::ParserConfig;
    ///
    /// let config = ParserConfig::default().with_command_threshold(2);
    /// ```
    pub fn with_command_threshold(mut self, threshold: usize) -> Self {
        self.command_threshold = threshold;
        self
    }

    /// Set whether to skip annotation lines for this configuration
    ///
    /// # Arguments
    /// * `skip` - Whether to skip annotation lines (true) or include them (false)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::parser::ParserConfig;
    ///
    /// let config = ParserConfig::default().with_skip_annotations(true);
    /// ```
    pub fn with_skip_annotations(mut self, skip: bool) -> Self {
        self.skip_annotations = skip;
        self
    }

    /// Set whether to convert number command name into @number
    ///
    /// # Arguments
    /// * `convert` - Whether to convert number command name into @number
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::parser::ParserConfig;
    ///
    /// let config = ParserConfig::default().with_convert_number_command(true);
    /// ```
    pub fn with_convert_number_command(mut self, convert: bool) -> Self {
        self.convert_number_command = convert;
        self
    }

    /// Set whether to preserve indentation in text and annotation lines
    ///
    /// # Arguments
    /// * `preserve` - Whether to preserve leading whitespace in text/annotations
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::parser::ParserConfig;
    ///
    /// let config = ParserConfig::default().with_preserve_indent(true);
    /// ```
    pub fn with_preserve_indent(mut self, preserve: bool) -> Self {
        self.preserve_indent = preserve;
        self
    }

    /// Set whether to preserve empty lines as text commands
    ///
    /// # Arguments
    /// * `preserve` - Whether to preserve empty lines as text commands
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::parser::ParserConfig;
    ///
    /// let config = ParserConfig::default().with_preserve_empty_lines(true);
    /// ```
    pub fn with_preserve_empty_lines(mut self, preserve: bool) -> Self {
        self.preserve_empty_lines = preserve;
        self
    }
}

/// Core KoiLang parser
///
/// The parser processes input line by line and produces `ParsedCommand` structures
/// for each logical unit (commands, text lines, annotations). It supports streaming
/// processing for memory-efficient parsing of large files.
pub struct Parser<T: TextInputSource> {
    input: Input<T>,
    config: ParserConfig,
}

impl<T: TextInputSource> Parser<T> {
    /// Create a new parser with the specified configuration
    ///
    /// # Arguments
    /// * `input_source` - The source of text input
    /// * `config` - Parser configuration
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::parser::{Parser, ParserConfig, StringInputSource};
    ///
    /// let input = StringInputSource::new("#name \"Test\"");
    /// let config = ParserConfig::default();
    /// let mut parser = Parser::new(input, config);
    /// ```
    pub fn new(input_source: T, config: ParserConfig) -> Self {
        Self {
            input: Input::new(input_source),
            config,
        }
    }

    /// Get the next command from the input stream
    ///
    /// Returns `Ok(None)` when end of input is reached.
    /// Returns `Ok(Some(Command))` when a command is successfully parsed.
    /// Returns `Err(ParseError)` when a parsing error occurs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::parser::{Parser, ParserConfig, StringInputSource};
    ///
    /// let input = StringInputSource::new("#name \"Test\"");
    /// let config = ParserConfig::default();
    /// let mut parser = Parser::new(input, config);
    ///
    /// while let Some(command) = parser.next_command()? {
    ///     println!("Command: {}", command.name());
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn next_command(&mut self) -> ParseResult<Option<Command>> {
        self.next_command_with_source()
            .map(|opt| opt.map(|(cmd, _)| cmd))
    }

    /// Get the next command from the input stream with source information
    ///
    /// Similar to `next_command()`, but also returns the source location information
    /// including filename, line number, and original text content.
    ///
    /// Returns `Ok(None)` when end of input is reached.
    /// Returns `Ok(Some((Command, ParserLineSource)))` when a command is successfully parsed.
    /// Returns `Err(ParseError)` when a parsing error occurs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::parser::{Parser, ParserConfig, StringInputSource};
    ///
    /// let input = StringInputSource::new("#name \"Test\"");
    /// let config = ParserConfig::default();
    /// let mut parser = Parser::new(input, config);
    ///
    /// while let Some((command, source)) = parser.next_command_with_source()? {
    ///     println!("Command: {} at {}:{}", command.name(), source.filename, source.lineno);
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn next_command_with_source(&mut self) -> ParseResult<Option<(Command, ParserLineSource)>> {
        loop {
            let (lineno, line_text) = match self.input.next_line() {
                Ok(Some(line_info)) => line_info,
                Ok(None) => {
                    return Ok(None);
                }
                Err(e) => {
                    let source = ParserLineSource {
                        filename: self.input.as_ref().source_name().to_string(),
                        lineno: self.input.line_number,
                        text: String::new(),
                    };
                    return Err(ParseError::io(e).with_line_source(source));
                }
            };
            let source = ParserLineSource {
                filename: self.input.as_ref().source_name().to_string(),
                lineno,
                text: line_text.clone(),
            };
            let trimmed = line_text.trim();
            if trimmed.is_empty() {
                if self.config.preserve_empty_lines {
                    break Ok(Some((Command::new_text(""), source)));
                }
                continue;
            }

            // Count leading # characters
            let hash_count = trimmed.chars().take_while(|&c| c == '#').count();

            if hash_count < self.config.command_threshold {
                let text_content = if self.config.preserve_indent {
                    line_text.trim_end().to_string()
                } else {
                    trimmed.to_string()
                };
                break Ok(Some((Command::new_text(text_content), source)));
            } else if hash_count > self.config.command_threshold {
                if self.config.skip_annotations {
                    continue;
                }
                let annotation_content = if self.config.preserve_indent {
                    line_text.trim_end().to_string()
                } else {
                    let content: String = trimmed.chars().skip(hash_count).collect();
                    content.trim().to_string()
                };
                break Ok(Some((Command::new_annotation(annotation_content), source)));
            } else {
                // hash_count == self.config.command_threshold
                let column = line_text.offset(trimmed) + hash_count;
                let command_str: String = trimmed.chars().skip(hash_count).collect();
                break self
                    .parse_command_line(command_str, lineno, column)
                    .map_err(|e| e.with_line_source(source.clone()))
                    .map(|opt| opt.map(|cmd| (cmd, source)));
            }
        }
    }

    /// Parse a command line
    ///
    /// This is an internal method that handles the actual parsing of command syntax.
    /// It processes the text after the command prefix (#) and creates the appropriate
    /// Command structure.
    ///
    /// # Arguments
    /// * `command_text` - The text content of the command (without the # prefix)
    /// * `lineno` - The line number in the source file
    /// * `column` - The column number in the source file
    pub fn parse_command_line(
        &self,
        command_text: String,
        lineno: usize,
        column: usize,
    ) -> ParseResult<Option<Command>> {
        if command_text.is_empty() {
            return Err(ParseError::syntax_with_context(
                "Empty command line".to_string(),
                lineno,
                column,
                command_text,
            ));
        }

        let result = command_parser::parse_command_line::<NomErrorNode<&str>>(&command_text);

        match result {
            Ok(("", command)) => {
                let num_name = command.name().parse();
                match num_name {
                    Result::Err(_) => Ok(Some(command)),
                    Result::Ok(num) => {
                        if !self.config.convert_number_command {
                            Ok(Some(command))
                        } else {
                            Ok(Some(Command::new_number(num, command.params)))
                        }
                    }
                }
            }
            Ok((remaining, _)) => Err(ParseError::unexpected_input(
                remaining.to_string(),
                lineno,
                column,
                command_text,
            )),
            Err(nom::Err::Error(e)) | Err(nom::Err::Failure(e)) => {
                // Create a simple nom error for compatibility
                Err(ParseError::from_nom_error(
                    "Command parsing error".to_string(),
                    command_text.as_str(),
                    lineno,
                    column,
                    e,
                ))
            }
            Err(nom::Err::Incomplete(_)) => {
                Err(ParseError::unexpected_eof(command_text, lineno, column))
            }
        }
    }

    /// Process all commands using a callback function
    ///
    /// This provides a streaming interface where each parsed command is
    /// passed to the provided handler function. This is the most memory-efficient
    /// way to process large files.
    ///
    /// # Arguments
    /// * `handler` - Function to call for each parsed command. Should return:
    ///   * `Ok(true)` to continue processing
    ///   * `Ok(false)` to stop processing
    ///   * `Err(e)` to propagate an error
    ///
    /// # Returns
    /// * `Ok(true)` if processing completed and reached EOF
    /// * `Ok(false)` if processing was stopped early by the handler
    /// * `Err(E)` if the handler returned an error or a parse error occurred
    ///
    /// # Examples
    ///
    /// ```rust
    /// use koicore::parser::{Parser, ParserConfig, StringInputSource};
    ///
    /// let input = StringInputSource::new("#name \"Test\"\nHello");
    /// let config = ParserConfig::default();
    /// let mut parser = Parser::new(input, config);
    ///
    /// let reached_eof = parser.process_with(|command| -> Result<bool, Box<dyn std::error::Error>> {
    ///     match command.name() {
    ///         "@text" => {
    ///             println!("Text: {}", command);
    ///             Ok(true) // Continue processing
    ///         },
    ///         "@annotation" => {
    ///             println!("Annotation: {}", command);
    ///             Ok(false) // Stop processing after this command
    ///         },
    ///         _ => {
    ///             println!("Command: {}", command);
    ///             Ok(true) // Continue processing
    ///         },
    ///     }
    /// })?;
    ///
    /// assert!(reached_eof, "Should have reached end of file");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn process_with<F, E>(&mut self, mut handler: F) -> Result<bool, E>
    where
        F: FnMut(Command) -> Result<bool, E>,
        E: From<Box<ParseError>>,
    {
        loop {
            match self.next_command() {
                Ok(Some(command)) => {
                    let should_continue = handler(command)?;
                    if !should_continue {
                        return Ok(false); // Stopped early by handler
                    }
                }
                Ok(None) => {
                    return Ok(true); // Reached EOF
                } // End of input
                Err(e) => {
                    return Err(e.into());
                } // Convert ParseError to E
            }
        }
    }

    /// Get the current line number
    ///
    /// Returns the line number that the parser is currently processing.
    /// This is useful for error reporting and progress tracking.
    pub fn current_line(&self) -> usize {
        self.input.line_number
    }
}

impl<T: TextInputSource> AsRef<T> for Parser<T> {
    fn as_ref(&self) -> &T {
        &self.input.source
    }
}

impl<T: TextInputSource> AsMut<T> for Parser<T> {
    fn as_mut(&mut self) -> &mut T {
        &mut self.input.source
    }
}

impl<T: TextInputSource> Iterator for Parser<T> {
    type Item = ParseResult<Command>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.next_command() {
            Ok(Some(cmd)) => Some(Ok(cmd)),
            Ok(None) => None,
            Err(e) => Some(Err(e)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::error::ParseError;

    #[test]
    fn test_parser_config() {
        let config = ParserConfig::default();
        assert_eq!(config.command_threshold, 1);
        assert!(!config.skip_annotations);
        assert!(config.convert_number_command);
        assert!(!config.preserve_indent);
        assert!(!config.preserve_empty_lines);

        let config = ParserConfig::new(2, true, false, true, true);
        assert_eq!(config.command_threshold, 2);
        assert!(config.skip_annotations);
        assert!(!config.convert_number_command);
        assert!(config.preserve_indent);
        assert!(config.preserve_empty_lines);

        let config = ParserConfig::default()
            .with_command_threshold(3)
            .with_skip_annotations(true)
            .with_convert_number_command(false)
            .with_preserve_indent(true)
            .with_preserve_empty_lines(true);
        assert_eq!(config.command_threshold, 3);
        assert!(config.skip_annotations);
        assert!(!config.convert_number_command);
        assert!(config.preserve_indent);
        assert!(config.preserve_empty_lines);
    }

    #[test]
    fn test_preserve_indent() {
        let input = StringInputSource::new("  indented text\nnormal text");
        
        let config = ParserConfig::default();
        let mut parser = Parser::new(input, config);
        let cmd = parser.next_command().unwrap().unwrap();
        assert_eq!(cmd.name(), "@text");
        assert_eq!(cmd.params()[0].to_string(), "\"indented text\"");
        
        let input = StringInputSource::new("  indented text\nnormal text");
        let config = ParserConfig::default().with_preserve_indent(true);
        let mut parser = Parser::new(input, config);
        let cmd = parser.next_command().unwrap().unwrap();
        assert_eq!(cmd.name(), "@text");
        assert_eq!(cmd.params()[0].to_string(), "\"  indented text\"");
    }

    #[test]
    fn test_preserve_empty_lines() {
        let input = StringInputSource::new("text1\n\ntext2");
        
        let config = ParserConfig::default();
        let mut parser = Parser::new(input, config);
        let cmd1 = parser.next_command().unwrap().unwrap();
        assert_eq!(cmd1.name(), "@text");
        assert_eq!(cmd1.params()[0].to_string(), "text1");
        let cmd2 = parser.next_command().unwrap().unwrap();
        assert_eq!(cmd2.name(), "@text");
        assert_eq!(cmd2.params()[0].to_string(), "text2");
        
        let input = StringInputSource::new("text1\n\ntext2");
        let config = ParserConfig::default().with_preserve_empty_lines(true);
        let mut parser = Parser::new(input, config);
        let cmd1 = parser.next_command().unwrap().unwrap();
        assert_eq!(cmd1.name(), "@text");
        assert_eq!(cmd1.params()[0].to_string(), "text1");
        let cmd_empty = parser.next_command().unwrap().unwrap();
        assert_eq!(cmd_empty.name(), "@text");
        assert_eq!(cmd_empty.params()[0].to_string(), "\"\"");
        let cmd2 = parser.next_command().unwrap().unwrap();
        assert_eq!(cmd2.name(), "@text");
        assert_eq!(cmd2.params()[0].to_string(), "text2");
    }

    #[test]
    fn test_preserve_indent_annotation() {
        let input = StringInputSource::new("##  annotation text");
        
        let config = ParserConfig::default();
        let mut parser = Parser::new(input, config);
        let cmd = parser.next_command().unwrap().unwrap();
        assert_eq!(cmd.name(), "@annotation");
        assert_eq!(cmd.params()[0].to_string(), "\"annotation text\"");
        
        let input = StringInputSource::new("##  annotation text");
        let config = ParserConfig::default().with_preserve_indent(true);
        let mut parser = Parser::new(input, config);
        let cmd = parser.next_command().unwrap().unwrap();
        assert_eq!(cmd.name(), "@annotation");
        assert_eq!(cmd.params()[0].to_string(), "\"##  annotation text\"");
    }

    #[test]
    fn test_parser_process_with() {
        let input = StringInputSource::new("#cmd1\n#cmd2");
        let config = ParserConfig::default();
        let mut parser = Parser::new(input, config);

        let mut commands = Vec::new();
        // Explicitly specify the Error type for the result
        let result: Result<bool, Box<ParseError>> = parser.process_with(|cmd| {
            commands.push(cmd.name().to_string());
            Ok(true)
        });

        assert!(result.is_ok());
        assert!(result.unwrap()); // EOF reached
        assert_eq!(commands, vec!["cmd1", "cmd2"]);
    }

    #[test]
    fn test_parser_process_with_early_stop() {
        let input = StringInputSource::new("#cmd1\n#cmd2");
        let config = ParserConfig::default();
        let mut parser = Parser::new(input, config);

        let mut commands = Vec::new();
        let result: Result<bool, Box<ParseError>> = parser.process_with(|cmd| {
            commands.push(cmd.name().to_string());
            Ok(false) // Stop after first command
        });

        assert!(result.is_ok());
        assert!(!result.unwrap()); // Stopped early
        assert_eq!(commands, vec!["cmd1"]);

        // Next command should be available
        let next = parser.next_command().unwrap();
        assert!(next.is_some());
        assert_eq!(next.unwrap().name(), "cmd2");
    }

    #[test]
    fn test_parser_current_line() {
        let input = StringInputSource::new("#cmd1\n#cmd2");
        let config = ParserConfig::default();
        let mut parser = Parser::new(input, config);

        assert_eq!(parser.current_line(), 1);
        parser.next_command().unwrap();
        assert_eq!(parser.current_line(), 2);
    }

    #[test]
    fn test_next_command_with_source_command() {
        let input = StringInputSource::new("#name \"Test\"\n#draw Line");
        let config = ParserConfig::default();
        let mut parser = Parser::new(input, config);

        let (cmd, source) = parser.next_command_with_source().unwrap().unwrap();
        assert_eq!(cmd.name(), "name");
        assert_eq!(source.filename, "<string>");
        assert_eq!(source.lineno, 1);
        assert_eq!(source.text, "#name \"Test\"\n");

        let (cmd, source) = parser.next_command_with_source().unwrap().unwrap();
        assert_eq!(cmd.name(), "draw");
        assert_eq!(source.lineno, 2);
        assert_eq!(source.text, "#draw Line");
    }

    #[test]
    fn test_next_command_with_source_text() {
        let input = StringInputSource::new("Hello World\nAnother line");
        let config = ParserConfig::default();
        let mut parser = Parser::new(input, config);

        let (cmd, source) = parser.next_command_with_source().unwrap().unwrap();
        assert_eq!(cmd.name(), "@text");
        assert_eq!(source.filename, "<string>");
        assert_eq!(source.lineno, 1);
        assert_eq!(source.text, "Hello World\n");

        let (cmd, source) = parser.next_command_with_source().unwrap().unwrap();
        assert_eq!(cmd.name(), "@text");
        assert_eq!(source.lineno, 2);
        assert_eq!(source.text, "Another line");
    }

    #[test]
    fn test_next_command_with_source_annotation() {
        let input = StringInputSource::new("## annotation text\n## another");
        let config = ParserConfig::default();
        let mut parser = Parser::new(input, config);

        let (cmd, source) = parser.next_command_with_source().unwrap().unwrap();
        assert_eq!(cmd.name(), "@annotation");
        assert_eq!(source.filename, "<string>");
        assert_eq!(source.lineno, 1);
        assert_eq!(source.text, "## annotation text\n");

        let (cmd, source) = parser.next_command_with_source().unwrap().unwrap();
        assert_eq!(cmd.name(), "@annotation");
        assert_eq!(source.lineno, 2);
        assert_eq!(source.text, "## another");
    }

    #[test]
    fn test_next_command_with_source_eof() {
        let input = StringInputSource::new("#cmd");
        let config = ParserConfig::default();
        let mut parser = Parser::new(input, config);

        let result = parser.next_command_with_source().unwrap();
        assert!(result.is_some());

        let result = parser.next_command_with_source().unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_next_command_with_source_error() {
        let input = StringInputSource::new("#");
        let config = ParserConfig::default();
        let mut parser = Parser::new(input, config);

        let result = parser.next_command_with_source();
        assert!(result.is_err());
    }

    #[test]
    fn test_next_command_with_source_preserve_empty_lines() {
        let input = StringInputSource::new("text1\n\ntext2");
        let config = ParserConfig::default().with_preserve_empty_lines(true);
        let mut parser = Parser::new(input, config);

        let (cmd, source) = parser.next_command_with_source().unwrap().unwrap();
        assert_eq!(cmd.name(), "@text");
        assert_eq!(source.lineno, 1);
        assert_eq!(source.text, "text1\n");

        let (cmd, source) = parser.next_command_with_source().unwrap().unwrap();
        assert_eq!(cmd.name(), "@text");
        assert_eq!(source.lineno, 2);
        assert_eq!(source.text, "\n");

        let (cmd, source) = parser.next_command_with_source().unwrap().unwrap();
        assert_eq!(cmd.name(), "@text");
        assert_eq!(source.lineno, 3);
        assert_eq!(source.text, "text2");
    }

    #[test]
    fn test_next_command_with_source_skip_annotations() {
        let input = StringInputSource::new("#cmd1\n##annotation\n#cmd2");
        let config = ParserConfig::default().with_skip_annotations(true);
        let mut parser = Parser::new(input, config);

        let (cmd, source) = parser.next_command_with_source().unwrap().unwrap();
        assert_eq!(cmd.name(), "cmd1");
        assert_eq!(source.lineno, 1);

        let (cmd, source) = parser.next_command_with_source().unwrap().unwrap();
        assert_eq!(cmd.name(), "cmd2");
        assert_eq!(source.lineno, 3);
    }
}