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
use std::io::{self, Write};
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::path::{ Path , PathBuf};
use crate::error::{RadError, ErrorLogger};
use crate::models::{MacroMap, WriteOption, UnbalancedChecker, MacroRule};
use crate::utils::Utils;
use crate::consts::*;
use crate::lexor::*;
use crate::arg_parser::ArgParser;
#[derive(Debug)]
pub struct MacroFragment {
pub whole_string: String,
pub name: String,
pub args: String,
pub pipe: bool,
pub greedy: bool,
pub preceding: bool,
pub yield_literal : bool,
pub trimmed : bool,
}
impl MacroFragment {
pub fn new() -> Self {
MacroFragment {
whole_string : String::new(),
name : String::new(),
args : String::new(),
pipe: false,
greedy: false,
preceding: false,
yield_literal : false,
trimmed: false,
}
}
pub 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;
}
pub fn is_empty(&self) -> bool {
self.whole_string.len() == 0
}
}
pub enum ParseResult {
FoundMacro(String),
Printable(String),
NoPrint,
EOI,
}
pub struct Processor{
pub map: MacroMap,
define_parse: DefineParser,
write_option: WriteOption,
error_logger: ErrorLogger,
checker: UnbalancedChecker,
line_number: usize,
ch_number: usize,
pub pipe_value: String,
pub newline: String,
pub paused: bool,
pub redirect: bool,
purge: bool,
always_greedy: bool,
temp_target: (PathBuf,File),
}
// 1. Get string
// 2. Parse until macro invocation detected
// 3. Return remainder and macro fragments
// 4. Continue parsing with fragments
impl Processor {
pub fn new(write_option: WriteOption, error_write_option : Option<WriteOption>, newline: String) -> 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());
Self {
map : MacroMap::new(),
write_option,
define_parse: DefineParser::new(),
error_logger: ErrorLogger::new(error_write_option),
checker : UnbalancedChecker::new(),
line_number :0,
ch_number:0,
newline,
pipe_value: String::new(),
paused: false,
redirect: false,
purge: false,
always_greedy: false,
temp_target,
}
}
pub fn print_result(&mut self) -> Result<(), RadError> {
self.error_logger.print_result()?;
Ok(())
}
pub fn set_greedy(&mut self) {
self.always_greedy = true;
}
pub fn set_purge(&mut self) {
self.purge = true;
}
pub fn get_map(&self) -> &MacroMap {
&self.map
}
pub 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());
}
pub fn get_temp_path(&self) -> &Path {
&self.temp_target.0
}
pub fn get_temp_file(&self) -> &File {
&self.temp_target.1
}
pub fn from_stdin(&mut self, get_result: bool) -> Result<String, RadError> {
let stdin = io::stdin();
let mut line_iter = Utils::full_lines(stdin.lock());
let mut lexor = Lexor::new();
let mut invoke = MacroFragment::new();
let mut content = String::new();
let mut container = if get_result { Some(&mut content) } else { None };
loop {
self.line_number = self.line_number + 1;
let result = self.parse_line(&mut line_iter, &mut lexor ,&mut invoke)?;
// Clear local variable macros
self.map.clear_local();
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 container)?;
// Reset fragment
if &invoke.whole_string != "" {
invoke = MacroFragment::new();
}
}
ParseResult::FoundMacro(remainder) => {
self.write_to(&remainder, &mut container)?;
}
ParseResult::NoPrint => (), // Do nothing
// End of input, end loop
ParseResult::EOI => break,
}
} // Loop end
Ok(content)
}
pub fn from_file(&mut self, path :&Path, get_result: bool) -> Result<String, RadError> {
let file_stream = File::open(path)?;
let reader = io::BufReader::new(file_stream);
let mut line_iter = Utils::full_lines(reader);
let mut lexor = Lexor::new();
let mut invoke = MacroFragment::new();
let mut content = String::new();
let mut container = if get_result { Some(&mut content) } else { None };
loop {
self.line_number = self.line_number + 1;
let result = self.parse_line(&mut line_iter, &mut lexor ,&mut invoke)?;
// Clear local variable macros
self.map.clear_local();
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 container)?;
// Reset fragment
if &invoke.whole_string != "" {
invoke = MacroFragment::new();
}
}
ParseResult::FoundMacro(remainder) => {
self.write_to(&remainder, &mut container)?;
}
ParseResult::NoPrint => (), // Do nothing
// End of input, end loop
ParseResult::EOI => break,
}
} // Loop end
Ok(content)
}
/// Parse line is called only by the main loop thus, caller name is special name of @MAIN@
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> {
if let Some(line) = lines.next() {
let line = line?;
let remainder = self.parse(lexor, frag, &line, 0, MAIN_CALLER)?;
// 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 is called by non-main process, thus needs caller
pub fn parse_chunk(&mut self, level: usize, caller: &str, chunk: &str) -> Result<String, RadError> {
let mut lexor = Lexor::new();
let mut frag = MacroFragment::new();
let mut result = self.parse(&mut lexor, &mut frag, chunk, level, caller)?;
if !frag.is_empty() {
result.push_str(&frag.whole_string);
}
return Ok(result);
} // parse_chunk end
fn parse(&mut self,lexor: &mut Lexor, frag: &mut MacroFragment, line: &str, level: usize, caller: &str) -> Result<String, RadError> {
self.ch_number = 0;
// Local values
let mut remainder = String::new();
// Reset lexor's escape_nl
lexor.escape_nl = false;
for ch in line.chars() {
self.ch_number = self.ch_number + 1;
let lex_result = lexor.lex(ch)?;
// Either add character to remainder or fragments
match lex_result {
LexResult::Ignore => frag.whole_string.push(ch),
// If given result is literal
LexResult::Literal(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);
}
}
}
LexResult::StartFrag => {
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();
}
},
LexResult::EmptyName => {
frag.whole_string.push(ch);
self.error_logger
.set_number(
self.line_number,
self.ch_number
);
// If paused, then reset lexor context
if self.paused {
lexor.reset();
remainder.push_str(&frag.whole_string);
frag.clear();
}
}
LexResult::AddToRemainder => {
if !self.checker.check(ch) {
self.error_logger.set_number(self.line_number, self.ch_number);
self.log_warning("Unbalanced parenthesis detected.")?;
}
remainder.push(ch);
}
LexResult::AddToFrag(cursor) => {
match cursor{
Cursor::Name => {
if frag.name.len() == 0 {
self.error_logger
.set_number(
self.line_number,
self.ch_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);
}
// End of fragment
// 1. Evaluate macro
// 1.5 -> If define, parse rule applied again.
// 2. And append to remainder
// 3. Reset fragment
LexResult::EndFrag => {
frag.whole_string.push(ch);
// define
if frag.name == "define" {
self.add_define(frag, &mut remainder)?;
lexor.escape_nl = true;
frag.clear()
}
// Invoke macro
else {
// Try to evaluate
let evaluation_result = self.evaluate(level, caller, &frag.name, &frag.args, frag.greedy || self.always_greedy);
// If panicked, this means unrecoverable error occured.
if let Err(error) = evaluation_result {
// this is equlvalent to conceptual if let not pattern
if let RadError::Panic = error{
// Do nothing
();
} else {
self.log_error(&format!("{}", error))?;
}
return Err(RadError::Panic);
}
// else it is ok to proceed.
// thus it is safe to unwrap it
if let Some(mut content) = evaluation_result.unwrap() {
if frag.pipe {
self.pipe_value = content;
lexor.escape_nl = true;
}
// If content is none
// Ignore new line after macro evaluation until any character
else if content.len() == 0 {
lexor.escape_nl = true;
} else {
if frag.trimmed {
content = Utils::trim(&content)?;
}
if frag.yield_literal {
content = format!("\\*{}*\\", content);
}
remainder.push_str(&content);
}
}
// Failed to invoke
// because macro doesn't exist
else {
// 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_nl = true;
}
}
// Clear fragment regardless of success
frag.clear()
}
}
// Remove fragment and set to remainder
LexResult::ExitFrag => {
frag.whole_string.push(ch);
remainder.push_str(&frag.whole_string);
frag.clear();
}
}
} // End Character iteration
Ok(remainder)
}
fn add_define(&mut self, frag: &mut MacroFragment, remainder: &mut String) -> Result<(), RadError> {
if let Some((name,args,body)) = self.define_parse.parse_define(&frag.args) {
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);
}
// Clear fragment regardless of success
frag.clear();
Ok(())
}
// Evaluate can be nested deeply
// Disable caller for temporary
fn evaluate(&mut self,level: usize, _caller: &str, name: &str, args: &str, greedy: bool) -> Result<Option<String>, RadError> {
let level = level + 1;
// This parses and processes arguments
// and macro should be evaluated after
// TODO
// Make caller to name
let args = self.parse_chunk(level, name, args)?;
// Find local macro
// The macro can be be the macro 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(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(Some(result));
} else {
return Ok(None);
}
}
// Find basic macro
else if self.map.basic.contains(&name) {
let final_result = self.map.basic.clone().call(name, &args, greedy, self)?;
return Ok(Some(final_result));
}
// No macros found to evaluate
else {
return Ok(None);
}
}
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::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, arg_values.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]);
}
// parse the Chunk
let result = self.parse_chunk(level, &name, &rule.body)?;
Ok(Some(result))
}
fn write_to(&mut self, content: &str, container: &mut Option<&mut 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 let Some(container) = container {
container.push_str(content);
}
// Write out to file or stdout
else {
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::Stdout => print!("{}", content),
}
}
}
Ok(())
}
fn log_error(&mut self, log : &str) -> Result<(), RadError> {
self.error_logger.elog(log)?;
Ok(())
}
fn log_warning(&mut self, log : &str) -> Result<(), RadError> {
self.error_logger.wlog(log)?;
Ok(())
}
pub fn set_file(&mut self, file: &str) {
self.error_logger.set_file(file);
self.line_number = 0;
self.ch_number = 0;
}
pub fn add_custom_rules(&mut self, rules: HashMap<String, MacroRule>) {
self.map.custom.extend(rules.into_iter());
}
}
pub struct DefineParser{
arg_cursor :DefineCursor,
name: String,
args: String,
body: String,
dquote: bool,
container: String,
}
impl DefineParser {
pub fn new() -> Self {
Self {
arg_cursor : DefineCursor::Name,
name : String::new(),
args : String::new(),
body : String::new(),
dquote : false,
container : String::new(),
}
}
fn clear(&mut self) {
self.arg_cursor = DefineCursor::Name;
self.name.clear();
self.args.clear();
self.body.clear();
self.dquote = false;
self.container.clear();
}
// Static function
// NOTE This method expects valid form of macro invocation
// Given value should be without outer prentheses
// e.g. ) name,a1 a2,body text
pub fn parse_define(&mut self, text: &str) -> Option<(String, String, String)> {
self.clear();
let mut bind = false;
let mut char_iter = text.chars().peekable();
while let Some(ch) = char_iter.next() {
match self.arg_cursor {
DefineCursor::Name => {
// $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;
bind = true;
continue;
}
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();
} else {
// Ignore
continue;
}
}
// Comma go to args
else if ch == ',' {
self.name.push_str(&self.container);
self.container.clear();
self.arg_cursor = DefineCursor::Args;
continue;
}
else {
// If not valid name return None
if !self.is_valid_name(ch) { return None; }
}
}
DefineCursor::Args => {
// Blank space separates arguments
if Utils::is_blank_char(ch) && self.name.len() != 0 {
self.args.push_str(&self.container);
self.args.push(' ');
self.container.clear();
continue;
}
// Go to body
else if ch == '=' {
self.args.push_str(&self.container);
self.container.clear();
self.arg_cursor = DefineCursor::Body;
continue;
}
// Others
else {
// If not valid name return
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 && !bind {
return None;
}
// End of body
self.body.push_str(&self.container);
Some((self.name.clone(), self.args.clone(), self.body.clone()))
}
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
}
// Reserved for later refactoring
//fn branch_name() {
//}
//fn branch_args() {
//}
//fn branch_body() {
//}
}
enum DefineCursor {
Name,
Args,
Body,
}