r4d 3.0.0-rc.4

Text oriented macro processor
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
use crate::consts::*;
use crate::logger::{Logger, WarningType};
use crate::models::{DiffOption, MacroFragment, RadResult};
use crate::utils::Utils;
use crossterm::{terminal::ClearType, ExecutableCommand};
use similar::ChangeTag;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, Write};
use std::path::Path;

/// Debugger
pub(crate) struct Debugger {
    pub(crate) debug: bool,
    pub(crate) log: bool,
    pub(crate) debug_switch: DebugSwitch,
    pub(crate) line_number: usize,
    // This is a global line number storage for various deubbing usages
    // This is a bit bloaty, but debugging needs functionality over efficiency
    pub(crate) line_caches: HashMap<usize, String>,
    pub(crate) do_yield_diff: bool,
    pub(crate) diff_only_change: bool,
    pub(crate) diff_original: Option<File>,
    pub(crate) diff_processed: Option<File>,
    pub(crate) interactive: bool,
    prompt_log: Option<String>,
}

impl Debugger {
    pub fn new() -> Self {
        Self {
            debug: false,
            log: false,
            debug_switch: DebugSwitch::NextLine,
            line_number: 1,
            line_caches: HashMap::new(),
            do_yield_diff: false,
            diff_only_change: false,
            diff_original: None,
            diff_processed: None,
            interactive: false,
            prompt_log: None,
        }
    }

    /// Enable diff logic
    ///
    /// WIth diff enabled, diff information will be saved to two separate files
    pub fn enable_diff(&mut self, diff_option: DiffOption) -> RadResult<()> {
        // DiffOption specific operation
        match diff_option {
            DiffOption::None => return Ok(()), // No diff, return
            DiffOption::Change => self.diff_only_change = true,
            _ => (),
        }
        self.do_yield_diff = true;
        self.diff_original = Some(
            OpenOptions::new()
                .create(true)
                .write(true)
                .read(true)
                .truncate(true)
                .open(Path::new(DIFF_SOURCE_FILE))?,
        );
        self.diff_processed = Some(
            OpenOptions::new()
                .create(true)
                .write(true)
                .read(true)
                .truncate(true)
                .open(Path::new(DIFF_OUT_FILE))?,
        );

        Ok(())
    }

    /// Enable interactive mode
    ///
    /// This clears terminal if possible
    pub fn set_interactive(&mut self) {
        self.interactive = true;
    }

    /// Get debug command
    ///
    /// Get user input and parsed the given command
    pub fn get_command(&self, log: &str, prompt: Option<&str>) -> RadResult<String> {
        // Disable line wrap
        if self.interactive {
            std::io::stdout().execute(crossterm::terminal::DisableLineWrap)?;
        }

        let mut input = String::new();
        let prompt = if let Some(content) = prompt {
            content
        } else {
            ""
        };
        // TODO
        // This utilizes eprint variant which can yield not handled error
        // but it is generally ok because debugger is mostly self contained process
        eprintln!("{} : {}", Utils::green(&format!("({})", &prompt)), log);
        eprint!(">> ");

        // Restore wrapping
        if self.interactive {
            std::io::stdout().execute(crossterm::terminal::EnableLineWrap)?;
        }
        // Flush because eprint! is not "printed" yet
        std::io::stdout().flush()?;

        // Get user input
        let stdin = std::io::stdin();
        stdin.lock().read_line(&mut input)?;
        if self.interactive {
            // Clear user input line
            // Preceding 1 is for "(input)" prompt
            self.remove_terminal_lines(1 + Utils::count_sentences(log))?;
        }

        Ok(input)
    }

    /// Remove terminal lines by given count
    fn remove_terminal_lines(&self, count: usize) -> RadResult<()> {
        // Clear current line
        std::io::stdout().execute(crossterm::terminal::Clear(ClearType::CurrentLine))?;

        // Range is max exclusive thus min should start from 0
        // e.g. 0..1 only tries once with index 0
        for _ in 0..count {
            std::io::stdout()
                .execute(crossterm::cursor::MoveUp(1))?
                .execute(crossterm::terminal::Clear(ClearType::CurrentLine))?;
        }

        Ok(())
    }

    /// Print differences of original and processed
    pub fn yield_diff(&self, logger: &mut Logger) -> RadResult<()> {
        if !self.do_yield_diff {
            return Ok(());
        }

        let source = std::fs::read_to_string(Path::new(DIFF_SOURCE_FILE))?;
        let processed = std::fs::read_to_string(Path::new(DIFF_OUT_FILE))?;
        let result = similar::TextDiff::from_lines(&source, &processed);

        let mut log: String;
        // Color function reference
        let mut colorfunc: ColorDisplayFunc;

        // Print header
        logger.elog_no_prompt(format!("{0}DIFF : {0}", LINE_ENDING))?;

        // Print changes with color support
        for change in result.iter_all_changes() {
            colorfunc = None;
            match change.tag() {
                ChangeTag::Delete => {
                    log = format!("- {}", change);
                    colorfunc.replace(Utils::red);
                }
                ChangeTag::Insert => {
                    log = format!("+ {}", change);
                    colorfunc.replace(Utils::green);
                }
                ChangeTag::Equal => {
                    if !self.diff_only_change {
                        log = format!("  {}", change);
                    } else {
                        // Log should be assigned at least once
                        // because later codes expectes log to be exsitent.
                        // It is ok to create empty owned string,
                        // compiler is smart enough not to allocate
                        // any memory for empty string.
                        log = "".to_owned();
                    }
                }
            }
            if let Some(func) = colorfunc {
                // Bind display to log
                let log = func(&log);
                logger.elog_no_prompt(&log)?;
            } else {
                logger.elog_no_prompt(&log)?;
            }
        }

        Ok(())
    }

    /// Process breakpoint
    pub(crate) fn break_point(
        &mut self,
        frag: &mut MacroFragment,
        logger: &mut Logger,
    ) -> RadResult<()> {
        if &frag.name == "BR" {
            if self.debug {
                if let DebugSwitch::NextBreakPoint(name) = &self.debug_switch {
                    // Name is empty or same with frag.args
                    if name == &frag.args || name.is_empty() {
                        self.debug_switch = DebugSwitch::NextLine;
                    }
                }
                // Clear fragment
                frag.clear();
                return Ok(());
            }

            // Warning
            logger.wlog("Breakpoint in non debug mode", WarningType::Sanity)?;
            frag.clear();
        }

        Ok(())
    }

    /// Print debug information log
    pub(crate) fn print_log(
        &mut self,
        macro_name: &str,
        raw_args: &str,
        frag: &MacroFragment,
        logger: &mut Logger,
    ) -> RadResult<()> {
        if !self.log {
            return Ok(());
        }
        let attributes = self.print_macro_attr(frag);
        logger.dlog_print(&format!(
            r#"Name    = "{}"{}Attr    ={}{}Args    = "{}"{}---{}"#,
            macro_name, LINE_ENDING, LINE_ENDING, attributes, raw_args, LINE_ENDING, LINE_ENDING
        ))?;
        Ok(())
    }

    /// Format macro framgent attributes
    fn print_macro_attr(&self, frag: &MacroFragment) -> String {
        format!(
            r#"Greedy  : {}{}Pipe    : {}{}Literal : {}{}Trimmed : {}{}"#,
            frag.greedy,
            LINE_ENDING,
            frag.pipe,
            LINE_ENDING,
            frag.yield_literal,
            LINE_ENDING,
            frag.trimmed,
            LINE_ENDING
        )
    }

    /// Get user input command before processing starts
    pub(crate) fn user_input_on_start(
        &mut self,
        current_input: &str,
        logger: &mut Logger,
    ) -> RadResult<()> {
        // Stop by lines if debug option is lines
        if self.debug {
            let mut log = if let Some(pl) = self.prompt_log.take() {
                pl
            } else {
                "Default is next. Ctrl + c to exit.".to_owned()
            };

            self.command_loop(&mut log, current_input, None, logger)?;
        }
        Ok(())
    }

    /// Prompt user input until break condition has been met
    fn user_input_prompt(
        &mut self,
        frag: &MacroFragment,
        initial_prompt: &str,
        logger: &mut Logger,
    ) -> RadResult<()> {
        // Respect custom prompt log if it exists
        let mut log = if let Some(pl) = self.prompt_log.take() {
            pl
        } else {
            match &self.debug_switch {
                &DebugSwitch::NextMacro | &DebugSwitch::StepMacro => self
                    .line_caches
                    .get(&logger.get_abs_last_line())
                    .unwrap()
                    .to_owned(),
                _ => self.line_caches.get(&self.line_number).unwrap().to_owned(),
            }
        };

        self.command_loop(&mut log, initial_prompt, Some(frag), logger)?;
        Ok(())
    }

    /// Continuously get user input until break situation
    fn command_loop(
        &mut self,
        log: &mut String,
        prompt: &str,
        frag: Option<&MacroFragment>,
        logger: &mut Logger,
    ) -> RadResult<()> {
        let mut do_continue = true;
        while do_continue {
            // This technically strips newline feed regardless of platforms
            // It is ok to simply convert to a single line because it is logically a single
            let input = self.debug_wait_input(log, Some(prompt))?;
            // Strip newline
            let input = input.lines().next().unwrap();

            do_continue = self.parse_debug_command_and_continue(input, frag, log, logger)?;
        }

        Ok(())
    }

    /// Get user input on line
    ///
    /// This method should be called before evaluation of a line
    pub fn user_input_on_line(
        &mut self,
        frag: &MacroFragment,
        logger: &mut Logger,
    ) -> RadResult<()> {
        // Stop by lines if debug option is lines
        if self.debug {
            // Only when debugswitch is nextline
            if let DebugSwitch::NextLine = self.debug_switch {
                // Continue;
            } else {
                return Ok(()); // Return early
            }
            self.user_input_prompt(frag, "line", logger)?;
        }
        Ok(())
    }

    /// Get user input before macro execution
    pub fn user_input_before_macro(
        &mut self,
        frag: &MacroFragment,
        logger: &mut Logger,
    ) -> RadResult<()> {
        // Stop by lines if debug option is lines
        if self.debug {
            match &self.debug_switch {
                &DebugSwitch::UntilMacro => (),
                _ => return Ok(()),
            }
            self.user_input_prompt(frag, "until", logger)?;
        }
        Ok(())
    }

    /// Get user input after execution
    pub fn user_input_on_macro(
        &mut self,
        frag: &MacroFragment,
        logger: &mut Logger,
    ) -> RadResult<()> {
        // Stop by lines if debug option is lines
        if self.debug {
            match &self.debug_switch {
                &DebugSwitch::NextMacro | &DebugSwitch::StepMacro => (),
                _ => return Ok(()),
            }
            self.user_input_prompt(frag, &frag.name, logger)?;
        }
        Ok(())
    }

    /// Get user input on execution but also nested macro can be targeted
    pub fn user_input_on_step(
        &mut self,
        frag: &MacroFragment,
        logger: &mut Logger,
    ) -> RadResult<()> {
        // Stop by lines if debug option is lines
        if self.debug {
            if let &DebugSwitch::StepMacro = &self.debug_switch {
                // Continue;
            } else {
                return Ok(()); // Return early
            }

            self.user_input_prompt(frag, &frag.name, logger)?;
        }
        Ok(())
    }

    /// Get user input and evaluates whether loop of input prompt should be breaked or not
    pub fn parse_debug_command_and_continue(
        &mut self,
        command_input: &str,
        frag: Option<&MacroFragment>,
        log: &mut String,
        logger: &mut Logger,
    ) -> RadResult<bool> {
        let command_input: Vec<&str> = command_input.split(' ').collect();
        let command = command_input[0];
        // Default is empty &str ""
        let command_args = if command_input.len() == 2 {
            command_input[1]
        } else {
            ""
        };

        match command.to_lowercase().as_str() {
            // Continues until next break point
            "cl" | "clear" => {
                Utils::clear_terminal()?;
                return Ok(true);
            }
            "c" | "continue" => {
                self.debug_switch = DebugSwitch::NextBreakPoint(command_args.to_owned());
            }
            // Continue to next line
            "n" | "next" | "" => {
                self.debug_switch = DebugSwitch::NextLine;
            }
            // Continue to next macro
            "m" | "macro" => {
                self.debug_switch = DebugSwitch::NextMacro;
            }
            // Continue to until next macro
            "u" | "until" => {
                self.debug_switch = DebugSwitch::UntilMacro;
            }
            // Setp into macro
            "s" | "step" => {
                self.debug_switch = DebugSwitch::StepMacro;
            }
            "h" | "help" => {
                *log = RDB_HELP.to_owned();
                return Ok(true);
            }
            // Print "variable"
            "p" | "print" => {
                if let Some(frag) = frag {
                    self.check_command_print(log, command_args, frag, logger);
                } else {
                    // No fragment which means it is the start of file
                    return Ok(false);
                }
                // Get user input again
                return Ok(true);
            }
            // Invalid command
            _ => {
                *log = format!("Invalid command : {} {}", command, &command_args);
                return Ok(true);
            }
        } // End match

        // Unless specific cases,
        // Continue without any loop
        Ok(false)
    }

    /// Check command print's content
    fn check_command_print(
        &self,
        log: &mut String,
        command_args: &str,
        frag: &MacroFragment,
        logger: &mut Logger,
    ) {
        match command_args.to_lowercase().as_str() {
            // Only name
            "name" | "n" => {
                *log = frag.name.to_owned();
            }
            // Current line number
            "line" | "l" => match &self.debug_switch {
                DebugSwitch::StepMacro | DebugSwitch::NextMacro => {
                    *log = logger.get_abs_last_line().to_string();
                }
                _ => {
                    *log = self.line_number.to_string();
                }
            },
            // Span of codes,macro chunk
            "span" | "s" => {
                let mut line_number = match &self.debug_switch {
                    &DebugSwitch::NextMacro | &DebugSwitch::StepMacro => logger.get_abs_line(),
                    _ => self.line_number,
                };

                let mut sums = String::new();
                // This puts lines in invert order
                while let Some(line) = self.line_caches.get(&line_number) {
                    let mut this_line = format!("{}{}", LINE_ENDING, line);
                    this_line.push_str(&sums);
                    sums = this_line;
                    line_number -= 1;
                }

                // Put prompt log "Span" on top
                let mut this_line = "\"Span\"".to_string();
                this_line.push_str(&sums);
                sums = this_line;

                *log = sums;
            }
            // Current line text
            "text" | "t" => match &self.debug_switch {
                DebugSwitch::StepMacro | DebugSwitch::NextMacro => {
                    *log = self
                        .line_caches
                        .get(&logger.get_abs_last_line())
                        .unwrap()
                        .to_owned();
                }
                _ => {
                    *log = self.line_caches.get(&self.line_number).unwrap().to_owned();
                }
            },
            // Current argument
            "arg" | "a" => {
                *log = frag.processed_args.to_owned();
            }
            // Original argument
            "raw" | "r" => {
                *log = frag.args.to_owned();
            }
            // Invalid argument
            _ => {
                *log = format!("Invalid argument \"{}\"", &command_args);
            }
        } // End match
    }

    /// Bridge function that waits user's stdin input
    pub fn debug_wait_input(&self, log: &str, prompt: Option<&str>) -> RadResult<String> {
        self.get_command(log, prompt)
    }

    pub fn inc_line_number(&mut self) {
        self.line_number += 1;
    }

    pub fn add_line_cache(&mut self, line: &str) {
        self.line_caches
            .insert(self.line_number, line.lines().next().unwrap().to_owned());
    }

    pub fn clear_line_cache(&mut self) {
        self.line_caches.clear();
    }

    // Save original content to a file for diff check
    pub fn write_to_original(&mut self, content: &str) -> RadResult<()> {
        if self.do_yield_diff {
            self.diff_original
                .as_ref()
                .unwrap()
                .write_all(content.as_bytes())?;
        }
        Ok(())
    }

    // Save processed content to a file for diff check
    pub fn write_to_processed(&mut self, content: &str) -> RadResult<()> {
        if self.do_yield_diff {
            self.diff_processed
                .as_ref()
                .unwrap()
                .write_all(content.as_bytes())?;
        }
        Ok(())
    }

    pub fn set_prompt_log(&mut self, prompt: &str) {
        self.prompt_log.replace(prompt.to_owned());
    }
}

/// Debug switch(state) that indicates what debugging behaviours are intended for next branch
pub enum DebugSwitch {
    UntilMacro,
    NextLine,
    NextMacro,
    StepMacro,
    NextBreakPoint(String),
}