r4d 3.1.0

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
# TOC

* [Macro definition]#macro-definition
  * [Caveats]#caveats
* [Macro invocation]#macro-invocation
* [Literal rules]#literal-rules
* [Comments]#comments
* [Macro attributes]#macro-attributes
* [Errors]#errors
* [Break point]#break-point

## Macro definition

Definition syntax is similar to macro invocation but requires a specific form
to sucessfully register the macro.

```
$define(name,arg1 arg2=$arg1() $arg2())
        |    |         |
Arg:    1st  2nd       3rd
```
**First argument** (Before first comma)

First argument is a macro name. Macro should start with an alphabet character
and following characters should be either alphanumeric or underscore.

**Second argument** (Before equal sign)

Second argument is macro's arguments. Macro argument also follows same rule
of naming. Multiple arguments can be declared and should be **separated by
whitespaces.**

**Third argument** (After equal sign)

Third argument is a macro body. Any text can be included in the macro body
while an unbalanced parenthesis will prematurely. Currently there is no way to
include unbalanced parenthesis inside definition body.

You can also simply bind the value without giving arguments. Which is mostly
similar to static macro. But defined body is always evaluated.

```
$define(v_name=Simon creek)
% Which is same with
$static(v_name,Simon creek)
```

### Caveats

**Define is not evaluated on declaration**

Definition's body can include any macro invocation in itself, but wrong macro
use inside definition cannot be detected at the time of definition. By other
terms, defined macro is evaluated lazily.

```
$define(panik,kalm=$calm())
$panik()
$define(calm=KALM)
$panik()
===
error: Failed to invoke a macro : "calm"
 --> stdin:2:2
$calm()
KALM
% After calm is defined, it prints out without error
```

You can check some easy mistakes with ```dryrun``` flag. Dryrun flag audits
simple errors on macro declaration.

```
% Ran with rad --dryrun
$define(panik,kalm=$calm())
$define(bonk=$fout(path.txt))
===
warning: Invalid macro name
= No such macro name : "calm"
 --> [INPUT = test]:1:2 >> (MACRO = panik):1:2
warning: Invalid macro name
= No such macro name : "fout"
 --> [INPUT = test]:1:2 >> (MACRO = bonk):1:2
warning: found 2 warnings
```

**Define is evaluated on every call**

Because defined macro is evaluated on every invocation. This may not be a
desired behaviour. Use static macro if you want statically bound value. Static
macro eagerly evaluates arguments and assigns the processed value to a macro.

```
$define(counter=0)
$define(print_counter=$counter())
$static(print_counter_as_static,$counter())
$append(counter,0000)
$print_counter()
$print_counter_as_static()
===
00000
0
```

Also, static macro is not evaluated on invocation thus a "static". Most of time
it doesn't matter. But theoretically static macro is faster than defined
macro.

## Macro invocation

Prefix is a dollar sign($)
```
$define(macro_name,a1 a2=$a1() $a2())
$macro_name(arg1, arg2)
```
Macro can be invoked anywhere after the definition.
```
My name is $macro_name(Simon, Creek).
```
converts to
```
My name is Simon Creek.
```

Special macro ```$:()``` is used for iterated value.
```
$foreach^(Name : $:()$nl(),John,Simon,Jane)
$forloop^($:()th$nl(),5,10)
```
converts to
```
Name : John
Name : Simon
Name : Jane
5th
6th
7th
8th
9th
10th
```

**NOTE**

An unbalanced parenthesis changes the behaviour of macro invocation and a
non-escaped comma will change the number or content of arguments. If desirable
content includes unbalanced parentheses or commas, enclose the body with string
literal with the syntax of ```\* TEXT GOES HERE *\```.

## Literal quotes

### Abstract

Texts within literal quote ```\*  *\``` will not be expanded or treated as a
macro syntax. Literal quote makes code fuzzy, sadly, but it is frequently used
to give an array as a single chunk of argument. Literal quote was made to evade
confusions as much as possible so the syntax has exotic expression on intent. (
Unlike regular expressions like simple quotes or double quotes )

**Simple usage of literal quote**

```
% Although in this case, prefer arguments order of "value" and then "array" so
% that parser can greedily aggregates surplus commas as second arguments
$define(get_array_n_value,a_arr a_src=$foreach($:() $a_src()$nl(),$a_arr()))
$get_array_n_value^(\*1,2,3*\,-)
===
1 -
2 -
3 -
```

What would happen if array was given without literal quote?

```
$define(get_array_n_value,a_arr a_src=
$logm(a_arr)
$logm(a_src)
$foreach($:() $a_src()$nl(),$a_arr()))
$get_array_n_value^(1,2,3,-)
===
% Console output
% log: 1
%  --> test:6:2
% log: 2,3,-
%  --> test:8:2
1 2,3,-
```

The result text is not what one would expect. Because parser thought first
argument "1" was for ```a_arr``` and remainder for ```a_src```.

### Literal expansion rules

Literal rules in r4d is unfortunately not straightforward at a first glance.
General rules are followings

- Literal text inside definition body is not stripped on execution
- Literal text as an argument is expanded and then stripped
    - Arguments with only constants is treated as if it were not quoted
    - Arguments with macro will not expand macro and return it as if it were
    normal text

In short, rad processes macros in given subprocesses.

- Expand expression from arguments
- Strip expanded arguments
- Split arguments according to macro's arguments
- Bind arguments to local macros
- Expand a macro body

See an examples to better understand literal rules

### Macro body

```r4d
$define(test=\*$path(a,b)*\)
$test()
===
% Macro body is not stripped
\*$path(a,b)*\
```

### Literl inside arguments

**Literal arguments without macros**

```r4d
$static(p1,$path(\*a*\,b,c))
$static(p2,$path(a,b,c))
$assert($p1(),$p2())
===
% This holds true because \*a*\ is stripped to be a value of "a"
% Thus path macro can process argument as if it was originally a "a,b,c"
```

**Literal arguments with macros**

```
$static(p,a/b)
$static(p1,$path(\*$p()*\,b,c))
$static(p2,$path($p(),b,c))
$logm(p1)
$logm(p2)
$assert($p1(),$p2())
===
% p1's argument was stripped but not expanded
% log: $p()/b/c
%  --> test:4:2
%
% log: a/b/b/c
%  --> test:5:2
% This holds anyway because assert has expanded each values
% Thus final result of p1 and p2 is same to end user
```

**Literal passed as nested arguments**

```
$define(demo,a_first=$if($a_first(),TRUE))
$demo($not(false))
$demo(\*$not(false)*\)
===
TRUE
error: Invalid argument
= If requires either true/false or zero/nonzero integer but given "$not(false)"
 --> test:3:2~~
```

If an argument is passed as literal, local argument will be linked to stripped
but non-expanded value. which is ```$not(false)``` in this case. Since **local
argument is not expanded**, if receives strange value and execution fails.

To prevent this error, minimize literal usage if possible. When passing array,
use literal quote only when the values are constants. If you need to create a
dynamically created array, wrap it inside a macro and use literal attribute.

```r4d
$define=(
    arr_pass,
    a_arr a_it
    =
    $foreach=(
        $:() + $a_it()$nl(),
        $a_arr()
    )
)
$static(array,a,b,c,d,e,f,g)
$arr_pass^($array*(),@)

% This is same with
% $arr_pass^(\*a,b,c,d,e,f,g*\,@)
===
a + @
b + @
c + @
d + @
e + @
f + @
g + @
```

Simple process how this works

- **arr_pass**
    - Expand $array() -> ```a,b,c,d,e,f,g```
    - Try stripping, but nothing to do anyway
    - Wrap it inside literal (attirbute) -> ```\* a,b,c,d,e,f,g *\```
    - Bind the wrapped value to an argument ```a_arr```
- **foreach**
    - Expand $a_arr() -> ```\* a,b,c,d,e,f,g *\```
    - Strip a value -> ```a,b,c,d,e,f,g```
    - Bind the value to an argument ```a_body``` ( Refer --man foreach )

## Comments

Comment is disabled by default because a comment character can intefere with
macro expansion and user expectance. You can enable comment mode with
```--comment``` flag.

There are three types of comment mode. Those are none,start and any. None is
the default and ```--comment``` is same with ```--comment start```.
And finally ```--comment any``` enables comments for any positions.

Default comment character is ```%```. If you have used LaTex before, it would
be familar. This can be configured with builder method.

```
% This is a valid comment on both start and any mode
    % Nested comment is better for reading in some cases
Prior content goes here  % This is only valid comment on "any" mode.
```

### Macro attributes

**Trim output**

Trim output attribute ```^``` trims preceding and following newlines,
whitespaces from output.

```
$define(
    test
    =
    Hello
    World
)
$test()
$test^()
===

        Hello
        World

Hello
        World
```

One important feature of trim output attribute is that it **converts empty
string into None**. You can refer why such feature is special in a
[doc](./newline_rules.md)

Therefore following example works

```
$define(none_if_empty=$ifdefel(test,DEFINED,$empty()))
$none_if_empty^() % => "None"
$define(test=)
$none_if_empty()  % => DEFINED
===
DEFINED
```

**Trim input**

Trim input attribute ```=``` trims macro arguments by lines and also trim by
chunk. This is useful when you want to use a multiline complex text as
arguments but surplus blank spaces are unnecessary. Trim inputs power is mostly
centered on single argument macros but other situations are also plausible.

Trim input can be applied to define macro and trimming will be applied to macro
body.

```
% Needs trim output to remove newline that comes before "hello world"
$ifenv^=(HOME,
    hello world
    How are you?
    I'm fine, thanks. How's it going?
    yatti yatta
)
===
hello world
How are you?
I'm fine, thanks. How's it going?
yatti yatta
```

Since "trim input" trims input not arguments, trimmed input can be different
from expectation.

e.g)
```
$macro_name=(
    first,
    second
)
===
% Arguments are passed as
% first
%
% second
```

**Pipe output**

Pipe output attribute ```|``` saves macro output into a temporary container.
This is useful when you use hygiene mode and needs a persistent container that
is not volatile. Or simply you are just tired of defining container everytime
you want to use. ( Though I recommend using named macro container for code
readability )

```
$define(test,a=$a())
$test|(I'm going to be used by a pipe macro)
$trim($repeat(2,$-()
))
$test|(\*I'll be requoted with literal*\)
$-*()
===
I'm going to be used by a pipe macro
I'm going to be used by a pipe macro
\*I'll be requoted with literal*\
```

CAVEAT

Getting value from pipe truncates an original value.

```
$eval|("test" == "test")
$define(result=$-())
$result()
% This time result will print nothing
$result()
===
true

```

**Pipe input**

Pipe input attribute sets argument as piped value. This also truncates pipe
value. Piped input is not expanded.

```
$define(mac,a_src=+$a_src())
$mac|(1)
$mac|-()
$mac|-()
$mac-()
===
+++1
```

**Yield literal**

Yield literal attribute ```*``` makes output printed as literal form. This is
useful when you have to give an argument literal value but you need to pre
process the data which means it cannot be marked as literal. In other words you
can send dynamic content as quoted with help of yield literal attribute. Use
yield literal when you manipulate complex texts that can possibly include
unbalanced parenthesis or commas.

Refer about [literal quotes](#literal-rules) to grasp possible usages.

**Negate result**

You can negate a result with ```!``` attribute. On strict mode, if the result
is not a boolean-able, processor panicks.

```
$is_empty($empty())
$is_empty!($empty())
===
true
false
```

### Errors

Every error is panicking by default(strict mode), to make programs more stable
and expectable or because I'm too rusty person. You can disable strict mode
with lenient option ```-l or --lenient``` or puge option ```-p or --purge```.

Refer [modes](./modes.md) document for detailed error behaviours

### Break point

```BR``` is reserved for debugging usage. You cannot override breakpoint.

```
$BR()
```

### Escape blanks

```EB``` is reserved for blank escape opeartion. After ```EB``` is invoked
every blank spaces are escaped.

```r4d
BEFORE$EB()


AFTER
===
BEFOREAFTER
```