r4d 3.0.0-rc.2

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
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
use crate::deterred_map::DFunctionMacroType;
use crate::deterred_map::DeterredMacroMap;
use crate::error::RadError;
use crate::function_map::FunctionMacroMap;
use crate::function_map::FunctionMacroType;
use crate::runtime_map::{RuntimeMacro, RuntimeMacroMap};
#[cfg(feature = "signature")]
use crate::sigmap::MacroSignature;
use crate::utils::Utils;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::path::{Path, PathBuf};

/// Genenric result type for every rad operations
///
/// RadResult is a genric result type of T and error of [RadError](RadError)
pub type RadResult<T> = Result<T, RadError>;

/// State enum value about direction of processed text
///
/// - File       : Set file output
/// - Variable   : Set variable to save
/// - Return     : Return otuput directly ( logger ignores this variant )
/// - Terminal   : Print to terminal
/// - Discard    : Do nothing
pub enum WriteOption<'a> {
    File(File),
    Variable(&'a mut String),
    Return,
    Terminal,
    Discard,
}

/// Local macro
#[derive(Clone)]
pub struct LocalMacro {
    pub level: usize,
    pub name: String,
    pub body: String,
}

impl LocalMacro {
    pub fn new(level: usize, name: String, body: String) -> Self {
        Self { level, name, body }
    }
}

/// Macro map that stores all kinds of macro informations
///
/// Included macro types are
/// - Keyword macro
/// - Basic macro
/// - Runtime macro
/// - Local bound macro
pub(crate) struct MacroMap {
    pub deterred: DeterredMacroMap,
    pub function: FunctionMacroMap,
    pub runtime: RuntimeMacroMap,
    pub local: HashMap<String, LocalMacro>,
}

impl MacroMap {
    /// Creates empty map without default macros
    pub fn empty() -> Self {
        Self {
            deterred: DeterredMacroMap::empty(),
            function: FunctionMacroMap::empty(),
            runtime: RuntimeMacroMap::new(),
            local: HashMap::new(),
        }
    }

    /// Creates default map with default function macros
    pub fn new() -> Self {
        Self {
            deterred: DeterredMacroMap::new(),
            function: FunctionMacroMap::new(),
            runtime: RuntimeMacroMap::new(),
            local: HashMap::new(),
        }
    }

    pub fn clear_runtime_macros(&mut self, volatile: bool) {
        self.runtime.clear_runtime_macros(volatile);
    }

    /// Create a new local macro
    ///
    /// This will override local macro if save value was given.
    pub fn add_local_macro(&mut self, level: usize, name: &str, value: &str) {
        self.local.insert(
            Utils::local_name(level, name),
            LocalMacro::new(level, name.to_owned(), value.to_owned()),
        );
    }

    /// Removes a local macro
    ///
    /// This will try to remove but will do nothing if given macro doesn't exist.
    pub fn remove_local_macro(&mut self, level: usize, name: &str) {
        self.local.remove(&Utils::local_name(level, name));
    }

    /// Clear all local macros
    pub fn clear_local(&mut self) {
        self.local.clear();
    }

    /// Retain only local macros that is smaller or equal to current level
    pub fn clear_lower_locals(&mut self, current_level: usize) {
        self.local.retain(|_, mac| mac.level <= current_level);
    }

    pub fn is_deterred_macro(&self, name: &str) -> bool {
        self.deterred.contains(name)
    }

    pub fn contains_macro(
        &self,
        macro_name: &str,
        macro_type: MacroType,
        hygiene_type: Hygiene,
    ) -> bool {
        match macro_type {
            MacroType::Deterred => self.deterred.contains(macro_name),
            MacroType::Function => self.function.contains(macro_name),
            MacroType::Runtime => self.runtime.contains(macro_name, hygiene_type),
            MacroType::Any => {
                self.function.contains(macro_name)
                    || self.runtime.contains(macro_name, hygiene_type)
                    || self.deterred.contains(macro_name)
            }
        }
    }

    // Empty argument should be treated as no arg
    /// Register a new runtime macro
    pub fn register_runtime(
        &mut self,
        name: &str,
        args: &str,
        body: &str,
        hygiene_type: Hygiene,
    ) -> RadResult<()> {
        // Trim all whitespaces and newlines from the string
        let mac = RuntimeMacro::new(&Utils::trim(name), &Utils::trim(args), body);
        self.runtime.new_macro(name, mac, hygiene_type);
        Ok(())
    }

    /// Undeifne macro
    pub fn undefine(&mut self, macro_name: &str, macro_type: MacroType, hygiene_type: Hygiene) {
        match macro_type {
            MacroType::Deterred => {
                self.deterred.undefine(macro_name);
            }
            MacroType::Function => {
                self.function.undefine(macro_name);
            }
            MacroType::Runtime => {
                self.runtime.undefine(macro_name, hygiene_type);
            }
            MacroType::Any => {
                self.function.undefine(macro_name);
                self.runtime.undefine(macro_name, hygiene_type);
                self.deterred.undefine(macro_name);
            }
        }
    }

    pub fn rename(
        &mut self,
        macro_name: &str,
        target_name: &str,
        macro_type: MacroType,
        hygiene_type: Hygiene,
    ) {
        match macro_type {
            MacroType::Deterred => {
                self.deterred.rename(macro_name, target_name);
            }
            MacroType::Function => {
                self.function.rename(macro_name, target_name);
            }
            MacroType::Runtime => {
                self.runtime.rename(macro_name, target_name, hygiene_type);
            }
            MacroType::Any => {
                self.function.rename(macro_name, target_name);
                self.runtime.rename(macro_name, target_name, hygiene_type);
                self.deterred.rename(macro_name, target_name);
            }
        }
    }

    pub fn append(&mut self, name: &str, target: &str, hygiene_type: Hygiene) {
        if self.runtime.contains(name, hygiene_type) {
            self.runtime.append_macro(name, target, hygiene_type);
        }
    }

    pub fn replace(&mut self, name: &str, target: &str, hygiene_type: Hygiene) -> bool {
        if self.runtime.contains(name, hygiene_type) {
            self.runtime.replace_macro(name, target, hygiene_type);
            true
        } else {
            false
        }
    }

    /// Get macro signatures object
    #[cfg(feature = "signature")]
    pub fn get_signatures(&self) -> Vec<MacroSignature> {
        let key_iter = self
            .deterred
            .macros
            .iter()
            .map(|(_, sig)| MacroSignature::from(sig));
        let funcm_iter = self
            .function
            .macros
            .iter()
            .map(|(_, sig)| MacroSignature::from(sig));
        let runtime_iter = self
            .runtime
            .macros
            .iter()
            .map(|(_, mac)| MacroSignature::from(mac));
        key_iter.chain(funcm_iter).chain(runtime_iter).collect()
    }

    #[cfg(feature = "signature")]
    pub fn get_default_signatures(&self) -> Vec<MacroSignature> {
        let key_iter = self
            .deterred
            .macros
            .iter()
            .map(|(_, sig)| MacroSignature::from(sig));
        let funcm_iter = self
            .function
            .macros
            .iter()
            .map(|(_, sig)| MacroSignature::from(sig));
        key_iter.chain(funcm_iter).collect()
    }

    #[cfg(feature = "signature")]
    pub fn get_runtime_signatures(&self) -> Vec<MacroSignature> {
        self.runtime
            .macros
            .iter()
            .map(|(_, mac)| MacroSignature::from(mac))
            .collect()
    }
}

/// Struct designed to check unbalanced parenthesis
pub(crate) struct UnbalancedChecker {
    paren: usize,
}

impl UnbalancedChecker {
    pub fn new() -> Self {
        Self { paren: 0 }
    }
    pub fn check(&mut self, ch: char) -> bool {
        match ch {
            '(' => self.paren += 1,
            ')' => {
                if self.paren > 0 {
                    self.paren -= 1;
                } else {
                    return false;
                }
            }
            _ => {
                return true;
            }
        }
        true
    }
}

/// Readable, writeable struct that holds information of runtime macros
#[derive(Serialize, Deserialize)]
pub struct RuleFile {
    pub rules: HashMap<String, RuntimeMacro>,
}

impl RuleFile {
    pub fn new(rules: Option<HashMap<String, RuntimeMacro>>) -> Self {
        if let Some(content) = rules {
            Self { rules: content }
        } else {
            Self {
                rules: HashMap::new(),
            }
        }
    }

    /// Read from rule file and make it into hash map
    pub fn melt(&mut self, path: &Path) -> RadResult<()> {
        Utils::is_real_path(path)?;
        let result = bincode::deserialize::<Self>(&std::fs::read(path)?);
        if let Err(err) = result {
            Err(RadError::BincodeError(format!(
                "Failed to melt the file : {} \n {}",
                path.display(),
                err
            )))
        } else {
            self.rules.extend(result.unwrap().rules.into_iter());
            Ok(())
        }
    }

    pub fn melt_literal(&mut self, literal: &[u8]) -> RadResult<()> {
        let result = bincode::deserialize::<Self>(literal);
        if let Ok(rule_file) = result {
            self.rules.extend(rule_file.rules.into_iter());
            Ok(())
        } else {
            Err(RadError::BincodeError(
                "Failed to melt the literal value".to_string(),
            ))
        }
    }

    /// Convert runtime rules into a single binary file
    pub(crate) fn freeze(&self, path: &std::path::Path) -> RadResult<()> {
        let result = bincode::serialize(self);
        if result.is_err() {
            Err(RadError::BincodeError(format!(
                "Failed to freeze to a file : {}",
                path.display()
            )))
        } else if std::fs::write(path, result.unwrap()).is_err() {
            Err(RadError::InvalidArgument(format!(
                "Failed to create a file : {}",
                path.display()
            )))
        } else {
            Ok(())
        }
    }
}

/// Macro framgent that processor saves fragmented information of the mcaro invocation
#[derive(Debug)]
pub(crate) struct MacroFragment {
    pub whole_string: String,
    pub name: String,
    pub args: String,
    // This yield processed_args information which is not needed for normal operation.
    #[cfg(feature = "debug")]
    pub processed_args: String,

    // Macro attributes
    pub pipe: bool,
    pub greedy: bool,
    pub yield_literal: bool,
    pub trimmed: bool,
}

impl MacroFragment {
    pub fn new() -> Self {
        MacroFragment {
            whole_string: String::new(),
            name: String::new(),
            args: String::new(),
            #[cfg(feature = "debug")]
            processed_args: String::new(),
            pipe: false,
            greedy: false,
            yield_literal: false,
            trimmed: false,
        }
    }

    /// Reset all state
    pub(crate) fn clear(&mut self) {
        self.whole_string.clear();
        self.name.clear();
        self.args.clear();
        #[cfg(feature = "debug")]
        self.processed_args.clear();
        self.pipe = false;
        self.greedy = false;
        self.yield_literal = false;
        self.trimmed = false;
    }

    /// Check if fragment is empty or not
    ///
    /// This also enables user to check if fragment has been cleared or not
    pub(crate) fn is_empty(&self) -> bool {
        self.whole_string.len() == 0
    }

    pub(crate) fn has_attribute(&self) -> bool {
        self.pipe || self.greedy || self.yield_literal || self.trimmed
    }
}

/// Comment type
///
/// NoComment is for no comment
/// Start is when comment character should be positioned at start of the line
/// Any is when any position is possible
///
/// * Example
/// ```Text
/// % Sample     -> This is ok for Any,Start
/// Prior % Next -> This is only ok for Any
///
/// ```
#[derive(PartialEq, Debug)]
pub enum CommentType {
    /// Don't enable comment
    None,
    /// Only treat a line as a comment when it starts with comment character
    Start,
    /// Treat any text chunk that starts with comment character
    Any,
}

impl std::str::FromStr for CommentType {
    type Err = RadError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let comment_type = match s.to_lowercase().as_str() {
            "none" => Self::None,
            "start" => Self::Start,
            "any" => Self::Any,
            _ => {
                return Err(RadError::InvalidCommandOption(format!(
                    "Comment type : \"{}\" is not available.",
                    s
                )));
            }
        };
        Ok(comment_type)
    }
}

#[derive(Debug)]
/// Diffing behaviour
pub enum DiffOption {
    /// Do not yield diff
    None,
    /// Diff all texts
    All,
    /// Diff only changes
    Change,
}

impl std::str::FromStr for DiffOption {
    type Err = RadError;
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let var = match text.to_lowercase().as_str() {
            "none" => Self::None,
            "all" => Self::All,
            "change" => Self::Change,
            _ => {
                return Err(RadError::InvalidConversion(format!(
                    "Diffoption, \"{}\" is not a valid type",
                    text
                )))
            }
        };
        Ok(var)
    }
}

/// Enum that controls processing flow
pub enum FlowControl {
    None,
    Escape,
    Exit,
}

#[cfg(feature = "signature")]
pub enum SignatureType {
    All,
    Default,
    Runtime,
}

#[cfg(feature = "signature")]
impl SignatureType {
    pub fn from_str(text: &str) -> RadResult<Self> {
        let variant = match text.to_lowercase().as_str() {
            "all" => Self::All,
            "default" => Self::Default,
            "runtime" => Self::Runtime,
            _ => {
                return Err(RadError::InvalidConversion(format!(
                    "\"{}\" is not supported signature type",
                    text
                )))
            }
        };

        Ok(variant)
    }
}

/// Result alias for storage operation
///
/// Error is a boxed container for generic error trait. Therefore any kind of errors can be
/// captured by storageresult.
pub type StorageResult<T> = Result<T, Box<dyn std::error::Error>>;

/// Triat for storage interaction
///
/// Rad can utilizes storage to save given input as modified form and extract data from
///
/// # Example
///
/// ```rust
/// use r4d::{RadStorage, RadError, StorageOutput, StorageResult};
///
/// pub struct StorageDemo {
///     content: Vec<String>,
/// }
///
/// impl RadStorage for StorageDemo {
///     fn update(&mut self, args: &[String]) -> StorageResult<()> {
///         if args.is_empty() {
///             return Err(Box::new(RadError::InvalidArgument("Not enough arguments".to_string())));
///         }
///         self.content.push(args[0].clone());
///
///         Ok(())
///     }
///     fn extract(&mut self, serialize: bool) -> StorageResult<Option<StorageOutput>> {
///         let result = if serialize {
///             StorageOutput::Binary(self.content.join(",").as_bytes().to_vec())
///         } else {
///             StorageOutput::Text(self.content.join(","))
///         };
///         Ok(Some(result))
///     }
/// }
/// ```
pub trait RadStorage {
    /// Update storage with given arguments
    fn update(&mut self, args: &[String]) -> StorageResult<()>;
    /// Extract data from storage.
    ///
    /// # Args
    ///
    /// - serialize : whether to serialize storage output or not
    fn extract(&mut self, serialize: bool) -> StorageResult<Option<StorageOutput>>;
}

#[derive(Debug)]
/// Output that storage creates
pub enum StorageOutput {
    /// Binary form of output
    Binary(Vec<u8>),
    /// Text form of output
    Text(String),
}

impl StorageOutput {
    pub(crate) fn into_printable(self) -> String {
        match self {
            Self::Binary(bytes) => format!("{:?}", bytes),
            Self::Text(text) => text,
        }
    }
}

#[derive(Debug)]
pub enum RelayTarget {
    None,
    File(FileTarget),
    Macro(String),
    #[cfg(not(feature = "wasm"))]
    Temp,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ProcessInput {
    Stdin,
    File(PathBuf),
}

impl ToString for ProcessInput {
    fn to_string(&self) -> String {
        match self {
            Self::Stdin => "Stdin".to_owned(),
            Self::File(file) => file.display().to_string(),
        }
    }
}

/// Standards of behaviour
#[derive(PartialEq)]
pub enum ErrorBehaviour {
    Strict,
    Lenient,
    Purge,
}

#[derive(Clone)]
/// Builder struct for extension macros
///
/// This creates an extension macro without going through tedious processor methods interaction.
///
/// Use a template feature to utilizes eaiser extension register.
///
/// # Example
///
/// ```
/// let mut processor = r4d::Processor::new();
/// #[cfg(feature = "template")]
/// processor.add_ext_macro(r4d::ExtMacroBuilder::new("macro_name")
///     .args(&["a1","b2"])
///     .function(r4d::function_template!(
///         let args = r4d::split_args!(2)?;
///         let result = format!("{} + {}", args[0], args[1]);
///         Ok(Some(result))
/// )));
/// ```
pub struct ExtMacroBuilder {
    pub(crate) macro_name: String,
    pub(crate) macro_type: ExtMacroType,
    pub(crate) args: Vec<String>,
    pub(crate) macro_body: Option<ExtMacroBody>,
    pub(crate) macro_desc: Option<String>,
}

impl ExtMacroBuilder {
    /// Creates an empty macro with given macro name
    pub fn new(macro_name: &str) -> Self {
        Self {
            macro_name: macro_name.to_string(),
            macro_type: ExtMacroType::Function,
            // Empty values
            args: vec![],
            macro_body: None,
            macro_desc: None,
        }
    }

    /// Set macro's body type as function
    pub fn function(mut self, func: FunctionMacroType) -> Self {
        self.macro_type = ExtMacroType::Function;
        self.macro_body = Some(ExtMacroBody::Function(func));
        self
    }

    /// Set macro's body type as deterred
    pub fn deterred(mut self, func: DFunctionMacroType) -> Self {
        self.macro_type = ExtMacroType::Deterred;
        self.macro_body = Some(ExtMacroBody::Deterred(func));
        self
    }

    /// Set macro's arguments
    pub fn args(mut self, args: &[impl AsRef<str>]) -> Self {
        self.args = args.iter().map(|a| a.as_ref().to_string()).collect();
        self
    }

    /// Set description of the macro
    pub fn desc(mut self, description: &str) -> Self {
        self.macro_desc.replace(description.to_string());
        self
    }
}

#[derive(Clone)]
pub(crate) enum ExtMacroType {
    Function,
    Deterred,
}

#[derive(Clone)]
pub(crate) enum ExtMacroBody {
    Function(FunctionMacroType),
    Deterred(DFunctionMacroType),
}

/// Types of a macros
///
/// This is intended for processor ext interface but user can use it directly
pub enum MacroType {
    Function,
    Deterred,
    Runtime,
    Any,
}

#[derive(Debug)]
pub struct FileTarget {
    pub(crate) path: PathBuf,
    pub(crate) file: Option<File>,
}

impl FileTarget {
    pub fn empty() -> Self {
        Self {
            path: PathBuf::new(),
            file: None,
        }
    }

    pub fn set_path(&mut self, path: &Path) {
        self.path = path.to_owned();
        self.file = Some(
            std::fs::OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(path)
                .unwrap(),
        );
    }
}

#[derive(PartialEq, Clone, Copy)]
/// Hygiene variant
///
/// - None    : No hygiene applied
/// - Macro   : Hygine by per invocation
/// - Input   : Hygiene by per input
/// - Aseptic : No runtime definition or invocation at all.
pub enum Hygiene {
    /// No hygiene applied
    None,
    /// Hygine by per invocation
    Macro,
    /// Hygiene by per input
    Input,
    /// No runtime definition or invocation at all.
    Aseptic,
}