r4d 3.2.0-beta.1

Text oriented macro processor
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
//! # Logger
//!
//! Logger handles all kinds of logging logics. Such log can be warning, error
//! or debug logs.

use crate::common::{ProcessInput, RadResult, WriteOption};
use crate::utils::Utils;
use crate::{consts::*, RadError};
use std::fmt::Write;
use std::io::Write as _;
use trexter::{Track, Tracker};

/// Logger that controls logging
pub(crate) struct Logger<'logger> {
    suppresion_type: WarningType,
    current_input: ProcessInput,
    pub(crate) tracker_stack: TrackerStack,
    pub(crate) write_option: Option<WriteOption<'logger>>,
    pub(crate) assert: bool,
    stat: LoggerStat,
}

/// Status of a logger
#[derive(Default)]
pub struct LoggerStat {
    error_count: usize,
    warning_count: usize,
    assert_success: usize,
    assert_fail: usize,
}

impl<'logger> Logger<'logger> {
    /// Create a new instance
    pub fn new() -> Self {
        Self {
            suppresion_type: WarningType::None,
            current_input: ProcessInput::Stdin,
            write_option: None,
            tracker_stack: TrackerStack::new(),
            assert: false,
            stat: LoggerStat::default(),
        }
    }

    /// Set assert mode
    pub fn set_assert(&mut self) {
        self.assert = true;
    }

    /// Supress warning for a logger
    pub fn suppress_warning(&mut self, warning_type: WarningType) {
        self.suppresion_type = warning_type;
    }

    /// Set write option for logger
    pub fn set_write_option(&mut self, write_option: Option<WriteOption<'logger>>) {
        self.write_option = write_option;
    }

    // ----Tracker methods----

    /// Create new tracker instance
    ///
    /// This creates a context of tracking
    pub fn start_new_tracker(&mut self, track_type: TrackType) {
        self.tracker_stack.increase_level(track_type);
    }

    /// Stop last tracker
    pub fn stop_last_tracker(&mut self) {
        self.tracker_stack.decrease_level();
    }

    /// Set file's logging information and start new state
    pub fn set_input(&mut self, input: &ProcessInput) {
        self.current_input = input.clone();
        self.start_new_tracker(TrackType::Input(self.current_input.to_string()));
    }

    /// Set file's logging information and but don't start a new state
    pub fn recover_input(&mut self, input: &ProcessInput) {
        self.current_input = input.clone();
    }

    /// Increase line number
    pub fn inc_line_number(&mut self) {
        self.tracker_stack.tracker_mut().forward_line();
    }
    /// Increase char number
    pub fn inc_char_number(&mut self) {
        self.tracker_stack.tracker_mut().forward_char();
    }

    /// Add new tracks inside tracker
    pub fn append_track(&mut self, record: String) {
        self.tracker_stack
            .tracker_mut()
            .new_track(TrackType::Record(record));
    }

    /// Merge last tracks
    pub fn merge_track(&mut self) {
        self.tracker_stack.tracker_mut().connect_track();
    }

    /// Get current input track without generic milestone
    pub fn get_current_input_track(&self) -> Track<()> {
        let mut out_track = Track::new(());
        for tracker in self.tracker_stack.stack.iter().rev() {
            if let TrackType::Input(_) = tracker.get_distance().milestone {
                out_track.line_index = tracker.get_distance().line_index;
                out_track.char_index = tracker.get_distance().char_index;

                // Only get the latet input information
                break;
            }
        }
        out_track
    }

    /// Get first track
    #[cfg(feature = "debug")]
    pub fn get_first_track(&self) -> Track<()> {
        let mut out_track = Track::new(());
        let tracker = self.tracker_stack.stack.first().unwrap();
        out_track.line_index = tracker.get_distance().line_index;
        out_track.char_index = tracker.get_distance().char_index;
        out_track
    }

    /// Get last line
    #[cfg(feature = "debug")]
    pub fn get_last_line(&self) -> usize {
        let mut last_line = 0;
        for tracker in &self.tracker_stack.stack {
            let distance = tracker.get_distance();
            last_line += distance.line_index;
        }
        last_line
    }

    /// Construct log position from trexter tracks
    fn construct_log_position(&self) -> RadResult<String> {
        #[cfg(debug_assertions)]
        if std::env::var("DEBUG_TRACE").is_ok() {
            eprintln!("{:#?}", self.tracker_stack);
        }
        if std::env::var("RAD_BACKTRACE").is_ok() {
            let mut track_iter = self.tracker_stack.stack.iter();
            let input = track_iter.next().unwrap().get_distance();
            let mut trace = format!(
                "[{}]:{}:{}",
                input.milestone, input.line_index, input.char_index
            );
            for track in track_iter {
                let dist = track.get_distance();
                write!(
                    trace,
                    " >> ({}):{}:{}",
                    dist.milestone, dist.line_index, dist.char_index
                )?;
            }
            return Ok(trace);
        }
        let track = self.get_current_input_track();
        let (last_line, last_char) = (track.line_index, track.char_index);

        // Set last position first,
        // which is the first trigger macro's position
        let mut position = format!(
            "[INPUT = {}]:{}:{}",
            self.current_input, last_line, last_char
        );

        // Then append current macro's position which is the direct source of an error
        let last_distance = self.tracker_stack.tracker().get_distance();
        match &last_distance.milestone {
            TrackType::Body(name) | TrackType::Argument(name) => {
                write!(
                    position,
                    " >> (MACRO = {}):{}:{}",
                    name,
                    last_distance.line_index + 1, // THis is because inner tracks starts from line "0"
                    last_distance.char_index,
                )?;
            }
            _ => (),
        }

        Ok(position)
    }

    /// Write formatted log message without line
    fn write_formatted_log_msg_without_line(
        &mut self,
        prompt: &str,
        log_msg: &str,
        #[cfg(feature = "color")] color_func: ColorDisplayFunc,
    ) -> RadResult<()> {
        if let Some(option) = &mut self.write_option {
            match option {
                WriteOption::File(file) => {
                    file.inner()
                        .write_all(format!("{} : {}{}", prompt, log_msg, LINE_ENDING).as_bytes())?;
                }
                WriteOption::Terminal => {
                    #[allow(unused_mut)]
                    let mut prompt = prompt.to_string();
                    #[cfg(feature = "color")]
                    {
                        prompt = color_func(&prompt, self.is_logging_to_file()).to_string();
                    }
                    write!(std::io::stderr(), "{}: {}{}", prompt, log_msg, LINE_ENDING)?;
                }
                WriteOption::Variable(var) => {
                    write!(var, "{} : {}{}", prompt, log_msg, LINE_ENDING)?;
                }
                WriteOption::Discard | WriteOption::Return => (),
            } // Match end
        }
        Ok(())
    }

    /// Write formatted log message
    fn write_formatted_log_msg(
        &mut self,
        prompt: &str,
        log_msg: &str,
        #[cfg(feature = "color")] color_func: ColorDisplayFunc,
    ) -> RadResult<()> {
        let log_pos = self.construct_log_position()?;
        if let Some(option) = &mut self.write_option {
            match option {
                WriteOption::File(file) => {
                    file.inner().write_all(
                        format!("{} : {} -> {}{}", prompt, log_msg, log_pos, LINE_ENDING)
                            .as_bytes(),
                    )?;
                }
                WriteOption::Terminal => {
                    #[allow(unused_mut)]
                    let mut prompt = prompt.to_string();
                    #[cfg(feature = "color")]
                    {
                        prompt = color_func(&prompt, self.is_logging_to_file()).to_string();
                    }
                    write!(
                        std::io::stderr(),
                        "{}: {} {} --> {}{}",
                        prompt,
                        log_msg,
                        LINE_ENDING,
                        log_pos,
                        LINE_ENDING
                    )?;
                }
                WriteOption::Variable(var) => {
                    write!(
                        var,
                        "{} : {} -> {}{}",
                        prompt, log_msg, log_pos, LINE_ENDING
                    )?;
                }
                WriteOption::Discard | WriteOption::Return => (),
            } // Match end
        }
        Ok(())
    }

    /// Log message
    pub(crate) fn log(&mut self, log_msg: &str) -> RadResult<()> {
        self.write_formatted_log_msg(
            "log",
            log_msg,
            #[cfg(feature = "color")]
            Utils::green,
        )
    }

    /// Log error
    pub(crate) fn elog(&mut self, log_msg: &str) -> RadResult<()> {
        self.stat.error_count += 1;

        if self.assert {
            return Ok(());
        }
        self.write_formatted_log_msg(
            "error",
            log_msg,
            #[cfg(feature = "color")]
            Utils::red,
        )
    }

    /// Log error without line number
    pub(crate) fn elog_no_line(&mut self, log_msg: impl std::fmt::Display) -> RadResult<()> {
        self.stat.error_count += 1;

        if self.assert {
            return Ok(());
        }
        self.write_formatted_log_msg_without_line(
            "error",
            &log_msg.to_string(),
            #[cfg(feature = "color")]
            Utils::red,
        )?;
        Ok(())
    }

    /// Log warning
    pub(crate) fn wlog(&mut self, log_msg: &str, warning_type: WarningType) -> RadResult<()> {
        if self.suppresion_type == WarningType::Any || self.suppresion_type == warning_type {
            return Ok(());
        }

        self.stat.warning_count += 1;

        if self.assert {
            return Ok(());
        }

        self.write_formatted_log_msg(
            "warning",
            log_msg,
            #[cfg(feature = "color")]
            Utils::yellow,
        )
    }

    /// Log warning within line
    pub(crate) fn wlog_no_line(
        &mut self,
        log_msg: &str,
        warning_type: WarningType,
    ) -> RadResult<()> {
        if self.suppresion_type == WarningType::Any || self.suppresion_type == warning_type {
            return Ok(());
        }

        self.stat.warning_count += 1;

        if self.assert {
            return Ok(());
        }

        self.write_formatted_log_msg_without_line(
            "warning",
            log_msg,
            #[cfg(feature = "color")]
            Utils::yellow,
        )?;

        Ok(())
    }

    /// Assertion log
    pub fn alog(&mut self, success: bool) -> RadResult<()> {
        if success {
            self.stat.assert_success += 1;
            return Ok(());
        }
        self.stat.assert_fail += 1;
        self.write_formatted_log_msg(
            "assert fail",
            "",
            #[cfg(feature = "color")]
            Utils::red,
        )
    }

    /// Print result of logging of warnings and errors
    pub fn print_result(&mut self) -> RadResult<()> {
        let log_to_file = self.is_logging_to_file();
        if let Some(option) = &mut self.write_option {
            // There is either error or warning
            let error_result = format!(
                "{}: found {} errors",
                Utils::red("error", log_to_file),
                self.stat.error_count
            );
            let warning_result = format!(
                "{}: found {} warnings",
                Utils::yellow("warning", log_to_file),
                self.stat.warning_count
            );
            let assert_result = format!(
                "
{}
SUCCESS : {}
FAIL: {}",
                Utils::green("Assert", log_to_file),
                self.stat.assert_success,
                self.stat.assert_fail
            );
            match option {
                WriteOption::File(file) => {
                    if self.stat.error_count > 0 {
                        file.inner().write_all(error_result.as_bytes())?;
                    }
                    if self.stat.warning_count > 0 {
                        file.inner().write_all(warning_result.as_bytes())?;
                    }
                    if self.assert {
                        file.inner().write_all(assert_result.as_bytes())?;
                    }
                }
                WriteOption::Terminal => {
                    if self.stat.error_count > 0 {
                        writeln!(std::io::stderr(), "{}", error_result)?;
                    }
                    if self.stat.warning_count > 0 {
                        writeln!(std::io::stderr(), "{}", warning_result)?;
                    }
                    if self.assert {
                        writeln!(std::io::stderr(), "{}", assert_result)?;
                    }
                }
                WriteOption::Discard | WriteOption::Variable(_) | WriteOption::Return => (),
            }
        } else {
            // Silent option
            // Do nothing
        }

        Ok(())
    }

    // ----------
    // Debug related methods
    // <DEBUG>

    /// Check if logger is logging to file or not
    pub fn is_logging_to_file(&self) -> bool {
        matches!(self.write_option, Some(WriteOption::File(_)))
    }

    /// Log debug information
    #[cfg(feature = "debug")]
    pub fn dlog_print(&mut self, log: &str) -> RadResult<()> {
        let track = self.get_first_track();
        let last_line = track.line_index;
        if let Some(option) = &mut self.write_option {
            match option {
                WriteOption::Terminal => {
                    write!(
                        std::io::stderr(),
                        "{}{}{}",
                        Utils::green(&format!("{}:log", last_line), self.is_logging_to_file()),
                        LINE_ENDING,
                        log
                    )?;
                }
                WriteOption::File(file) => {
                    file.inner()
                        .write_all(format!("{}:log{}{}", last_line, LINE_ENDING, log).as_bytes())?;
                }
                _ => (),
            }
        }
        Ok(())
    }
    // End of debug related methods
    // </DEBUG>
    // ----------
}

/// Type variant or warning
///
/// - None : Default value
/// - Security : Security related warning
/// - Sanity : Warning about possible errors
/// - Any : Both warnings
#[derive(PartialEq, Eq)]
pub enum WarningType {
    /// Default wrapping type
    None,
    /// About possibly dangerous behaviours
    Security,
    /// About possibly unintended behaviours
    Sanity,
    /// Both warnings
    Any,
}

impl std::str::FromStr for WarningType {
    type Err = RadError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "none" => Self::None,
            "security" => Self::Security,
            "sanity" => Self::Sanity,
            "any" => Self::Any,
            _ => {
                return Err(RadError::InvalidConversion(format!(
                    "Cannot convert \"{}\" into WarningType",
                    s
                )))
            }
        })
    }
}

/// Trackers container that saves trakcer as stack
#[derive(Debug)]
pub struct TrackerStack {
    pub(crate) stack: Vec<Tracker<TrackType>>,
}

impl TrackerStack {
    /// Create a new instance
    pub fn new() -> Self {
        Self { stack: vec![] }
    }

    /// Gets a top-most trakcer
    pub fn tracker(&self) -> &Tracker<TrackType> {
        self.stack.last().unwrap()
    }

    /// Gets a top-most trakcer as mutable
    pub fn tracker_mut(&mut self) -> &mut Tracker<TrackType> {
        self.stack.last_mut().unwrap()
    }

    /// Creates a new tracker on top of stack
    pub fn increase_level(&mut self, track_type: TrackType) {
        let tracker = Tracker::new(track_type);
        self.stack.push(tracker);
    }

    /// Pop last tracker on top of stack
    pub fn decrease_level(&mut self) {
        self.stack.pop();
    }
}

/// Type of a track
#[derive(Debug)]
pub enum TrackType {
    /// Meaningful but not decided milestone
    Record(String),
    /// Start of new input
    Input(String),
    /// Start of an argument
    Argument(String),
    /// Macro body
    Body(String),
}

impl std::fmt::Display for TrackType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Record(cont) => write!(f, "RECORD = {}", cont),
            Self::Input(cont) => write!(f, "INPUT = {}", cont),
            Self::Argument(cont) => write!(f, "MACRO = {}", cont),
            Self::Body(cont) => write!(f, "MACRO = {}", cont),
        }
    }
}