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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
//! # Basic module
//!
//! Basic module includes struct and methods related to basic macros which are technically function
//! pointers.

use std::array::IntoIter;
use std::io::Write;
use std::fs::OpenOptions;
use std::collections::HashMap;
use std::iter::FromIterator;
use std::path::PathBuf;
use std::process::Command;
use crate::error::RadError;
use crate::arg_parser::ArgParser;
use crate::consts::MAIN_CALLER;
use regex::Regex;
use crate::utils::Utils;
use crate::processor::{Processor, auth::{AuthState, AuthType}};
#[cfg(feature = "csv")]
use crate::formatter::Formatter;
#[cfg(feature = "lipsum")]
use lipsum::lipsum;

/// Type signature of basic macros
///
/// This is in order of args, greediness, processor's mutable reference
///
/// # Example
///
/// ```rust
/// fn demo(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
///     let mut medium = String::new();
///     // Some logics go here
///     if this_macro_prints_something {
///         Ok(Some(medium))
///     } else {
///         // If return "None", then single newline will be removed
///         Ok(None)
///     }
/// }
///
/// // ... While building a processor ...
/// processor.add_basic_rules(vec![("test", test as MacroType)]);
/// ```
pub type MacroType = fn(&str, bool ,&mut Processor) -> Result<Option<String>, RadError>;

#[derive(Clone)]
pub struct BasicMacro {
    macros : HashMap<String, MacroType>,
}

impl BasicMacro {
    /// Creates empty map
    pub fn empty() -> Self {
        Self {
            macros: HashMap::new(),
        }
    }

    /// Creates new basic macro hashmap
    ///
    /// Optional macros are included only when a feature is enabled
    pub fn new() -> Self {
        // Create hashmap of functions
        #[allow(unused_mut)]
        let mut map = HashMap::from_iter(IntoIter::new([
            ("regex".to_owned(), BasicMacro::regex_sub as MacroType),
            ("trim".to_owned(), BasicMacro::trim as MacroType),
            ("chomp".to_owned(), BasicMacro::chomp as MacroType).to_owned(),
            ("comp".to_owned(), BasicMacro::compress as MacroType).to_owned(),
            ("include".to_owned(), BasicMacro::include as MacroType).to_owned(),
            ("repeat".to_owned(), BasicMacro::repeat as MacroType).to_owned(),
            ("syscmd".to_owned(), BasicMacro::syscmd as MacroType).to_owned(),
            ("if".to_owned(), BasicMacro::if_cond as MacroType).to_owned(),
            ("ifelse".to_owned(), BasicMacro::ifelse as MacroType).to_owned(),
            ("ifdef".to_owned(), BasicMacro::ifdef as MacroType).to_owned(),
            ("foreach".to_owned(), BasicMacro::foreach as MacroType).to_owned(),
            ("forloop".to_owned(), BasicMacro::forloop as MacroType).to_owned(),
            ("undef".to_owned(), BasicMacro::undefine_call as MacroType).to_owned(),
            ("rename".to_owned(), BasicMacro::rename_call as MacroType).to_owned(),
            ("append".to_owned(), BasicMacro::append as MacroType).to_owned(),
            ("len".to_owned(), BasicMacro::len as MacroType).to_owned(),
            ("tr".to_owned(), BasicMacro::translate as MacroType).to_owned(),
            ("sub".to_owned(), BasicMacro::substring as MacroType).to_owned(),
            ("pause".to_owned(), BasicMacro::pause as MacroType).to_owned(),
            ("tempto".to_owned(), BasicMacro::set_temp_target as MacroType).to_owned(),
            ("tempout".to_owned(), BasicMacro::temp_out as MacroType).to_owned(),
            ("tempin".to_owned(), BasicMacro::temp_include as MacroType).to_owned(),
            ("redir".to_owned(), BasicMacro::temp_redirect as MacroType).to_owned(),
            ("fileout".to_owned(), BasicMacro::file_out as MacroType).to_owned(),
            ("pipe".to_owned(), BasicMacro::pipe as MacroType).to_owned(),
            ("bind".to_owned(), BasicMacro::bind_to_local as MacroType).to_owned(),
            ("env".to_owned(), BasicMacro::get_env as MacroType).to_owned(),
            ("path".to_owned(), BasicMacro::merge_path as MacroType).to_owned(),
            ("nl".to_owned(), BasicMacro::newline as MacroType).to_owned(),
            ("-".to_owned(), BasicMacro::get_pipe as MacroType).to_owned(),
        ]));
        
        // Optional macros
        #[cfg(feature = "csv")]
        {
            map.insert("from".to_owned(), BasicMacro::from_data as MacroType);
            map.insert("table".to_owned(), BasicMacro::table as MacroType);
        }
        #[cfg(feature = "chrono")]
        {
            map.insert("time".to_owned(), BasicMacro::time as MacroType);
            map.insert("date".to_owned(), BasicMacro::date as MacroType);
        }
        #[cfg(feature = "lipsum")]
        map.insert("lipsum".to_owned(), BasicMacro::placeholder as MacroType);
        #[cfg(feature = "evalexpr")]
        map.insert("eval".to_owned(), BasicMacro::eval as MacroType);

        // Return struct
        Self { macros : map }
    }

    /// Add new basic rule
    pub fn add_new_rule(&mut self, name: &str, macro_ref: MacroType) {
        self.macros.insert(name.to_owned(), macro_ref);
    }

    /// Check if a given macro exists
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the macro to find
    pub fn contains(&self, name: &str) -> bool {
        self.macros.contains_key(name)
    }

    /// Check file authority
    fn is_granted(name:&str, auth_type: AuthType, processor: &mut Processor) -> Result<bool, RadError> {
        match processor.get_auth_state(&auth_type) {
            AuthState::Restricted => {
                processor.log_error(&format!("\"{}\" not allowed.\"{:?}\" permission is required", name, auth_type))?;
                Ok(false)
            }
            AuthState::Warn => {
                processor.log_warning(&format!("\"{}\" was called with \"{:?}\" permission", name, auth_type))?;
                Ok(true)
            }
            AuthState::Open => Ok(true),
        }
    }

    /// Call a macro
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the macro to call
    /// * `args` - Argument sto supply to macro
    /// * `greedy` - Whether macro should interpret arguments greedily
    /// * `processor` - Processor instance to execute macro
    pub fn call(&mut self, name : &str, args: &str,greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(func) = self.macros.get(name) {
            // Print out macro call result
            let result = func(args, greedy, processor);
            if let Err(err) = result {
                eprintln!("{}",err);
                Ok(None)
            } else { result }
        } else {
            Ok(None)
        }
    }

    /// Undefine a macro
    ///
    /// # Arguments
    ///
    /// * `name` - Macro name to undefine
    pub fn undefine(&mut self, name: &str) {
        self.macros.remove(name);
    }

    /// Rename a macro
    ///
    /// # Arguments
    ///
    /// * `name` - Source macro name to find
    /// * `target` - Target macro name to apply
    pub fn rename(&mut self, name: &str, target: &str) {
        let func = self.macros.remove(name).unwrap();
        self.macros.insert(target.to_owned(), func);
    }

    // ==========
    // Basic Macros
    // ==========
    /// Print out current time
    ///
    /// # Usage
    ///
    /// $time()
    #[cfg(feature = "chrono")]
    fn time(_: &str, _: bool, _ : &mut Processor) -> Result<Option<String>, RadError> {
        Ok(Some(format!("{}", chrono::offset::Local::now().format("%H:%M:%S"))))
    }

    /// Print out current date
    ///
    /// # Usage
    ///
    /// $date()
    #[cfg(feature = "chrono")]
    fn date(_: &str, _: bool, _ : &mut Processor) -> Result<Option<String>, RadError> {
        Ok(Some(format!("{}", chrono::offset::Local::now().format("%Y-%m-%d"))))
    }

    /// Substitute the given source with following match expressions
    ///
    /// # Usage
    ///
    /// $regex(source_text,regex_match,substitution)
    fn regex_sub(args: &str, greedy: bool, _: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 3, greedy) {
            let source= &args[0];
            let match_expr= &args[1];
            let substitution= &args[2];

            // This is regex expression without any preceding and trailing commands
            let reg = Regex::new(&format!(r"{}", match_expr))?;
            let result = reg.replace_all(source, substitution); // This is a cow, moo~
            Ok(Some(result.to_string()))
        } else {
            Err(RadError::InvalidArgument("Regex sub requires three arguments".to_owned()))
        }
    }

    /// Evaluate given expression
    ///
    /// This returns true, false or evaluated number
    ///
    /// # Usage
    ///
    /// $eval(expression)
    #[cfg(feature = "evalexpr")]
    fn eval(args: &str, greedy: bool,_: &mut Processor ) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            let formula = &args[0];
            let result = evalexpr::eval(formula)?;
            // TODO Enable floating points length (or something similar)
            Ok(Some(result.to_string()))
        } else {
            Err(RadError::InvalidArgument("Eval requires an argument".to_owned()))
        }
    }

    /// Trim preceding and trailing whitespaces (' ', '\n', '\t', '\r')
    ///
    /// # Usage
    ///
    /// $trim(expression)
    fn trim(args: &str, greedy: bool, _: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            Ok(Some(Utils::trim(&args[0])?))
        } else {
            Err(RadError::InvalidArgument("Trim requires an argument".to_owned()))
        }
    }

    /// Removes duplicate newlines whithin given input
    ///
    /// # Usage
    ///
    /// $chomp(expression)
    fn chomp(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            let source = &args[0];
            let reg = Regex::new(&format!(r"{0}\s*{0}", &processor.newline))?;
            let result = reg.replace_all(source, &format!("{0}{0}", &processor.newline));

            Ok(Some(result.to_string()))
        } else {
            Err(RadError::InvalidArgument("Chomp requires an argument".to_owned()))
        }
    }

    /// Both apply trim and chomp to given expression
    ///
    /// # Usage
    ///
    /// $comp(Expression)
    fn compress(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            let source = &args[0];
            // Chomp and then compress
            let result = Utils::trim(&BasicMacro::chomp(source,greedy, processor)?.unwrap())?;

            Ok(Some(result.to_string()))
        } else {
            Err(RadError::InvalidArgument("Compress requires an argument".to_owned()))
        }
    }

    /// Creates placeholder with given amount of word counts
    ///
    /// # Usage
    ///
    /// $lipsum(Number)
    #[cfg(feature = "lipsum")]
    fn placeholder(args: &str, greedy: bool,_: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            let word_count = &args[0];
            if let Ok(count) = Utils::trim(word_count)?.parse::<usize>() {
                Ok(Some(lipsum(count)))
            } else {
                Err(RadError::InvalidArgument(format!("Lipsum needs a number bigger or equal to 0 (unsigned integer) but given \"{}\"", word_count)))
            }
        } else {
            Err(RadError::InvalidArgument("Placeholder requires an argument".to_owned()))
        }
    }

    /// Paste given file's content
    ///
    /// Every macros within the file is also expanded
    ///
    /// # Usage
    ///
    /// $include(path)
    fn include(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if !Self::is_granted("include", AuthType::FIN,processor)? {
            return Ok(None);
        }
        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            let raw = Utils::trim(&args[0])?;
            let file_path = std::path::Path::new(&raw);
            if file_path.is_file() { 
                processor.set_sandbox();
                let result = processor.from_file(file_path)?;
                Ok(Some(result))
            } else {
                let formatted = format!("File path : \"{}\" doesn't exist or not a file", file_path.display());
                Err(RadError::InvalidArgument(formatted))
            }
        } else {
            Err(RadError::InvalidArgument("Include requires an argument".to_owned()))
        }
    }

    /// Repeat given expression about given amount times
    ///
    /// # Usage
    ///
    /// $repeat(count,text)
    fn repeat(args: &str, greedy: bool,_: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 2, greedy) {
            let repeat_count;
            if let Ok(count) = Utils::trim(&args[0])?.parse::<usize>() {
                repeat_count = count;
            } else {
                return Err(RadError::InvalidArgument(format!("Repeat needs a number bigger or equal to 0 (unsigned integer) but given \"{}\"", &args[0])));
            }
            let repeat_object = &args[1];
            let mut repeated = String::new();
            for _ in 0..repeat_count {
                repeated.push_str(&repeat_object);
            }
            Ok(Some(repeated))
        } else {
            Err(RadError::InvalidArgument("Repeat requires two arguments".to_owned()))
        }
    }

    /// Call system command
    ///
    /// This calls via 'CMD \C' in windows platform while unix call is operated without any mediation.
    ///
    /// Syscmd is always greedy
    ///
    /// # Usage
    ///
    /// $syscmd(system command -a arguments)
    fn syscmd(args: &str, _: bool,p: &mut Processor) -> Result<Option<String>, RadError> {
        if !Self::is_granted("syscmd", AuthType::CMD,p)? {
            return Ok(None);
        }
        if let Some(args_content) = ArgParser::new().args_with_len(args, 1, true) {
            let source = &args_content[0];
            let arg_vec = source.split(' ').collect::<Vec<&str>>();

            let output = if cfg!(target_os = "windows") {
                Command::new("cmd")
                    .arg("/C")
                    .args(arg_vec)
                    .output()
                    .expect("failed to execute process")
                    .stdout
            } else {
                let sys_args = if arg_vec.len() > 1 { &arg_vec[1..] } else { &[] };
                Command::new(&arg_vec[0])
                    .args(sys_args)
                    .output()
                    .expect("failed to execute process")
                    .stdout
            };

            Ok(Some(String::from_utf8(output)?))
        } else {
            Err(RadError::InvalidArgument("Syscmd requires an argument".to_owned()))
        }
    }

    /// Print content according to given condition
    /// 
    /// If macro's second argument is evaluated twice.
    ///
    /// # Usage 
    ///
    /// $if(evaluation, \*ifstate*\)
    fn if_cond(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 2, greedy) {
            let boolean = &args[0];
            let if_state = &args[1];

            // Given condition is true
            let trimmed_cond = Utils::trim(boolean)?;
            if let Ok(cond) = trimmed_cond.parse::<bool>() {
                if cond { 
                    let result = processor.parse_chunk_args(0, &MAIN_CALLER.to_owned(), if_state)?;
                    return Ok(Some(result)); 
                }
            } else if let Ok(number) = trimmed_cond.parse::<i32>() {
                if number != 0 { 
                    let result = processor.parse_chunk_args(0, &MAIN_CALLER.to_owned(), if_state)?;
                    return Ok(Some(result)); 
                }
            } else {
                return Err(RadError::InvalidArgument(format!("If requires either true/false or zero/nonzero integer but given \"{}\"", trimmed_cond)))
            }

            Ok(None)
        } else {
            Err(RadError::InvalidArgument("if requires two arguments".to_owned()))
        }
    }

    /// Print content according to given condition
    /// 
    /// Ifelse second and third arguemtns are evaluated twice.
    ///
    /// # Usage 
    ///
    /// $ifelse(evaluation, \*ifstate*\, \*elsestate*\)
    fn ifelse(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 3, greedy) {
            let boolean = &args[0];
            let if_state = &args[1];

            // Given condition is true
            let trimmed_cond = Utils::trim(boolean)?;
            if let Ok(cond) = trimmed_cond.parse::<bool>() {
                if cond { 
                    let result = processor.parse_chunk_args(0, &MAIN_CALLER.to_owned(), if_state)?;
                    return Ok(Some(result)); 
                }
            } else if let Ok(number) = trimmed_cond.parse::<i32>() {
                if number != 0 { 
                    let result = processor.parse_chunk_args(0, &MAIN_CALLER.to_owned(), if_state)?;
                    return Ok(Some(result)); 
                }
            } else {
                return Err(RadError::InvalidArgument(format!("Ifelse requires either true/false or zero/nonzero integer but given \"{}\"",trimmed_cond)))
            }

            // Else state
            let else_state = &args[2];
            let result = processor.parse_chunk_args(0, &MAIN_CALLER.to_owned(), else_state)?;
            return Ok(Some(result));
        } else {
            Err(RadError::InvalidArgument("ifelse requires three argument".to_owned()))
        }
    }

    /// Check if macro is defined or not
    ///
    /// This return 'true' or 'false'
    ///
    /// # Usage
    ///
    /// $ifdef(macro_name) 
    fn ifdef(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            let name = &Utils::trim(&args[0])?;
            let map = processor.get_map();

            // Return true or false by the definition
            if map.basic.contains(name) || map.custom.contains_key(name) {
                Ok(Some("true".to_owned()))
            } else {
                Ok(Some("false".to_owned()))
            }
        } else {
            Err(RadError::InvalidArgument("Ifdef requires an argument".to_owned()))
        }
    }

    /// Undefine a macro 
    ///
    /// 'Define' and 'BR' cannot be undefined because it is not actually a macro 
    ///
    /// # Usage
    ///
    /// $undef(macro_name)
    fn undefine_call(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            let name = &Utils::trim(&args[0])?;

            let map = processor.get_map();
            if map.contains(name) { 
                map.undefine(name);
            } else {
                processor.log_error(&format!("Macro \"{}\" doesn't exist, therefore cannot undefine", name))?;
            }
            Ok(None)
        } else {
            Err(RadError::InvalidArgument("Undefine requires an argument".to_owned()))
        }
    }

    /// Loop around given values and substitute iterators  with the value
    ///
    /// Foreach's second macro is evaluated twice.
    ///
    /// # Usage 
    ///
    /// $foreach(\*a,b,c*\,\*$:*\)
    fn foreach(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 2, greedy) {
            let mut sums = String::new();
            let target = &args[1]; // evaluate on loop
            let loopable = &args[0];

            for value in loopable.split(',') {
                let result = processor.parse_chunk_args(0, &MAIN_CALLER.to_owned(), &target.replace("$:", value))?;
                sums.push_str(&result);
            }
            Ok(Some(sums))
        } else {
            Err(RadError::InvalidArgument("Foreach requires two argument".to_owned()))
        }
    }

    /// For loop around given min, max value and finally substitue iterators with value
    ///
    /// Forloop's second macro is evaluated twice.
    ///
    /// # Usage
    ///
    /// $forloop(1,5,\*$:*\)
    fn forloop(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 3, greedy) {
            let mut sums = String::new();
            let expression = &args[2]; // evaluate on loop

            let min: usize; 
            let max: usize; 
            if let Ok(num) = Utils::trim(&args[0])?.parse::<usize>() {
                min = num;
            } else { return Err(RadError::InvalidArgument(format!("Forloop's min value should be non zero positive integer but given {}", &args[0]))); }
            if let Ok(num) = Utils::trim(&args[1])?.parse::<usize>() {
                max = num
            } else { return Err(RadError::InvalidArgument(format!("Forloop's min value should be non zero positive integer gut given \"{}\"", &args[1]))); }
            
            for value in min..=max {
                let result = processor.parse_chunk_args(0, &MAIN_CALLER.to_owned(), &expression.replace("$:", &value.to_string()))?;
                sums.push_str(&result);
            }

            Ok(Some(sums))
        } else {
            Err(RadError::InvalidArgument("Forloop requires two argument".to_owned()))
        }
    }

    /// Create multiple macro executions from given csv value
    ///
    /// # Usage
    ///
    /// $from(\*1,2,3
    /// 4,5,6*\, macro_name)
    #[cfg(feature = "csv")]
    fn from_data(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 2, greedy) {
            let macro_data = &args[0];
            let macro_name = &Utils::trim(&args[1])?;

            let result = Formatter::csv_to_macros(macro_name, macro_data, &processor.newline)?;
            // This is necessary
            let result = processor.parse_chunk_args(0, &MAIN_CALLER.to_owned(), &result)?;
            Ok(Some(result))
        } else {
            Err(RadError::InvalidArgument("From requires two arguments".to_owned()))
        }
    }

    /// Create a table with given format and csv input
    ///
    /// Available formats are 'github', 'wikitext' and 'html'
    ///
    /// # Usage
    ///
    /// $table(github,"1,2,3
    /// 4,5,6")
    #[cfg(feature = "csv")]
    fn table(args: &str, greedy: bool, p: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 2, greedy) {
            let table_format = &args[0]; // Either gfm, wikitex, latex, none
            let csv_content = &args[1];
            let result = Formatter::csv_to_table(table_format, csv_content, &p.newline)?;
            Ok(Some(result))
        } else {
            Err(RadError::InvalidArgument("Table requires two arguments".to_owned()))
        }
    }

    /// Put value into a temporary stack called pipe
    ///
    /// Piped value can be popped with macro '-'
    ///
    /// # Usage
    ///
    /// $pipe(Value)
    fn pipe(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            processor.pipe_value = args[0].to_owned();
        }
        Ok(None)
    }

    /// Bind a local macro
    ///
    /// Bound macro gets deleted after macro execution
    ///
    /// # Usage
    ///
    /// $bind(name,value)
    fn bind_to_local(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 2, greedy) {
            let name = &args[0];
            let value = &args[1];
            processor.get_map().new_local(1, name, value);
            if processor.get_map().contains(name) {
                processor.log_warning(&format!("Creating a binding with a name already existing : \"{}\"", name))?;
            }
        }
        Ok(None)
    }

    /// Get environment variable with given name
    ///
    /// # Usage
    ///
    /// $env(SHELL)
    fn get_env(args: &str, _: bool, p : &mut Processor) -> Result<Option<String>, RadError> {
        if !Self::is_granted("env", AuthType::ENV,p)? {
            return Ok(None);
        }
        let out = std::env::var(args)?;
        Ok(Some(out))
    }

    /// Merge two path into a single path
    ///
    /// This creates platform agonistic path which can be consumed by other macros.
    ///
    /// # Usage
    ///
    /// $path($env(HOME),document)
    fn merge_path(args: &str, greedy: bool, _: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 2, greedy) {
            let target = Utils::trim(&args[0])?;
            let added = Utils::trim(&args[1])?;

            let out = format!("{}",&std::path::Path::new(&target).join(&added).display());
            Ok(Some(out))
        } else {
            Err(RadError::InvalidArgument("Path macro needs two arguments".to_owned()))
        }
    }

    /// Yield newline according to platform or user option
    ///
    /// # Usage
    ///
    /// $nl()
    fn newline(_: &str, _: bool, p: &mut Processor) -> Result<Option<String>, RadError> {
        Ok(Some(p.newline.to_owned()))
    }

    /// Pop pipe value
    ///
    /// # Usage
    ///
    /// $-()
    fn get_pipe(_: &str, _: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        let out = processor.pipe_value.clone();
        processor.pipe_value.clear();
        Ok(Some(out))
    }

    /// Return a length of the string
    /// 
    /// This is O(n) operation.
    /// String.len() function returns byte length not "Character" length
    /// therefore, chars().count() is used
    ///
    /// # Usage
    ///
    /// $len(안녕하세요)
    /// $len(Hello)
    fn len(args: &str, _: bool, _: &mut Processor) -> Result<Option<String>, RadError> {
        Ok(Some(args.chars().count().to_string()))
    }

    /// Rename macro rule to other name
    ///
    /// Define and BR can't be renamed.
    ///
    /// # Usage
    ///
    /// $rename(name,target)
    fn rename_call(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 2, greedy) {
            let target = &args[0];
            let new = &args[1];

            let map = processor.get_map();
            if map.contains(target) { 
                processor.get_map().rename(target, new);
            } else {
                processor.log_error(&format!("Macro \"{}\" doesn't exist, therefore cannot rename", target))?;
            }

            Ok(None)
        } else {
            Err(RadError::InvalidArgument("Rename requires two arguments".to_owned()))
        }
    }

    /// Append content to a macro
    ///
    /// Only custom macros can be appended.
    ///
    /// # Usage
    ///
    /// $append(macro_name,Content)
    fn append(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 2, greedy) {
            let name = &args[0];
            let target = &args[1];
            let map = processor.get_map();
            if map.custom.contains_key(name) {
                map.append(name, target);
            } else {
                processor.log_error(&format!("Macro \"{}\" doesn't exist", name))?;
            }

            Ok(None)
        } else {
            Err(RadError::InvalidArgument("Append requires two arguments".to_owned()))
        }
    }

    /// Translate given char aray into corresponding char array
    ///
    /// # Usage
    ///
    /// $tr(Source,abc,ABC)
    fn translate(args: &str, greedy: bool, _: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 3, greedy) {
            let mut source = args[0].clone();
            let target = &args[1].chars().collect::<Vec<char>>();
            let destination = &args[2].chars().collect::<Vec<char>>();

            if target.len() != destination.len() {
                return Err(RadError::InvalidArgument(format!("Tr's replacment should have same length of texts while given \"{:?}\" and \"{:?}\"", target, destination)));
            }

            for i in 0..target.len() {
                source = source.replace(target[i], &destination[i].to_string());
            }

            Ok(Some(source))
        } else {
            Err(RadError::InvalidArgument("Tr requires three arguments".to_owned()))
        }
    }

    /// Get a substring(indexed) from given source
    ///
    /// # Usage
    ///
    /// $sub(0,5,GivenString)
    fn substring(args: &str, greedy: bool, _: &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 3, greedy) {
            let source = &args[2];

            let mut min: Option<usize> = None;
            let mut max: Option<usize> = None;

            let start = Utils::trim(&args[0])?;
            let end = Utils::trim(&args[1])?;

            if let Ok(num) = start.parse::<usize>() {
                min.replace(num);
            } else { 
                if start.len() != 0 {
                    return Err(RadError::InvalidArgument(format!("Sub's min value should be non zero positive integer or empty value but given \"{}\"", start))); 
                }
            }

            if let Ok(num) = end.parse::<usize>() {
                max.replace(num);
            } else { 
                if end.len() != 0 {
                    return Err(RadError::InvalidArgument(format!("Sub's max value should be non zero positive integer or empty value but given \"{}\"", end))); 
                }
            }

            Ok(Some(Utils::utf8_substring(source, min, max)))

        } else {
            Err(RadError::InvalidArgument("Sub requires three arguments".to_owned()))
        }
    }

    // TODO Make pause should be a logic branch not a basic macro?
    /// Pause every macro expansion
    ///
    /// Only other pause call is evaluated
    ///
    /// # Usage
    /// 
    /// $pause(true)
    /// $pause(false)
    fn pause(args: &str, greedy: bool, processor : &mut Processor) -> Result<Option<String>, RadError> {
        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            let arg = &args[0];
            if let Ok(value) =Utils::is_arg_true(arg) {
                if value {
                    processor.paused = true;
                } else {
                    processor.paused = false;
                }
                Ok(None)
            } 
            // Failed to evaluate
            else {
                Err(RadError::InvalidArgument(format!("Pause requires either true/false or zero/nonzero integer, but given \"{}\"", arg)))
            }
        } else {
            Err(RadError::InvalidArgument("Pause requires an argument".to_owned()))
        }
    }

    /// Save content to temporary file
    ///
    /// # Usage
    ///
    /// $tempout(true,Content)
    fn temp_out(args: &str, greedy: bool, p: &mut Processor) -> Result<Option<String>, RadError> {
        if !Self::is_granted("temput", AuthType::FOUT,p)? {
            return Ok(None);
        }

        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            let content = &args[0];
            p.get_temp_file().write_all(content.as_bytes())?;
            Ok(None)
        } else {
            Err(RadError::InvalidArgument("Tempout requires an argument".to_owned()))
        }
    }

    /// Save content to a file
    ///
    /// # Usage
    ///
    /// $fileout(true,file_name,Content)
    fn file_out(args: &str, greedy: bool, p: &mut Processor) -> Result<Option<String>, RadError> {
        if !Self::is_granted("fileout", AuthType::FOUT,p)? {
            return Ok(None);
        }
        if let Some(args) = ArgParser::new().args_with_len(args, 3, greedy) {
            let truncate = &args[0];
            let file_name = &args[1];
            let content = &args[2];
            if let Ok(truncate) = Utils::is_arg_true(truncate) {
                let file = std::env::current_dir()?.join(file_name);
                let mut target_file; 
                if truncate {
                    target_file = OpenOptions::new()
                        .create(true)
                        .write(true)
                        .truncate(true)
                        .open(file)
                        .unwrap();
                    } else {

                        if !file.is_file() {
                            return Err(RadError::InvalidArgument(format!("Failed to read \"{}\". Fileout without truncate option needs exsiting file",file.display())));
                        }

                        target_file = OpenOptions::new()
                            .append(true)
                            .open(file)
                            .unwrap();
                }
                target_file.write_all(content.as_bytes())?;
                Ok(None)
            } else {
                Err(RadError::InvalidArgument(format!("Fileout requires either true/false or zero/nonzero integer but given \"{}\"", truncate)))
            }
        } else {
            Err(RadError::InvalidArgument("Fileout requires three argument".to_owned()))
        }
    }

    /// Include but for temporary file
    ///
    /// # Usage
    ///
    /// $tempin()
    fn temp_include(_: &str, _: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if !Self::is_granted("tempin", AuthType::FIN,processor)? {
            return Ok(None);
        }
        let file = processor.get_temp_path().to_owned();
        processor.set_sandbox();
        Ok(Some(processor.from_file(&file)?))
    }

    /// Redirect all text into temporary file
    ///
    /// Every text including non macro calls are all sent to current temporary files.
    ///
    /// # Usage
    ///
    /// $redir(true) 
    /// $redir(false) 
    fn temp_redirect(args: &str, _: bool, p: &mut Processor) -> Result<Option<String>, RadError> {
        if !Self::is_granted("redir", AuthType::FOUT,p)? {
            return Ok(None);
        }
        if let Some(args) = ArgParser::new().args_with_len(args, 1, false) {
            let toggle = if let Ok(toggle) =Utils::is_arg_true(&args[0]) { 
                toggle
            } else {
                return Err(RadError::InvalidArgument(format!("Redir's agument should be valid boolean value but given \"{}\"", &args[0])));
            };
            p.redirect = toggle;
            Ok(None)
        } else {
            Err(RadError::InvalidArgument("Redir requires an argument".to_owned()))
        }
    }

    /// Set temporary file
    ///
    /// # Usage
    ///
    /// $tempto(file_name)
    fn set_temp_target(args: &str, greedy: bool, processor: &mut Processor) -> Result<Option<String>, RadError> {
        if !Self::is_granted("tempto", AuthType::FOUT,processor)? {
            return Ok(None);
        }
        if let Some(args) = ArgParser::new().args_with_len(args, 1, greedy) {
            processor.set_temp_file(&PathBuf::from(std::env::temp_dir()).join(&args[0]));
            Ok(None)
        } else {
            Err(RadError::InvalidArgument("Temp requires an argument".to_owned()))
        }
    }
}