r4d 0.11.1

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
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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
//! # processor
//!
//! "processor" module is about processing of given input.
//!
//! Processor substitutes all macros only when the macros were already defined and returns
//! untouched string back if not found any. 
//!
//! Processor can handle various types of inputs (string|stdin|file)
//!
//! # Detailed usage
//! ```rust
//! use rad::RadError;
//! use rad::Processor;
//! use rad::MacroType;
//! use rad::AuthType;
//! use std::path::Path;
//! 
//! // Builder
//! let mut processor = Processor::new()
//!     .purge(true)                                         // Purge undefined macro
//!     .greedy(true)                                        // Makes all macro greedy
//!     .silent(true)                                        // Silents all warnings
//!     .nopanic(true)                                       // No panic in any circumstances
//!     .lenient(true)                                       // Disable strict mode
//!     .custom_rules(Some(vec![Path::new("rule.r4f")]))?    // Read from frozen rule files
//!     .write_to_file(Some(Path::new("out.txt")))?          // default is stdout
//!     .error_to_file(Some(Path::new("err.txt")))?          // default is stderr
//!     .unix_new_line(true)                                 // use unix new line for formatting
//!     .discard(true)                                       // discard all output
//!     // Permission
//!     .allow(Some(vec![AuthType::ENV]))                    // Grant permission of authtypes
//!     .allow_with_warning(Some(vec![AuthType::CMD]))       // Grant permission of authypes with warning enabled
//!     // Debugging options
//!     .debug(true)                                         // Turn on debug mode
//!     .log(true)                                           // Use logging to terminal
//!     .interactive(true)                                   // Use interactive mode
//!     // Create unreferenced instance
//!     .build(); 
//! 
//! // Use Processor::empty() instead of Processor::new()
//! // if you don't want any default macros
//! 
//! // Print information about current processor permissions
//! // This is an warning and can be suppressed with silent option
//! processor.print_permission()?;
//!
//! // Add basic rules(= register functions)
//! // test function is not included in this demo
//! processor.add_basic_rules(vec![("test", test as MacroType)]);
//!
//! // You can add basic rule in form of closure too
//! processor.add_closure_rule(
//!     "test",                                                       // Name of macro
//!     2,                                                            // Count of arguments
//!     Box::new(|args: Vec<String>| -> Option<String> {              // Closure as an internal logic
//!         Some(format!("First : {}\nSecond: {}", args[0], args[1]))
//!     })
//! );
//!
//! 
//! // Add custom rules(in order of "name, args, body") 
//! processor.add_custom_rules(vec![("test","a_src a_link","$a_src() -> $a_link()")]);
//! 
//! // Process with inputs
//! // This prints to desginated write destinations
//! processor.from_string(r#"$define(test=Test)"#)?;
//! processor.from_stdin()?;
//! processor.from_file(Path::new("from.txt"))?;
//! 
//! processor.freeze_to_file(Path::new("out.r4f"))?; // Create frozen file
//! 
//! // Print out result
//! // This will print counts of warning and errors.
//! // It will also print diff between source and processed if diff option was
//! // given as builder pattern.
//! processor.print_result()?;                       
//! ```

#[cfg(feature = "debug")]
use similar::ChangeTag;

use crate::auth::{AuthType, AuthFlags, AuthState};
#[cfg(feature = "debug")]
use std::io::Read;
use std::io::{self, BufReader, Write};
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::path::{ Path , PathBuf};
use crate::basic::MacroType;
use crate::closure_map::ClosureMap;
use crate::error::RadError;
use crate::logger::{Logger, LoggerLines};
#[cfg(feature = "debug")]
use crate::logger::DebugSwitch;
use crate::models::{MacroMap, MacroRule, RuleFile, UnbalancedChecker, WriteOption};
use crate::utils::Utils;
use crate::consts::*;
use crate::lexor::*;
use crate::arg_parser::{ArgParser, GreedyState};

// Methods of processor consists of multiple sections followed as
// <BUILDER>            -> Builder pattern related
// <PROCESS>            -> User functions related
// <DEBUG>              -> Debug related functions
// <PARSE>              -> Parse rleated functions
//     <LEX>            -> sub sectin of parse, this is technically not a lexing but it's named as
// <MISC>               -> Miscellaenous
//
// Find each section's start with <NAME> and find end of section with </NAME>
//
// e.g. <BUILDER> for builder section start and </BUILDER> for builder section end

/// Processor that parses(lexes) given input and print out to desginated output
pub struct Processor{
    pub(crate) current_input : String, // This is either "stdin" or currently being read file's name
    auth_flags: AuthFlags,
    map: MacroMap,
    closure_map: ClosureMap,
    define_parse: DefineParser,
    write_option: WriteOption,
    logger: Logger,
    checker: UnbalancedChecker,
    pub(crate) pipe_value: String,
    pub(crate) newline: String,
    pub(crate) paused: bool,
    pub(crate) redirect: bool,
    #[cfg(feature = "debug")]
    pub(crate) debug: bool,
    #[cfg(feature = "debug")]
    pub(crate) debug_log: bool,
    #[cfg(feature = "debug")]
    debug_switch : DebugSwitch,
    // This is a global line number storage for various deubbing usages
    #[cfg(feature = "debug")]
    line_number : usize,
    // This is a bit bloaty, but debugging needs functionality over efficiency
    #[cfg(feature = "debug")]
    pub(crate) line_caches: HashMap<usize, String>,
    sandbox: bool,
    purge: bool,
    pub(crate) strict: bool,
    pub(crate) nopanic: bool,
    always_greedy: bool,
    // Temp target needs to save both path and file
    // because file doesn't necessarily have path. 
    // Especially in unix, this is not so an unique case
    temp_target: (PathBuf,File), 
    #[cfg(feature = "debug")]
    yield_diff: bool,
    /// File handle for given sources
    #[cfg(feature = "debug")]
    diff_original : Option<File>,
    #[cfg(feature = "debug")]
    diff_processed : Option<File>,
}

impl Processor {
    // ----------
    // Builder pattern methods
    // <BUILDER>
    /// Creates default processor with basic macros
    pub fn new() -> Self {
        Self::new_processor(true)
    }

    /// Creates default processor without basic macros
    pub fn empty() -> Self {
        Self::new_processor(false)
    }

    /// Internal function to create Processor struct
    ///
    /// This creates a complete processor that can parse and create output without any extra
    /// informations.
    ///
    /// Only basic macro usage should be given as an argument.
    fn new_processor(use_basic: bool) -> Self {
        let temp_path= std::env::temp_dir().join("rad.txt");
        let temp_target = (
            temp_path.to_owned(),
            OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&temp_path)
            .unwrap()
        );

        let mut logger = Logger::new();
        logger.set_write_options(Some(WriteOption::Terminal));

        let map = if use_basic {
            MacroMap::new()
        } else {
            MacroMap::empty()
        };

        Self {
            current_input: String::from("stdin"),
            auth_flags: AuthFlags::new(),
            map,
            closure_map: ClosureMap::new(),
            write_option: WriteOption::Terminal,
            define_parse: DefineParser::new(),
            logger,
            checker : UnbalancedChecker::new(),
            newline : LINE_ENDING.to_owned(),
            pipe_value: String::new(),
            paused: false,
            redirect: false,
            purge: false,
            strict: true,
            nopanic: false,
            sandbox : false,
            #[cfg(feature = "debug")]
            debug: false,
            #[cfg(feature = "debug")]
            debug_log: false,
            #[cfg(feature = "debug")]
            debug_switch: DebugSwitch::NextLine,
            #[cfg(feature = "debug")]
            line_number: 1,
            #[cfg(feature = "debug")]
            line_caches: HashMap::new(),
            always_greedy: false,
            temp_target,
            #[cfg(feature = "debug")]
            yield_diff: false,
            #[cfg(feature = "debug")]
            diff_original: None,
            #[cfg(feature = "debug")]
            diff_processed: None,
        }
    }

    /// Set write option to yield output to the file
    pub fn write_to_file(&mut self, target_file: Option<impl AsRef<Path>>) -> Result<&mut Self, RadError> {
        if let Some(target_file) = target_file {
            // If parent doesn't exist it is not a vlid write file
            if let Some(parent) = target_file.as_ref().parent() {
                Utils::is_real_path(parent)?;
            }
            let target_file = OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(target_file)?;

            self.write_option = WriteOption::File(target_file);
        }
        Ok(self)
    }

    /// Yield error to the file
    pub fn error_to_file(&mut self, target_file: Option<impl AsRef<Path>>) -> Result<&mut Self, RadError> {
        if let Some(target_file) = target_file {
            // If parent doesn't exist it is not a vlid write file
            if let Some(parent) = target_file.as_ref().parent() {
                Utils::is_real_path(parent)?;
            }

            let target_file = OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(target_file)?;

            self.logger = Logger::new();
            self.logger.set_write_options(Some(WriteOption::File(target_file)));
        }
        Ok(self)
    }

    /// Use unix line ending instead of operating system's default one
    pub fn unix_new_line(&mut self, use_unix_new_line: bool) -> &mut Self {
        if use_unix_new_line {
            self.newline = "\n".to_owned();
        }
        self
    }

    /// Set greedy option
    pub fn greedy(&mut self, greedy: bool) -> &mut Self {
        if greedy {
            self.always_greedy = true;
        }
        self
    }

    /// Set purge option
    pub fn purge(&mut self, purge: bool) -> &mut Self {
        if purge {
            self.purge = true;
        }
        self
    }

    /// Set lenient
    pub fn lenient(&mut self, lenient: bool) -> &mut Self {
        self.strict = !lenient;
        self
    }

    /// Set silent option
    pub fn silent(&mut self, silent: bool) -> &mut Self {
        if silent {
            self.logger.suppress_warning();
        }
        self
    }

    /// Set nopanic
    pub fn nopanic(&mut self, nopanic: bool) -> &mut Self {
        if nopanic {
            self.nopanic = nopanic;
        }
        self
    }

    /// Add debug options
    #[cfg(feature = "debug")]
    pub fn debug(&mut self, debug: bool) -> &mut Self {
        if debug {
            self.debug = true;
        }
        self
    }

    /// Add debug log options
    #[cfg(feature = "debug")]
    pub fn log(&mut self, log: bool) -> &mut Self {
        if log {
            self.debug_log = true;
        }
        self
    }

    /// Add diff option
    #[cfg(feature = "debug")]
    pub fn diff(&mut self, diff: bool) -> Result<&mut Self, RadError> {
        if diff {
            self.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(self)
    }

    /// Add debug interactive options
    #[cfg(feature = "debug")]
    pub fn interactive(&mut self, interactive: bool) -> &mut Self {
        if interactive {
            self.logger.set_debug_interactive();
        }
        self
    }

    /// Add custom rules
    pub fn custom_rules(&mut self, paths: Option<Vec<impl AsRef<Path>>>) -> Result<&mut Self, RadError> {
        if let Some(paths) = paths {
            let mut rule_file = RuleFile::new(None);
            for p in paths.iter() {
                // File validity is checked by melt methods
                rule_file.melt(p.as_ref())?;
            }
            self.map.custom.extend(rule_file.rules);
        }

        Ok(self)
    }

    /// Open authority of processor
    pub fn allow(&mut self, auth_types : Option<Vec<AuthType>>) -> &mut Self {
        if let Some(auth_types) = auth_types {
            for auth in auth_types {
                self.auth_flags.set_state(&auth, AuthState::Open)
            }
        }
        self
    }

    /// Open authority of processor but yield warning
    pub fn allow_with_warning(&mut self, auth_types : Option<Vec<AuthType>>) -> &mut Self {
        if let Some(auth_types) = auth_types {
            for auth in auth_types {
                self.auth_flags.set_state(&auth, AuthState::Warn)
            }
        }
        self
    }

    /// Discard output
    pub fn discard(&mut self, discard: bool) -> &mut Self {
        if discard {
            self.write_option = WriteOption::Discard;
        }
        self
    }

    /// Creates an unreferenced instance of processor
    pub fn build(&mut self) -> Self {
        std::mem::replace(self, Processor::new())
    }

    // </BUILDER>
    // End builder methods
    // ----------

    // ----------
    // Processing methods
    // <PROCESS>
    //

    /// Print current permission status
    #[allow(dead_code)]
    pub fn print_permission(&mut self) -> Result<(), RadError> {
        if let Some(status) = self.auth_flags.get_status_string() {
            let mut status_with_header = String::from("Permission granted");
            status_with_header.push_str(&status);
            self.log_warning(&status_with_header)?;
        }
        Ok(())
    }

    /// Print the result of a processing
    #[allow(dead_code)]
    pub fn print_result(&mut self) -> Result<(), RadError> {
        self.logger.print_result()?;

        #[cfg(feature = "debug")]
        if self.yield_diff {
            eprintln!("{0}DIFF : {0}",LINE_ENDING);
            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);

            for change in result.iter_all_changes() {
                match change.tag() {
                    ChangeTag::Delete => {
                        eprint!("{}", Utils::red(&format!("- {}", change)));
                    }
                    ChangeTag::Insert => {
                        eprint!("{}", Utils::green(&format!("+ {}", change)));
                    }
                    ChangeTag::Equal => {
                        eprint!("  {}",change);
                    }
                }
            }
        }

        Ok(())
    }

    /// Freeze to single file
    ///
    /// Frozen file is a bincode encoded binary format file.
    pub fn freeze_to_file(&self, path: impl AsRef<Path>) -> Result<(), RadError> {
        // File path validity is checked by freeze method
        RuleFile::new(Some(self.map.custom.clone())).freeze(path.as_ref())?;
        Ok(())
    }

    /// Add new basic rules
    pub fn add_basic_rules(&mut self, basic_rules:Vec<(&str,MacroType)>) {
        for (name, macro_ref) in basic_rules {
            self.map.basic.add_new_rule(name, macro_ref);
        }
    }

    /// Add new closure rule
    ///
    /// Accessing index bigger or equal to the length of argument vector is panicking error
    /// while "insufficient arguments" will simply prints error without panicking and stop
    /// evaluation.
    ///
    /// # Args
    ///
    /// * `name` - Name of the macro to add
    /// * `arg_count` - Count of macro's argument
    /// * `closure` - Vector of string is an parsed arguments with given length.
    ///
    /// # Example
    ///
    /// ```
    /// processor.add_closure_rule(
    ///     "test",                                                       
    ///     2,                                                            
    ///     Box::new(|args: Vec<String>| -> Option<String> {              
    ///         Some(format!("First : {}\nSecond: {}", args[0], args[1]))
    ///     })
    /// );
    /// ```
    pub fn add_closure_rule(&mut self, name: &'static str, arg_count: usize, closure : Box<dyn FnMut(Vec<String>) -> Option<String>>) {
        self.closure_map.add_new(name, arg_count, closure);
    }

    /// Add custom rules without builder pattern
    ///
    /// # Args
    ///
    /// The order of argument is "name, args, body"
    ///
    /// # Example
    ///
    /// ```rust
    /// processor.add_custom_rules(vec![("macro_name","macro_arg1 macro_arg2","macro_body=$macro_arg1()")]);
    /// ```
    pub fn add_custom_rules(&mut self, rules: Vec<(&str,&str,&str)>) {
        for (name,args,body) in rules {
            self.map.custom.insert(
                name.to_owned(), 
                MacroRule { 
                    name: name.to_owned(),
                    args: args.split(' ').map(|s| s.to_owned()).collect::<Vec<String>>(),
                    body: body.to_owned()
                }
            );
        }
    }


    /// Read from string
    pub fn from_string(&mut self, content: &str) -> Result<(), RadError> {
        // Set name as string
        self.set_input("String")?;

        let mut reader = content.as_bytes();
        self.from_buffer(&mut reader, None, false)?;
        Ok(())
    }

    /// Read from standard input
    ///
    /// If debug mode is enabled this, doesn't read stdin line by line but by chunk because user
    /// input is also a standard input and processor cannot distinguish the two
    pub fn from_stdin(&mut self) -> Result<(), RadError> {
        let stdin = io::stdin();

        // Early return if debug
        // This read whole chunk of string 
        #[cfg(feature = "debug")]
        if self.debug {
            let mut input = String::new();
            stdin.lock().read_to_string(&mut input)?;
            // This is necessary to prevent unexpected output from being captured.
            self.from_buffer(&mut input.as_bytes(),None,false)?;
            return Ok(());
        }

        let mut reader = stdin.lock();
        self.from_buffer(&mut reader, None, false)?;
        Ok(())
    }

    /// Process contents from a file
    pub fn from_file(&mut self, path :impl AsRef<Path>) -> Result<(), RadError> {
        // Sandboxed environment, backup
        let backup = if self.sandbox { Some(self.backup()) } else { None };
        // Set file as name of given path
        self.set_file(path.as_ref().to_str().unwrap())?;

        let file_stream = File::open(path)?;
        let mut reader = BufReader::new(file_stream);
        self.from_buffer(&mut reader, backup, false)?;
        Ok(())
    }

    pub(crate) fn from_file_as_chunk(&mut self, path :impl AsRef<Path>) -> Result<Option<String>, RadError> {
        // Sandboxed environment, backup
        let backup = if self.sandbox { Some(self.backup()) } else { None };
        // Set file as name of given path
        self.set_file(path.as_ref().to_str().unwrap())?;

        let file_stream = File::open(path)?;
        let mut reader = BufReader::new(file_stream);
        let debug = self.from_buffer(&mut reader, backup, true);
        debug
    }

    /// Internal method for processing buffers line by line
    fn from_buffer(&mut self,buffer: &mut impl std::io::BufRead, backup: Option<SandboxBackup>, use_container: bool) -> Result<Option<String>, RadError> {
        let mut line_iter = Utils::full_lines(buffer).peekable();
        let mut lexor = Lexor::new();
        let mut frag = MacroFragment::new();

        // Container can be used when file include is nested inside macro definition
        // In that case, bufstream include will print first and other parts of 
        // macro will be printed later
        let container = String::new(); // Don't remove this!
        let mut cont = if use_container{ Some(container) } else { None };

        #[cfg(feature = "debug")]
        self.user_input_on_start()?;
        loop {
            #[cfg(feature = "debug")]
            if let Some(line) = line_iter.peek() {
                let line = line.as_ref().unwrap();
                // Update line cache
                self.line_caches.insert(self.line_number, line.lines().next().unwrap().to_owned());
                // Only if debug switch is nextline
                self.user_input_on_line(&frag)?;
            }
            let result = self.parse_line(&mut line_iter, &mut lexor ,&mut frag)?;
            match result {
                // This means either macro is not found at all
                // or previous macro fragment failed with invalid syntax
                ParseResult::Printable(remainder) => {
                    self.write_to(&remainder,&mut cont)?;

                    // Test if this works
                    #[cfg(feature = "debug")]
                    self.line_caches.clear();

                    // Reset fragment
                    if &frag.whole_string != "" {
                        frag = MacroFragment::new();
                    }
                }
                ParseResult::FoundMacro(remainder) => {
                    self.write_to(&remainder,&mut cont)?;
                }
                // This happens only when given macro involved text should not be printed
                ParseResult::NoPrint => { }
                // End of input, end loop
                ParseResult::EOI => {
                    // THis is necessary somehow, its kinda hard to explain
                    // but chunk read makes trailing new line and it should be deleted
                    if use_container {
                        Utils::pop_newline(cont.as_mut().unwrap());
                    }
                    break
                }
            }
            // Increaing number should be followed after evaluation
            // To ensure no panick occurs during user_input_on_line, which is caused by
            // out of index exception from getting current line_cache
            #[cfg(feature = "debug")]
            {
                // Increase absolute line number
                self.line_number = self.line_number + 1; 
            }
        } // Loop end

        // Recover
        if let Some(backup) = backup { self.recover(backup); self.sandbox = false; }

        if use_container {
            Ok(cont)
        } else {
            Ok(None)
        }
    }

    // End of process methods
    // </PROCESS>
    // ----------


    // ===========
    // Debug related methods
    // <DEBUG>
    
    /// Check if given macro is local macro or not
    ///
    /// This is used when step debug command is to be executed.
    /// Without chekcing locality, step will go inside local binding macros
    #[cfg(feature = "debug")]
    fn is_local(&self, mut level: usize, name: &str) -> bool {
        while level > 0 {
            if self.map.local.contains_key(&Utils::local_name(level, &name)) {
                return true;
            }
            level = level - 1;
        }
        false
    }

    /// Process breakpoint
    #[cfg(feature = "debug")]
    fn break_point(&mut self, frag: &mut MacroFragment) -> Result<(), RadError> {
        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 == "" {
                        self.debug_switch = DebugSwitch::NextLine;
                    }
                }
                // Clear fragment
                frag.clear();
                return Ok(());
            } 

            self.logger.wlog("Breakpoint in non debug mode")?;
            frag.clear();
        }

        Ok(())
    }

    // Though this implementation is same with user_input_prompt
    // I thought modifying user_input_prompt isn't worth.
    /// Get user input command before processing starts
    #[cfg(feature = "debug")]
    fn user_input_on_start(&mut self) -> Result<(), RadError> {
        // Stop by lines if debug option is lines
        if self.debug {

            let mut log = "Default is next. Ctrl + c to exit.".to_owned();
            let mut prompt = self.current_input.as_str();
            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
                // line
                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, None, &mut log)?;
                prompt = "output";
            }
        }
        Ok(())
    }

    #[cfg(feature = "debug")]
    /// Prompt user input until break condition has been met
    fn user_input_prompt(&mut self, frag: &MacroFragment, initial_prompt: &str) -> Result<(), RadError> {
        let mut do_continue = true;
        let mut log = match &self.debug_switch {
            &DebugSwitch::NextMacro | &DebugSwitch::StepMacro => {
                self.line_caches.get(&self.logger.get_abs_last_line()).unwrap().to_owned()
            }
            _ => {
                self.line_caches.get(&self.line_number).unwrap().to_owned()
            }
        };
        let mut prompt = initial_prompt;
        while do_continue {
            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, Some(frag),&mut log)?;
            prompt = "output";
        }

        Ok(())
    }

    #[cfg(feature = "debug")]
    /// Get user input on line 
    ///
    /// This method should be called before evaluation of a line
    fn user_input_on_line(&mut self,frag: &MacroFragment) -> Result<(), RadError> {
        // 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")?;
        }
        Ok(())
    }

    #[cfg(feature = "debug")]
    /// Get user input before macro execution
    fn user_input_before_macro(&mut self, frag: &MacroFragment) -> Result<(), RadError> {
        // 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")?;
        }
        Ok(())
    }

    // This is possibly loopable
    #[cfg(feature = "debug")]
    /// Get user input after execution
    fn user_input_on_macro(&mut self, frag: &MacroFragment) -> Result<(), RadError> {
        // 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, "macro")?;
        }
        Ok(())
    }

    // This is possibly loopable
    #[cfg(feature = "debug")]
    /// Get user input on execution but also nested macro can be targeted
    fn user_input_on_step(&mut self, frag: &MacroFragment) -> Result<(), RadError> {
        // 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, "step")?;
        }
        Ok(())
    }

    #[cfg(feature = "debug")]
    /// Get user input and evaluates whether loop of input prompt should be breaked or not
    fn parse_debug_command_and_continue(&mut self, command_input: &str, frag: Option<&MacroFragment>, log: &mut String) -> Result<bool, RadError> {
        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 {
                    match command_args.to_lowercase().as_str() {
                        "name" | "n" => {
                           *log = frag.name.to_owned();
                        }
                        "line" | "l" => {
                            match &self.debug_switch{
                                DebugSwitch::StepMacro | DebugSwitch::NextMacro => {
                                    *log = self.logger.get_abs_last_line().to_string();
                                }
                                _ => {
                                    *log = self.line_number.to_string();
                                }
                            } 
                        }
                        "span" | "s" => {
                            let mut line_number = match &self.debug_switch {
                                &DebugSwitch::NextMacro | &DebugSwitch::StepMacro => {
                                    self.logger.get_abs_line()
                                }
                                _ => self.line_number
                            };

                            let mut sums = String::new();
                            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 = line_number - 1;
                            }
                            *log = sums;
                        }
                        "text" | "t" => {
                            match &self.debug_switch{
                                DebugSwitch::StepMacro | DebugSwitch::NextMacro => {
                                    *log = self.line_caches.get(&self.logger.get_abs_last_line()).unwrap().to_owned();
                                }
                                _ => {
                                    *log = self.line_caches.get(&self.line_number).unwrap().to_owned();
                                }
                            } 
                        }
                        "arg" | "a" => {
                            *log = frag.args.to_owned();
                        }
                        _ => {
                            *log = format!("Invalid argument \"{}\"",&command_args);
                        } 
                    } // end inner match
                } // End if let
                else { // No fragment which means it is the start of file
                    return Ok(false);
                }

                // Get user input again
                return Ok(true); 

            } // End print match
            _ => {
                *log = format!("Invalid command : {} {}",command, &command_args);
                return Ok(true);
            },
        } // End Outer match

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

    #[cfg(feature = "debug")]
    /// Bridge function to that waits user's stdin
    pub(crate) fn debug_wait_input(&self, log: &str, prompt: Option<&str>) -> Result<String, RadError> {
        Ok(self.logger.dlog_command(log, prompt)?)
    }
    #[cfg(feature = "debug")]
    /// Bridge function to that prints given log as debug form
    pub(crate) fn debug_print_log(&self,log : &str) -> Result<(), RadError> {
        self.logger.dlog_print(log)?;
        Ok(())
    }

    // </DEBUG>
    // End of debug methods
    // ----------

    // ----------
    // Parse related methods
    // <PARSE>
    /// Parse line is called only by the main loop thus, caller name is special name of @MAIN@
    ///
    /// This parses given input as line by line with an iterator of lines including trailing new
    /// line chracter.
    fn parse_line(&mut self, lines :&mut impl std::iter::Iterator<Item = std::io::Result<String>>, lexor : &mut Lexor ,frag : &mut MacroFragment) -> Result<ParseResult, RadError> {
        self.logger.add_line_number();
        if let Some(line) = lines.next() {
            let line = line?;

            // Save to original
            #[cfg(feature = "debug")]
            if self.yield_diff {
                self.diff_original.as_ref().unwrap().write_all(line.as_bytes())?;
            }

            let remainder = self.parse(lexor, frag, &line, 0, MAIN_CALLER)?;

            // Clear local variable macros
            self.map.clear_local();

            // Non macro string is included
            if remainder.len() != 0 {
                // Fragment is not empty
                if !frag.is_empty() {
                    Ok(ParseResult::FoundMacro(remainder))
                } 
                // Print everything
                else {
                    Ok(ParseResult::Printable(remainder))
                }
            } 
            // Nothing to print
            else {
                Ok(ParseResult::NoPrint)
            }
        } else {
            Ok(ParseResult::EOI)
        }
    } // parse_line end

    /// Parse chunk args by separating it into lines which implements BufRead
    pub(crate) fn parse_chunk_args(&mut self, level: usize, _caller: &str, chunk: &str) -> Result<String, RadError> {
        let mut lexor = Lexor::new();
        let mut frag = MacroFragment::new();
        let mut result = String::new();
        let backup = self.logger.backup_lines();
        self.logger.set_chunk(true);
        for line in Utils::full_lines(chunk.as_bytes()) {
            let line = line?;

            // NOTE
            // Parse's final argument is some kind of legacy of previous logics
            // However it can detect self calling macros in some cases
            // parse_chunk_body needs this caller but, parse_chunk_args doesn't need because
            // this methods only parses arguments thus, infinite loop is unlikely to happen
            result.push_str(&self.parse(&mut lexor, &mut frag, &line, level, "")?);

            self.logger.add_line_number();
        }
        self.logger.set_chunk(false);
        self.logger.recover_lines(backup);
        return Ok(result);
    } // parse_chunk_lines end

    /// Parse chunk body without separating lines
    /// 
    /// In contrast to parse_chunk_lines, parse_chunk doesn't create lines iterator but parses the
    /// chunk as a single entity or line.
    fn parse_chunk_body(&mut self, level: usize, caller: &str, chunk: &str) -> Result<String, RadError> {
        let mut lexor = Lexor::new();
        let mut frag = MacroFragment::new();
        let backup = self.logger.backup_lines();

        // NOTE
        // Parse's final argument is some kind of legacy of previous logics
        // However it can detect self calling macros in some cases
        let result = self.parse(&mut lexor, &mut frag, &chunk, level, caller)?;
        self.logger.recover_lines(backup);
        return Ok(result);
    } // parse_chunk end

    /// Parse a given line
    ///
    /// This calles lexor.lex to validate characters and decides next behaviour
    fn parse(&mut self,lexor: &mut Lexor, frag: &mut MacroFragment, line: &str, level: usize, caller: &str) -> Result<String, RadError> {
        // Initiate values
        // Reset character number
        self.logger.reset_char_number();
        // Local values
        let mut remainder = String::new();

        // Reset lexor's escape_nl 
        lexor.reset_escape();
        for ch in line.chars() {
            self.logger.add_char_number();

            let lex_result = lexor.lex(ch)?;
            // Either add character to remainder or fragments
            match lex_result {
                LexResult::Discard => (),
                LexResult::Ignore => frag.whole_string.push(ch),
                // If given result is literal
                LexResult::Literal(cursor) => {
                    self.lex_branch_literal(ch, frag, &mut remainder, cursor);
                }
                LexResult::StartFrag => {
                    self.lex_branch_start_frag(ch, frag, &mut remainder, lexor)?;
                },
                LexResult::RestartName => {
                    // This restart frags
                    remainder.push_str(&frag.whole_string);
                    frag.clear();
                    frag.whole_string.push('$');
                },
                LexResult::EmptyName => {
                    self.lex_branch_empty_name(ch, frag, &mut remainder, lexor);
                }
                LexResult::AddToRemainder => {
                    self.lex_branch_add_to_remainder(ch, &mut remainder)?;
                }
                LexResult::AddToFrag(cursor) => {
                    self.lex_branch_add_to_frag(ch, frag, cursor);
                }
                LexResult::EndFrag => {
                    self.lex_branch_end_frag(ch,frag,&mut remainder, lexor, level, caller)?;
                }
                // Remove fragment and set to remainder
                LexResult::ExitFrag => {
                    self.lex_branch_exit_frag(ch,frag,&mut remainder);
                }
            }
        } // End Character iteration
        Ok(remainder)
    }

    // Evaluate can be nested deeply
    // Disable caller for temporary
    /// Evaluate detected macro usage
    ///
    /// Evaluation order is followed
    /// - Local bound macro
    /// - Custom macro
    /// - Basic macro
    fn evaluate(&mut self,level: usize, caller: &str, name: &str, raw_args: &str, greedy: bool) -> Result<EvalResult, RadError> {
        let level = level + 1;
        // This parses and processes arguments
        // and macro should be evaluated after
        let args = self.parse_chunk_args(level, name, raw_args)?;

        #[cfg(feature = "debug")]
        if self.debug_log { 
            self.debug_print_log(
                &format!(
                    "Level = \"{}\"{}Name = \"{}\"{}Args = \"{}\"{}",
                    level,
                    LINE_ENDING,
                    name,
                    LINE_ENDING,
                    raw_args,
                    LINE_ENDING,
                )
            )?; 
        }

        // Possibly inifinite loop so warn user
        if caller == name {
            self.log_warning(&format!("Calling self, which is \"{}\", can possibly trigger infinite loop", name))?;
        }

        // Find local macro
        // The macro can be  the one defined in parent macro
        let mut temp_level = level;
        while temp_level > 0 {
            if let Some(local) = self.map.local.get(&Utils::local_name(temp_level, &name)) {
                return Ok(EvalResult::Eval(Some(local.to_owned())));
            } 
            temp_level = temp_level - 1;
        }
        // Find custom macro
        // custom macro comes before basic macro so that
        // user can override it
        if self.map.custom.contains_key(name) {
            if let Some(result) = self.invoke_rule(level, name, &args, greedy)? {
                return Ok(EvalResult::Eval(Some(result)));
            } else {
                return Ok(EvalResult::None);
            }
        }
        // Find basic macro
        else if self.map.basic.contains(&name) {
            // Func always exists, because contains succeeded.
            let func = self.map.basic.get(name).unwrap();
            let final_result = func(&args, greedy, self)?;
            return Ok(EvalResult::Eval(final_result));
        } 
        // Find closure map
        else if self.closure_map.contains(&name) {
            let final_result = self.closure_map.call(name, &args, greedy)?;
            return Ok(EvalResult::Eval(final_result));
        }
        // No macros found to evaluate
        else { 
            return Ok(EvalResult::None);
        }
    }

    /// Invoke a custom rule and get a result
    ///
    /// Invoke rule evaluates body of macro rule because body is not evaluated on register process
    fn invoke_rule(&mut self,level: usize ,name: &str, arg_values: &str, greedy: bool) -> Result<Option<String>, RadError> {
        // Get rule
        // Invoke is called only when key exists, thus unwrap is safe
        let rule = self.map.custom.get(name).unwrap().clone();
        let arg_types = &rule.args;
        let args: Vec<String>;
        // Set variable to local macros
        if let Some(content) = ArgParser::new().args_with_len(arg_values, arg_types.len(), greedy) {
            args = content;
        } else {
            // Necessary arg count is bigger than given arguments
            self.log_error(&format!("{}'s arguments are not sufficient. Given {}, but needs {}", name, ArgParser::new().args_to_vec(arg_values, ',', GreedyState::Never).len(), arg_types.len()))?;
            return Ok(None);
        }

        for (idx, arg_type) in arg_types.iter().enumerate() {
            //Set arg to be substitued
            self.map.new_local(level + 1, arg_type ,&args[idx]);
        }
        // Process the rule body
        let result = self.parse_chunk_body(level, &name, &rule.body)?;

        Ok(Some(result))
    }

    /// Add custom rule to macro map
    ///
    /// This doesn't clear fragment
    fn add_rule(&mut self, frag: &MacroFragment, remainder: &mut String) -> Result<(), RadError> {
        if let Some((name,args,body)) = self.define_parse.parse_define(&frag.args) {

            // Strict mode
            // Overriding is prohibited
            if self.strict && self.map.contains(&name) {
                self.log_error("Can't override exsiting macro on strict mode")?;
                return Err(RadError::StrictPanic);
            }

            self.map.register(&name, &args, &body)?;
        } else {
            self.log_error(&format!(
                    "Failed to register a macro : \"{}\"", 
                    frag.args.split(',').collect::<Vec<&str>>()[0]
            ))?;
            remainder.push_str(&frag.whole_string);
        }
        Ok(())
    }

    /// Write text to either file or standard output according to processor's write option
    fn write_to(&mut self, content: &str, container: &mut Option<String>) -> Result<(), RadError> {
        // Don't try to write empty string, because it's a waste
        if content.len() == 0 { return Ok(()); }

        // Save to container if it has value then return
        if let Some(cont) = container.as_mut() {
            cont.push_str(content);
            return Ok(());
        }

        // Save to "source" file for debuggin
        #[cfg(feature = "debug")]
        if self.yield_diff {
            self.diff_processed.as_ref().unwrap().write_all(content.as_bytes())?;
        }
        // Write out to file or stdout
        if self.redirect {
            self.temp_target.1.write(content.as_bytes())?;
        } else {
            match &mut self.write_option {
                WriteOption::File(f) => f.write_all(content.as_bytes())?,
                WriteOption::Terminal => print!("{}", content),
                WriteOption::Discard => () // Don't print anything
            }
        }

        Ok(())
    }

    // ==========
    // <LEX>
    // Start of lex branch methods
    // These are parse's sub methods for eaiser reading
    fn lex_branch_literal(&mut self, ch: char,frag: &mut MacroFragment, remainder: &mut String, cursor: Cursor) {
        match cursor {
            // Exit frag
            // If literal is given on names
            Cursor::Name => {
                frag.whole_string.push(ch);
                remainder.push_str(&frag.whole_string);
                frag.clear();
            }
            // Simply push if none or arg
            Cursor::None => { remainder.push(ch); }
            Cursor::Arg => { 
                frag.args.push(ch); 
                frag.whole_string.push(ch);
            }
        }
    }

    fn lex_branch_start_frag(&mut self, ch: char,frag: &mut MacroFragment, remainder: &mut String, lexor : &mut Lexor) -> Result<(), RadError> {
        #[cfg(feature = "debug")]
        self.user_input_before_macro(&frag)?;

        frag.whole_string.push(ch);

        // If paused and not pause, then reset lexor context
        if self.paused && frag.name != "pause" {
            lexor.reset();
            remainder.push_str(&frag.whole_string);
            frag.clear();
        }

        Ok(())
    }

    fn lex_branch_empty_name(&mut self, ch: char,frag: &mut MacroFragment, remainder: &mut String, lexor : &mut Lexor) {
        // THis is necessary because whole string should be whole anyway
        frag.whole_string.push(ch);
        // Freeze needed for logging
        self.logger.freeze_number(); 
        // If paused, then reset lexor context to remove cost
        if self.paused {
            lexor.reset();
            remainder.push_str(&frag.whole_string);
            frag.clear();
        }
    }

    fn lex_branch_add_to_remainder(&mut self, ch: char,remainder: &mut String) -> Result<(), RadError> {
        if !self.checker.check(ch) && !self.paused {
            self.logger.freeze_number();
            self.log_warning("Unbalanced parenthesis detected.")?;
        }
        remainder.push(ch);

        Ok(())
    }

    fn lex_branch_add_to_frag(&mut self, ch: char,frag: &mut MacroFragment, cursor: Cursor) {
        match cursor{
            Cursor::Name => {
                if frag.name.len() == 0 {
                    self.logger.freeze_number();
                }
                match ch {
                    '|' => frag.pipe = true,
                    '+' => frag.greedy = true,
                    '*' => frag.yield_literal = true,
                    '^' => frag.trimmed = true,
                    _ => frag.name.push(ch) 
                }
            },
            Cursor::Arg => {
                frag.args.push(ch)
            },
            _ => unreachable!(),
        } 
        frag.whole_string.push(ch);
    }

    fn lex_branch_end_frag(&mut self, ch: char, frag: &mut MacroFragment, remainder: &mut String, lexor : &mut Lexor, level: usize, caller: &str) -> Result<(), RadError> {
        // Push character to whole string anyway
        frag.whole_string.push(ch);

        if frag.name == "define" { // define
            self.lex_branch_end_frag_define(lexor, frag, remainder, level)?;
        } else if self.map.is_keyword(&frag.name) { // Is a keyword
            self.lex_branch_end_keyword(lexor, frag, remainder, level)?;
        } else { // Invoke macro
            self.lex_branch_end_invoke(lexor,frag,remainder, level, caller)?;
        }

        Ok(())
    }

    // Level is necessary for debug feature
    fn lex_branch_end_frag_define(&mut self,lexor: &mut Lexor, frag: &mut MacroFragment, remainder: &mut String, level: usize) -> Result<(), RadError> {
        self.add_rule(frag, remainder)?;
        lexor.escape_next_newline();
        #[cfg(feature = "debug")]
        {
            // If debug switch target is next macro
            // Stop and wait for input
            // Only on main level macro
            if level == 0 { self.user_input_on_macro(&frag)?; }
            else {self.user_input_on_step(&frag)?;}

            // Clear line_caches
            if level == 0 {
                self.line_caches.clear();
            }
        }
        frag.clear();
        Ok(())
    }

    fn lex_branch_end_keyword(&mut self,lexor: &mut Lexor, frag: &mut MacroFragment, remainder: &mut String, level: usize) -> Result<(), RadError> {
        let macro_func = self.map.keyword.get(&frag.name).unwrap();
        let result = macro_func(&frag.args,level,self);

        match result {
            Ok(option) => {
                // Something to print
                if let Some(text) = option {
                    self.write_to(&text,&mut None)?;
                } else { // Nothing to print
                    lexor.escape_next_newline();
                }

                // Clear fragment regardless of success
                frag.clear();
            }
            Err(err) => {
                self.log_error(&format!("{}", err))?;

                // If nopanic then don't panic
                if self.nopanic {
                    // If purge mode is set, don't print anything 
                    if !self.purge {
                        remainder.push_str(&frag.whole_string);
                    } else {
                        // If purge mode
                        // set escape new line 
                        lexor.escape_next_newline();
                    }

                    // Clear fragment regardless of success
                    frag.clear();

                    return Ok(());
                } else {

                    // Clear fragment regardless of success
                    frag.clear();
                    return Err(RadError::Panic);
                }
            }
        }
        Ok(())
    }

    fn lex_branch_end_invoke(&mut self,lexor: &mut Lexor, frag: &mut MacroFragment, remainder: &mut String, level: usize, caller: &str) -> Result<(), RadError> {
        // Name is empty
        if frag.name.len() == 0 {
            self.log_error("Name is empty")?;
            remainder.push_str(&frag.whole_string);
            frag.clear();
            return Ok(());
        }

        // Debug
        #[cfg(feature = "debug")]
        {
            // If debug switch target is break point
            // Set switch to next line.
            self.break_point(frag)?;
            // Break point is true , continue
            if frag.name.len() == 0 {
                lexor.escape_next_newline();
                return Ok(());
            }
        }

        // Try to evaluate
        let evaluation_result = self.evaluate(level, caller, &frag.name, &frag.args, frag.greedy || self.always_greedy);

        match evaluation_result {
            // If panicked, this means unrecoverable error occured.
            Err(error) => {
                self.lex_branch_end_frag_eval_result_error(error)?;
            }
            Ok(eval_variant) => {
                self.lex_branch_end_frag_eval_result_ok(eval_variant,frag,remainder,lexor,level)?;
            }
        }
        // Clear fragment regardless of success
        frag.clear();
        Ok(())
    }

    fn lex_branch_end_frag_eval_result_error(&mut self, error : RadError) -> Result<(), RadError> {
        // this is equlvalent to conceptual if let not pattern
        if let RadError::Panic = error{
            // Do nothing
            ();
        } else {
            self.log_error(&format!("{}", error))?;
        }

        // If nopanic don't panic
        if self.nopanic {
            Ok(())
        } else {
            Err(RadError::Panic)
        }
    }

    // Level is needed for feature debug codes
    fn lex_branch_end_frag_eval_result_ok(&mut self, variant : EvalResult, frag: &mut MacroFragment, remainder: &mut String, lexor : &mut Lexor, level: usize) -> Result<(), RadError> {
        match variant {
            // else it is ok to proceed.
            // thus it is safe to unwrap it
            EvalResult::Eval(content) => {

                // Debug
                // Debug command after macro evaluation
                // This goes to last line and print last line
                #[cfg(feature = "debug")]
                if !self.is_local(level + 1, &frag.name) {
                    // If debug switch target is next macro
                    // Stop and wait for input
                    // Only on main level macro
                    if level == 0 {self.user_input_on_macro(&frag)?;}
                    else {self.user_input_on_step(&frag)?;}

                    // Clear line_caches
                    if level == 0 {
                        self.line_caches.clear();
                    }
                }

                // If content is none
                // Ignore new line after macro evaluation until any character
                if let None = content {
                    lexor.escape_next_newline();
                } else {
                    let mut content = content.unwrap();
                    if frag.trimmed {
                        content = Utils::trim(&content);
                    }
                    if frag.yield_literal {
                        content = format!("\\*{}*\\", content);
                    }
                    // NOTE
                    // This should come later!!
                    if frag.pipe {
                        self.pipe_value = content;
                        lexor.escape_next_newline();
                    } else {
                        remainder.push_str(&content);
                    }
                }
            }
            EvalResult::None =>  { // Failed to invoke
                // because macro doesn't exist

                // If strict mode is set, every error is panic error
                if self.strict {
                    self.log_error(&format!("Failed to invoke a macro : \"{}\"", frag.name))?;
                    return Err(RadError::StrictPanic);
                } 
                // If purge mode is set, don't print anything 
                // and don't print error
                if !self.purge {
                    self.log_error(&format!("Failed to invoke a macro : \"{}\"", frag.name))?;
                    remainder.push_str(&frag.whole_string);
                } else {
                    // If purge mode
                    // set escape new line 
                    lexor.escape_next_newline();
                }
            }
        } // End match

        Ok(())
    }

    fn lex_branch_exit_frag(&mut self,ch: char, frag: &mut MacroFragment, remainder: &mut String) {
        frag.whole_string.push(ch);
        remainder.push_str(&frag.whole_string);
        frag.clear();
    }

    // </LEX>
    // End of lex branch methods
    // ==========
    // </PARSE>
    // End of parse related methods
    // ----------

    // ----------
    // Start of miscellaenous methods
    // <MISC>
    /// Get mutable reference of macro map
    pub(crate) fn get_map(&mut self) -> &mut MacroMap {
        &mut self.map
    }

    /// Bridge method to get auth state
    pub(crate) fn get_auth_state(&self, auth_type : &AuthType) -> AuthState {
        *self.auth_flags.get_state(auth_type)
    }

    /// Change temp file target
    ///
    /// This will create a new temp file if not existent
    pub(crate) fn set_temp_file(&mut self, path: &Path) {
        self.temp_target = (path.to_owned(),OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(path)
            .unwrap());
    }

    /// Turn on sandbox
    ///
    /// This is an explicit state change method for non-processor module's usage
    ///
    /// Sandbox means that current state(cursor) of processor should not be applied for following
    /// independent processing
    pub(crate) fn set_sandbox(&mut self) {
        self.sandbox = true; 
    }

    /// Get temp file's path
    pub(crate) fn get_temp_path(&self) -> &Path {
        self.temp_target.0.as_ref()
    }

    /// Get temp file's "file" struct
    pub(crate) fn get_temp_file(&self) -> &File {
        &self.temp_target.1
    }

    /// Backup information of current file before processing sandboxed input
    fn backup(&self) -> SandboxBackup {
        SandboxBackup { 
            current_input: self.current_input.clone(), 
            local_macro_map: self.map.local.clone(),
            logger_lines: self.logger.backup_lines(),
        }
    }

    /// Recover backup information into the processor
    fn recover(&mut self, backup: SandboxBackup) {
        // NOTE ::: Set file should come first becuase set_file override line number and character number
        self.logger.set_file(&backup.current_input);
        self.current_input = backup.current_input;
        self.map.local= backup.local_macro_map; 
        self.logger.recover_lines(backup.logger_lines);

        // Also recover env values
        self.set_file_env(&self.current_input);
    }

    /// Log error
    pub(crate) fn log_error(&mut self, log : &str) -> Result<(), RadError> {
        self.logger.elog(log)?;
        Ok(())
    }

    /// Log warning
    pub(crate) fn log_warning(&mut self, log : &str) -> Result<(), RadError> {
        self.logger.wlog(log)?;
        Ok(())
    }

    // This is not a backup but fresh set of file information
    /// Set(update) current processing file information
    fn set_file(&mut self, file: &str) -> Result<(), RadError> {
        let path = Path::new(file);
        if !path.exists() {
            Err(RadError::InvalidCommandOption(format!("File, \"{}\" doesn't exist, therefore cannot be read by r4d.", path.display())))
        } else {
            self.current_input = file.to_owned();
            self.logger.set_file(file);
            self.set_file_env(file);
            Ok(())
        }
    }

    /// Set some useful env values
    fn set_file_env(&self, file: &str) {
        let path = Path::new(file);
        std::env::set_var("RAD_FILE", file);
        std::env::set_var("RAD_FILE_DIR", path.parent().unwrap().to_str().unwrap());
    }

    /// Set input as string not as &path
    /// 
    /// This is conceptualy identical to set_file but doesn't validate if given input is existent
    fn set_input(&mut self, input: &str) -> Result<(), RadError> {
        self.current_input = input.to_owned();
        self.logger.set_file(input);
        Ok(())
    }

    // End of miscellaenous methods
    // </MISC>
    // ----------
}

/// Struct for deinition parsing
struct DefineParser{
    arg_cursor :DefineCursor,
    name: String,
    args: String,
    body: String,
    bind: bool,
    container: String,
}

impl DefineParser {
    fn new() -> Self {
        Self {
            arg_cursor : DefineCursor::Name,
            name : String::new(),
            args : String::new(),
            body : String::new(),
            bind : false,
            container : String::new(),
        }
    }

    /// Clear state
    fn clear(&mut self) {
        self.arg_cursor = DefineCursor::Name;
        self.name.clear();
        self.args.clear();
        self.body.clear();
        self.bind = false;
        self.container.clear();
    }

    /// Parse macro definition body
    ///
    /// NOTE: This method expects valid form of macro invocation
    /// which means given value should be presented without outer prentheses
    /// e.g. ) name,a1 a2=body text
    ///
    /// If definition doesn't comply with naming rules or syntaxes, if returnes "None"
    fn parse_define(&mut self, text: &str) -> Option<(String, String, String)> {
        self.clear(); // Start in fresh state
        let mut char_iter = text.chars().peekable();
        while let Some(ch) = char_iter.next() {
            match self.arg_cursor {
                DefineCursor::Name => {
                    if let ParseIgnore::Ignore = self.branch_name(ch) {continue;}
                    // If not valid name return None
                    if !self.is_valid_name(ch) { return None; }
                }
                DefineCursor::Args => {
                    if let ParseIgnore::Ignore = self.branch_args(ch) {continue;}
                    // If not valid name return None
                    if !self.is_valid_name(ch) { return None; }
                }
                // Add everything
                DefineCursor::Body => ()
            } 
            self.container.push(ch);
        }

        // This means pattern such as
        // $define(test,Test) 
        // -> This is not a valid pattern
        if self.args.len() == 0 && !self.bind {
            return None;
        }

        // End of body
        self.body.push_str(&self.container);

        Some((self.name.clone(), self.args.clone(), self.body.clone()))
    }

    /// Check if name complies with naming rule
    fn is_valid_name(&mut self, ch : char) -> bool {
        if self.container.len() == 0 { // Start of string
            // Not alphabetic 
            // $define( 1name ) -> Not valid
            if !ch.is_alphabetic() {
                return false;
            }
        } else { // middle of string
            // Not alphanumeric and not underscore
            // $define( na*1me ) -> Not valid
            // $define( na_1me ) -> Valid
            if !ch.is_alphanumeric() && ch != '_' {
                return false;
            }
        }
        true
    }
    
    // ---------
    // Start of branche methods
    // <DEF_BRANCH>
    
    fn branch_name(&mut self, ch: char) -> ParseIgnore {
        // $define(variable=something)
        // Don't set argument but directly bind variable to body
        if ch == '=' {
            self.name.push_str(&self.container);
            self.container.clear();
            self.arg_cursor = DefineCursor::Body;
            self.bind = true;
            ParseIgnore::Ignore
        } 
        else if Utils::is_blank_char(ch) {
            // This means pattern like this
            // $define( name ) -> name is registered
            // $define( na me ) -> na is ignored and take me instead
            if self.name.len() != 0 {
                self.container.clear();
                ParseIgnore::None
            } else {
                // Ignore
                ParseIgnore::Ignore
            }
        } 
        // Comma go to args
        else if ch == ',' {
            self.name.push_str(&self.container);
            self.container.clear();
            self.arg_cursor = DefineCursor::Args;
            ParseIgnore::Ignore
        } else {
            ParseIgnore::None
        }
    }

    fn branch_args(&mut self, ch: char) -> ParseIgnore {
        // Blank space separates arguments 
        // TODO: Why check name's length? Is it necessary?
        if Utils::is_blank_char(ch) && self.name.len() != 0 {
            if self.container.len() != 0 {
                self.args.push_str(&self.container);
                self.args.push(' ');
                self.container.clear();
            }
            ParseIgnore::Ignore
        } 
        // Go to body
        else if ch == '=' {
            self.args.push_str(&self.container);
            self.container.clear();
            self.arg_cursor = DefineCursor::Body; 
            ParseIgnore::Ignore
        } 
        // Others
        else {
            ParseIgnore::None
        }
    }

    // End of branche methods
    // </DEF_BRANCH>
    // ---------
}

enum DefineCursor {
    Name,
    Args,
    Body,
}

enum ParseIgnore {
    Ignore,
    None
}

/// Macro framgent that processor saves fragmented information of the mcaro invocation
#[derive(Debug)]
struct MacroFragment {
    pub whole_string: String,
    pub name: String,
    pub args: String,

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

impl MacroFragment {
    fn new() -> Self {
        MacroFragment {
            whole_string : String::new(),
            name : String::new(),
            args : String::new(),
            pipe: false,
            greedy: false,
            yield_literal : false,
            trimmed: false,
        }
    }

    /// Reset all state
    fn clear(&mut self) {
        self.whole_string.clear();
        self.name.clear();
        self.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
    fn is_empty(&self) -> bool {
        self.whole_string.len() == 0
    }
}

#[derive(Debug)]
enum ParseResult {
    FoundMacro(String),
    Printable(String),
    NoPrint,
    EOI,
}

/// Struct for backing current file and logging information
///
/// This is necessary because some macro processing should be executed in sandboxed environment.
/// e.g. when include macro is called, outer file's information is not helpful at all.
struct SandboxBackup {
    current_input: String,
    local_macro_map: HashMap<String,String>,
    logger_lines: LoggerLines,
}

enum EvalResult {
    Eval(Option<String>),
    None,
}