This repository has been archived by the owner on Nov 4, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MacroScript.pm
1678 lines (1249 loc) · 52.8 KB
/
MacroScript.pm
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
package Text::MacroScript ; # Documented at the __END__.
require 5.004 ;
use strict ;
use Carp qw( carp croak ) ;
use Cwd ;
use Symbol () ;
use vars qw( $VERSION ) ;
$VERSION = '1.40' ;
### Object fields
# -comment
# -file
# -macro
# -script
# -variable
# -embedded
# -opendelim
# -closedelim
### -which values: -variable -script -macro
### Private class data and methods.
#
# _expand_variable object
# _find_element object
# _insert_element object
# _remove_element object
sub _expand_variable { # Private object method.
my $self = shift ;
my $class = ref( $self ) || $self ;
local $_ = (shift || '') ;
foreach my $var (
sort {
length( $b ) <=> length( $a ) ||
$b cmp $a
} keys %{$self->{VARIABLE}}
) {
s/#\Q$var\E/\$Var{"$var"}/msg ;
}
$_ ;
}
# This is based on the 'binary_string' function, pg 163 of Mastering
# Algorithms with Perl (with the errata).
sub _find_element { # Private object method.
my( $self, $array_name, $target ) = @_ ;
my $class = ref( $self ) || $self ;
my $target_len = length $target ;
my( $low, $high ) = ( 0, scalar @{$self->{$array_name}} ) ;
while( $low < $high ) {
use integer ;
my $index = ( $low + $high ) / 2 ;
my $in_array = $self->{$array_name}->[$index][0] ;
my $in_array_len = length $in_array ;
# Order by longest, then by ASCII.
if( $in_array_len > $target_len or
( $in_array_len == $target_len and
$in_array lt $target ) ) {
$low = $index + 1 ;
}
elsif( $in_array eq $target ) { # This is more efficient than just
$low = $index ; # having the else.
last ;
}
else {
$high = $index ;
}
}
$low ;
}
sub _insert_element { # Private object method.
my( $self, $array_name, $name, $body ) = @_ ;
my $class = ref( $self ) || $self ;
if( $array_name eq 'VARIABLE' ) {
$self->{$array_name}{$name} = $body ;
}
else {
my $index = $self->_find_element( $array_name, $name ) ;
if( $index < @{$self->{$array_name}} and
$self->{$array_name}->[$index][0] eq $name ) {
# Already there so replace $body.
$self->{$array_name}->[$index] = [ $name, $body ] ;
}
else {
# Not there so insert it.
splice( @{$self->{$array_name}}, $index, 0, [ $name, $body ] ) ;
}
}
}
sub _remove_element { # Private object method.
my( $self, $array_name, $name ) = @_ ;
my $class = ref( $self ) || $self ;
my $element = undef ;
if( $array_name eq 'VARIABLE' ) {
$element = delete $self->{$array_name}{$name}
if exists $self->{$array_name}{$name} ;
}
else {
my $index = $self->_find_element( $array_name, $name ) ;
if( $index < @{$self->{$array_name}} and
$self->{$array_name}->[$index][0] eq $name ) {
$element = splice( @{$self->{$array_name}}, $index, 1 ) ;
}
}
$element ;
}
DESTROY { # Object method
; # Noop
}
### Public methods
sub new { # Class and object method
my $self = shift ;
my $class = ref( $self ) || $self ;
# We create a new object from scratch whether called as a class or object
# method.
$self = {
-comment => 0, # Create the %%[] comment macro?
-file => [], # Read macros and scripts from these on creation
-macro => [], # Array of macros in the form [[name=>body],...]
-script => [], # Array of scripts in the form [[name=>body],...]
-variable => [], # Array of variables in the form [[name=>value],...]
-embedded => 0, # If true will create default delims if not given
-opendelim => undef, # Delimiters used if we are working on embedded
-closedelim => undef, # macros
@_
} ;
@{$self->{MACRO}} = () ; # Ordered list to hold the macro definitions
@{$self->{SCRIPT}} = () ; # Ordered list to hold the script definitions
%{$self->{VARIABLE}} = () ; # Hash to hold the users variables
$self->{REMOVE} = 1 ; # Remove definitions from the output; only an
# option for debugging purposes
# `State' temporaries used during processing
$self->{IN_MACRO} = 0 ; # Are we in a multi-line macro definition?
$self->{IN_SCRIPT} = 0 ; # Are we in a multi-line script definition?
$self->{IN_CASE} = 0 ; # Are we in a %CASE block? 0, 'SKIP' or 1.
$self->{IN_EMBEDDED} = 0 ; # Are we in embedded text?
$self->{DEFINE} = '' ; # The multi-line macro or script we're building up
$self->{NAME} = '' ; # The name of the multi-line macro or script
$self->{LINO} = 1 ; # Current line number (for multi-line
# definitions this is always the line number
# of the %DEFINE line)
$self->{OPEN_LEN} = 0 ;
$self->{CLOSE_LEN} = 0 ;
if( $self->{-embedded} or defined $self->{-opendelim} ) {
# We want embedded, but may want default delimiters.
$self->{-opendelim} = "<:" unless $self->{-opendelim} ;
# If the user has just given an opendelim then use it as closedelim
# too.
$self->{-closedelim} = $self->{-opendelim}
if not $self->{-closedelim} and $self->{-opendelim} ne "<:" ;
$self->{-closedelim} = ":>" unless $self->{-closedelim} ;
# We process embedded if we have two delimiters.
$self->{-embedded} = 1 ;
$self->{OPEN_LEN} = length $self->{-opendelim} ;
$self->{CLOSE_LEN} = length $self->{-closedelim} ;
}
bless $self, $class ; # Bless early so we can call methods
eval {
local $_ ;
$self->define( -macro, '%%', '' ) if $self->{-comment} ;
foreach( @{$self->{-file}} ) {
$self->load_file( $_ ) ;
}
foreach( @{$self->{-variable}} ) {
my( $name, $body ) = @{$_} ;
$self->define( -variable, $name, $body ) ;
}
foreach( @{$self->{-macro}} ) {
my( $name, $body ) = @{$_} ;
$self->define( -macro, $name, $body ) ;
}
foreach( @{$self->{-script}} ) {
my( $name, $body ) = @{$_} ;
$self->define( -script, $name, $body ) ;
}
} ;
croak $@ if $@ ;
$self ;
}
sub get { # Object method
my $self = shift ;
my $class = ref( $self ) || $self ;
$self->{shift()} ;
}
# No set - use define instead.
sub define { # Object method.
my( $self, $which, $name, $body ) = @_ ;
my $class = ref( $self ) || $self ;
$self->_insert_element( uc substr( $which, 1 ), $name, $body ) ;
}
sub undefine { # Object method.
my( $self, $which, $name ) = @_ ;
my $class = ref( $self ) || $self ;
$which = uc substr( $which, 1 ) ;
carp "No $which called $name exists" unless
$self->_remove_element( $which, $name ) ;
}
sub list { # Object method.
my( $self, $which, $namesonly ) = @_ ;
my $class = ref( $self ) || $self ;
my @lines ;
local $_ ;
$which = uc substr( $which, 1 ) ;
my $script = '' ;
$script = "_$which" unless $which eq 'MACRO' ;
my $array ;
if( $which eq 'VARIABLE' ) {
$array = [ map { [ $_, $self->{VARIABLE}{$_} ] }
keys %{$self->{VARIABLE}} ] ;
}
else {
$array = $self->{$which} ;
}
foreach( @{$array} ) {
my( $name, $body ) = @{$_} ;
my $line = "%DEFINE$script $name" ;
if( $body =~ /\n/o ) {
$line .= "\n$body%END_DEFINE\n" unless $namesonly ;
}
else {
$line .= " [$body]\n" unless $namesonly ;
}
if( wantarray ) {
push @lines, $line ;
}
else {
print "$line\n" ;
}
}
@lines if wantarray ;
}
sub undefine_all { # Object method.
my( $self, $which ) = @_ ;
my $class = ref( $self ) || $self ;
$which = uc substr( $which, 1 ) ;
if( $which eq 'VARIABLE' ) {
%{$self->{$which}} = () ;
}
else {
@{$self->{$which}} = () ;
}
}
# If we just want to load in a macro file
sub load_file { # Object method.
my( $self, $file ) = @_ ;
my $class = ref( $self ) || $self ;
# Treat loaded files as if wrapped in delimiters (only affects embedded
# processing).
my $in_embedded = $self->{IN_EMBEDDED} ;
$self->{IN_EMBEDDED} = 1 ;
$self->expand_file( $file, -noprint ) ;
$self->{IN_EMBEDDED} = $in_embedded ;
}
# Usage: $macro->expand_file( name, body )
# In an array context will return the file, e.g.
# @expanded = $macro->expand_file( name, body ) ;
# In a void context will print to the current filehandle
sub expand_file { # Object method.
my( $self, $file, $noprint ) = @_ ;
my $class = ref( $self ) || $self ;
# We need this because eval creates a scalar context.
my $wantarray = wantarray ;
my @lines ;
eval {
croak "missing filename" unless $file ;
croak "file `$file' does not exist" unless -e $file ;
substr( $file, 0, 1 ) = ( $ENV{HOME} or $ENV{LOGDIR} or (getpwuid( $> ))[7] )
if substr( $file, 0, 1 ) eq '~' ;
local $_ ;
my $fh = Symbol::gensym ;
open $fh, $file or croak "failed to open $file: $!" ;
while( <$fh> ) {
my $line = $self->{-embedded} ?
$self->expand_embedded( $_, $file ) :
$self->expand( $_, $file ) ;
next unless defined $line and $line ;
if( $wantarray ) {
push @lines, $line ;
}
else {
print $line unless $noprint ;
}
}
close $fh or croak "failed to close $file: $!" ;
if( $self->{IN_MACRO} or $self->{IN_SCRIPT} ) {
my $which = $self->{IN_MACRO} ? 'DEFINE' : 'DEFINE_SCRIPT' ;
croak "runaway \%$which to end of file"
}
} ;
croak $@ if $@ ;
@lines if $wantarray and not $noprint ;
}
sub expand_embedded { # Object method.
my $self = shift ;
my $class = ref( $self ) || $self ;
local $_ = shift ;
my $file = (shift || '-') ;
my $line = '' ;
if( not $self->{IN_EMBEDDED} and /^$self->{-opendelim}$/o ) {
$self->{IN_EMBEDDED} = 1 ;
}
elsif( $self->{IN_EMBEDDED} and /^$self->{-closedelim}$/o ) {
$self->{IN_EMBEDDED} = 0 ;
}
elsif( not $self->{IN_EMBEDDED} ) {
my $pos = index( $_, $self->{-opendelim} ) ;
if( $pos > -1 ) {
$line = substr( $_, 0, $pos ) if $pos > 0 ;
my $start = $pos + $self->{OPEN_LEN} ;
my $end = index( $_, $self->{-closedelim}, $start ) ;
if( $end > -1 ) {
$line .= $self->expand(
substr( $_, $start, $end - $start ), $file ) ;
$line .= $self->expand_embedded(
substr( $_, $end + $self->{CLOSE_LEN} ), $file ) ;
}
else {
$line .= $self->expand( substr( $_, $start ), $file ) ;
$self->{IN_EMBEDDED} = 1 ;
}
}
else {
$line = $_ ;
}
}
else {
my $end = index( $_, $self->{-closedelim} ) ;
if( $end > -1 ) {
$line = $self->expand( substr( $_, 0, $end ), $file ) ;
$self->{IN_EMBEDDED} = 0 ;
$line .= $self->expand_embedded(
substr( $_, $end + $self->{CLOSE_LEN} ), $file ) ;
}
else {
$line = $self->expand( $_, $file ) ;
}
}
$line ;
}
sub expand { # Object method.
my $self = shift ;
my $class = ref( $self ) || $self ;
local $_ = shift ;
my $file = (shift || '-') ;
$self->{LINO} = $. || 1 unless $self->{IN_MACRO} or $self->{IN_SCRIPT} ;
my $where = "at $file line $self->{LINO}" ;
eval {
if( /^\%((?:END_)?CASE)(?:\s*\[(.*?)\])?/mso or
( $self->{IN_CASE} eq 'SKIP' ) ) {
croak "runaway \%DEFINE $where to line $."
if $self->{IN_MACRO} ;
croak "runaway \%DEFINE_SCRIPT $where to line $."
if $self->{IN_SCRIPT} ;
if( defined $1 and $1 eq 'CASE' ) {
croak "no condition for CASE $where" unless defined $2 ;
my $eval = $self->_expand_variable( $2 ) ;
my $result ;
eval {
my %Var = %{$self->{VARIABLE}} ;
local $_ ;
$result = eval $eval ;
%{$self->{VARIABLE}} = %Var ;
} ;
croak "evaluation of CASE $eval failed $where: $@" if $@ ;
$self->{IN_CASE} = $result ? 1 : 'SKIP' ;
}
elsif( defined $1 and $1 eq 'END_CASE' ) {
$self->{IN_CASE} = 0 ;
}
$_ = '' if $self->{REMOVE} ;
}
elsif( ( $self->{IN_MACRO} or $self->{IN_SCRIPT} ) and /^\%END_DEFINE/mso ) {
# End of a multi-line macro or script
$self->{DEFINE} = $self->_expand_variable( $self->{DEFINE} ) ;
my $which = $self->{IN_MACRO} ? 'MACRO' : 'SCRIPT' ;
$self->{"IN_$which"} = 0 ;
$self->_insert_element( $which, $self->{NAME}, $self->{DEFINE} ) ;
$self->{NAME} = $self->{DEFINE} = '' ;
$_ = '' if $self->{REMOVE} ;
}
elsif( $self->{IN_MACRO} or $self->{IN_SCRIPT} ) {
# Accumulating the body of a multi-line macro or script
my $which = $self->{IN_MACRO} ? 'DEFINE' : 'DEFINE_SCRIPT' ;
croak "runaway \%$which $where to line $."
if /^\%
(?:(?:UNDEFINE(?:_ALL)|DEFINE)(?:_SCRIPT|_VARIABLE)?) |
LOAD | INCLUDE | (?:END_)CASE
/msox ;
$self->{DEFINE} .= $_ ;
$_ = '' if $self->{REMOVE} ;
}
elsif( /^\%UNDEFINE(?:_(SCRIPT|VARIABLE))?\s+([^][\s]+)/mso ) {
# Undefining a macro, script or variable
my $which = $1 || 'MACRO' ;
carp "Cannot undefine non-existent $which $2 $where"
unless $self->_remove_element( $which, $2 ) ;
$_ = '' if $self->{REMOVE} ;
}
elsif( /^\%UNDEFINE_ALL(?:_(SCRIPT|VARIABLE))?/mso ) {
# Undefining all macros or scripts
my $which = $1 || 'MACRO' ;
@{$self->{$which}} = () ;
$_ = '' if $self->{REMOVE} ;
}
elsif( /^\%DEFINE(?:_(SCRIPT|VARIABLE))?\s+([^][\s]+)\s*\[(.*?)\]/mso ) {
# Defining a single-line macro, script or variable
my $which = $1 || 'MACRO' ;
$self->_insert_element( $which, $2, $self->_expand_variable( $3 || '' ) ) ;
$_ = '' if $self->{REMOVE} ;
}
elsif( /^\%DEFINE(?:_(SCRIPT))?\s+([^][\s]+)/mso ) {
# Preparing to define a multi-line macro or script (we don't permit
# multi-line variables)
my $which = defined $1 ? 'SCRIPT' : 'MACRO' ;
$self->{NAME} = $2 ;
$self->{DEFINE} = '' ;
$self->{"IN_$which"} = 1 ;
$_ = '' if $self->{REMOVE} ;
}
elsif( /^\%(LOAD|INCLUDE)\s*\[(.+?)\]/mso ) {
# Save state in local stack frame (i.e. recursion is taking care of
# stacking for us)
my $in_macro = $self->{IN_MACRO} ; # Should never be true
my $in_script = $self->{IN_SCRIPT} ; # Should never be true
my $in_case = $self->{IN_CASE} ; # Should never be true
my $define = $self->{DEFINE} ;
my $name = $self->{NAME} ;
my $lino = $self->{LINO} ;
my $in_embedded = $self->{IN_EMBEDDED} ;
my @lines = () ;
# Load in new stuff
if( $1 eq 'LOAD' ) {
# If we are doing embedded processing and we are loading a new
# file then we assume we are still in the embedded text since
# we're loading macros, scripts etc.
carp "Should be embedded when LOADing $2"
if $self->{-embedded} and not $self->{IN_EMBEDDED} ;
# $self->{IN_EMBEDDED} = 1 ; # Should be 1 anyway - this is done
# inside load_file().
# This is a macro/scripts file; instantiates macros and scripts,
# ignores everything else.
$self->load_file( $2 ) ;
}
else {
# If we are doing embedded processing and we are including a new file
# then we assume that we are not in embedded text at the start of that
# file, i.e. we look freshly for an opening delimiter.
carp "Should be embedded when INCLUDINGing $2"
if $self->{-embedded} and not $self->{IN_EMBEDDED} ;
$self->{IN_EMBEDDED} = 0 ; # Should be 1, but we want it off now.
# This is a normal file that may contain macros/scripts - the
# macros and scripts are instantiated and any text is returned
# with all expansions applied
@lines = $self->expand_file( $2 ) ;
}
# Restore state
$self->{IN_MACRO} = $in_macro ;
$self->{IN_SCRIPT} = $in_script ;
$self->{IN_CASE} = $in_case ;
$self->{DEFINE} = $define ;
$self->{NAME} = $name ;
$self->{LINO} = $lino ;
$self->{IN_EMBEDDED} = $in_embedded ;
# Replace string with the outcome of the load (empty) or include
$_ = join '', @lines ;
}
elsif( /^\%REQUIRE\s*\[(.+?)\]/mso ) {
my $file = $1 ;
eval {
require $file ;
} ;
carp "Failed to require `$file': $@" if $@ ;
$_ = '' if $self->{REMOVE} ;
}
else {
# This array is already ordered by length then by ASCII.
foreach my $script ( @{$self->{SCRIPT}} ) {
my( $name, $orig_body ) = @{$script} ;
# We substitute wherever found, including in the middle of 'words'
# or whatever (but we can always create macro names like *MYMACRO
# which are unlikely to occur in words).
# Macro names shouldn't include ] and can't include [.
s{
\Q$name\E
(?:\[(.+?)\])?
}{
# Get any parameters
my @param = split /\|/, $1 if defined $1 ;
# We get $body fresh every time since we could have the same
# macro or script occur more than once in a line but of course
# with different parameters.
my $body = $orig_body ;
# Substitute any parameters in the script's body; we go from
# largest index to smallest to ensure that we substitute #13
# before #1!
if( $body =~ /#\d/mso ) {
$body =~ s/\\#/\x0/msgo ; # Hide escaped #s
# Warnings don't seem to work correctly here so we switch
# them off and do them manually.
local $^W = 0 ;
for( my $i = $#param ; $i >= 0 ; $i-- ) {
$body =~ s/#$i/$param[$i]/msg ;
}
carp "missing parameter or unescaped # in SCRIPT " .
"$name $body $where"
if ( $#param > 9 and $body =~ /#\d\d\D/mso ) or
( $body =~ /#\d\D/mso ) ;
$body =~ s/\x0/#/msgo ; # Unhide escaped #s
# Extra parameters, i.e. those given in the text but not
# used by the macro or script are ignored and do not
# appear in the output.
}
# Evaluate the script
my $result = '' ;
eval {
my @Param = @param ; # Give (local) access to params
my %Var = %{$self->{VARIABLE}} ;
local $_ ;
$result = eval $body ;
%{$self->{VARIABLE}} = %Var ;
} ;
croak "evaluation of SCRIPT $name failed $where: $@"
if $@ ;
# This carp does't work - its supposed to catch a failed eval
# and give an error message - instead perl doesn't set $@ but
# outputs its own error message immediately instead. Although
# we can switch off perl's message using local $^W = 0, doing
# so means that the error goes by silently, so I've left the
# default behaviour so at least we know we've got an error.
# Please let me know how to fix this!
# Return the result of the evaluation as the replacement string
$result ;
}gmsex ;
}
foreach my $macro ( @{$self->{MACRO}} ) {
my( $name, $body ) = @{$macro} ;
s{
\Q$name\E
(?:\[(.+?)\])?
}{
my @param = split /\|/, $1 if defined $1 ;
{
$body =~ s/\\#/\x0/msgo ; # Hide escaped #s
local $^W = 0 ;
for( my $i = $#param ; $i >= 0 ; $i-- ) {
$body =~ s/#$i/$param[$i]/msg ;
}
carp "missing parameter or unescaped # in MACRO " .
"$name $body $where"
if ( $#param > 9 and $body =~ /#\d\d\D/mso ) or
( $body =~ /#\d\D/mso ) ;
$body =~ s/\x0/#/msgo ; # Unhide escaped #s
}
$body ;
}gmsex ;
}
}
} ;
croak $@ if $@ ;
$_ ;
}
1 ;
__END__
=head1 NAME
Text::MacroScript - A macro pre-processor with embedded perl capability
=head1 SYNOPSIS
use Text::MacroScript ;
# new() for macro processing
my $Macro = Text::MacroScript->new ;
while( <> ) {
print $Macro->expand( $_ ) if $_ ;
}
# Canonical use (the filename improves error messages):
my $Macro = Text::MacroScript->new ;
while( <> ) {
print $Macro->expand( $_, $ARGV ) if $_ ;
}
# new() for embedded macro processing
my $Macro = Text::MacroScript->new( -embedded => 1 ) ;
# Delimiters default to <: and :>
# or
my $Macro = Text::MacroScript->new( -opendelim => '[[', -closedelim => ']]' ) ;
while( <> ) {
print $Macro->expand_delimited( $_, $ARGV ) if $_ ;
}
# Create a macro object and create initial macros/scripts from the file(s)
# given:
my $Macro = Text::MacroScript->new(
-file => [ 'local.macro', '~/.macro/global.macro' ]
) ;
# Create a macro object and create initial macros/scripts from the
# definition(s) given:
my $Macro = Text::MacroScript->new(
-macro => [
[ 'MAX_INT' => '32767' ],
],
-script => [
[ 'DHM2S' =>
[
my $s = (#0*24*60*60)+(#1*60*60)+(#2*60) ;
"#0 days, #1 hrs, #2 mins = $s secs"
],
],
-variable => [ '*MARKER*' => 0 ],
) ;
# We may of course use any combination of the options.
my $Macro = Text::MacroScript->new( -comment => 1 ) ; # Create the %%[] macro.
# define()
$Macro->define( -macro, $macroname, $macrobody ) ;
$Macro->define( -script, $scriptname, $scriptbody ) ;
$Macro->define( -variable, $variablename, $variablebody ) ;
# undefine()
$Macro->undefine( -macro, $macroname ) ;
$Macro->undefine( -script, $scriptname ) ;
$Macro->undefine( -variable, $variablename ) ;
# undefine_all()
$Macro->undefine( -macro ) ;
$Macro->undefine( -script ) ;
$Macro->undefine( -variable ) ;
# list()
@macros = $Macro->list( -macro ) ;
@macros = $Macro->list( -macro, -namesonly ) ;
@scripts = $Macro->list( -script ) ;
@scripts = $Macro->list( -script, -namesonly ) ;
@variables = $Macro->list( -variable ) ;
@variables = $Macro->list( -variable, -namesonly ) ;
# load_file() - always treats the contents as within delimiters if we are
# doing embedded processing.
$Macro->load_file( $filename ) ;
# expand_file() - calls expand_embedded() if we are doing embedded
# processing otherwise calls expand().
$Macro->expand_file( $filename ) ;
@expanded = $Macro->expand_file( $filename ) ;
# expand()
$expanded = $Macro->expand( $unexpanded ) ;
$expanded = $Macro->expand( $unexpanded, $filename ) ;
# expand_embedded()
$expanded = $Macro->expand_embedded( $unexpanded ) ;
$expanded = $Macro->expand_embedded( $unexpanded, $filename ) ;
This bundle also includes the C<macro> and C<macrodir> scripts which allows us
to expand macros without having to use/understand C<Text::MacroScript.pm>,
although you will have to learn the handful of macro commands available and
which are documented here and in C<macro>. C<macro> provides more
documentation on the embedded approach.
The C<macroutil.pl> library supplied provides some functions which you may
choose to use in HTML work for example.
=head1 DESCRIPTION
Define macros, scripts and variables in macro files or directly in text files.
Commands may appear in separate macro files which are loaded in either via the
text files they process (e.g. via the C<%LOAD> command), or may be embedded
directly in text files. Almost every command that can appear in a file has an
equivalent object method so that programmers may achieve the same things in
code as can be achieved by macro commands in texts; there are also additional
methods which have no command equivalents.
Most the examples given here use the macro approach. However this module now
directly supports an embedded approach and this is now documented. Although
you may specify your own delimiters where shown in examples we use the default
delimiters of C<E<gt>:> and C<:E<lt>> throughout.
=head2 Public methods
new class object
get class object
define object
undefine object
list object
undefine_all object
load_file object
expand_file object
expand object
expand_embedded object
=head2 Summary of Commands
These commands may appear in separate `macro' files, and/or in the body of
files. Wherever a macroname or scriptname is encountered it will be replaced
by the body of the macro or the result of the evaluation of the script using
any parameters that are given.
Note that if we are using an embedded approach commands, macro names and
script names should appear between delimiters. (Except when we C<%LOAD> since
this assumes the whole file is `embedded'.)
%DEFINE macroname [macro body]
%DEFINE macroname
multi-line
macro body
#0, #1 are the first and second parameters if any used
%END_DEFINE
%UNDEFINE macroname
%UNDEFINE_ALL # Undefine all macros
%DEFINE_SCRIPT scriptname [script body]
%DEFINE_SCRIPT scriptname
multi-line
script body
arbitrary perl
optional parameters are in @Param, although #0, etc may be used
any variables are in %Var, although #varname may be used
%END_DEFINE
%UNDEFINE scriptname
%UNDEFINE_ALL_SCRIPT
%DEFINE_VARIABLE variablename [variable value]
%UNDEFINE variablename
%UNDEFINE_ALL_VARIABLE
%LOAD[path/filename] # Instantiate macros/scripts/variables in this
# file, but discard the text
%INCLUDE[path/filename] # Instantiate macros/scripts/variables in this
# file and output the resultant text
%REQUIRE[path/filename] # Make Perl require a file e.g. of functions,
# modules, etc. which can then be accessed within
# scripts.
%CASE [condition] # Provides #ifdef-type functionality
%END_CASE
Thus, in the body of a file we may have, for example:
%DEFINE &B [Billericky Rickety Builders]
Some arbitrary text.
We are writing to complain to the &B about the shoddy work they did.
If we are taking the embedded approach the example above might become:
<:%DEFINE BB [Billericky Rickety Builders]:>
Some arbitrary text.
We are writing to complain to the <:BB:> about the shoddy work they did.
When using an embedded approach we don't have to make the macro or script name
unique within the text, (although each must be distinct from each other),
since the delimiters are used to signify them. However since expansion applies
recursively it is still wise to make names distinctive.
=head2 Macro systems vs embedded systems
Macro systems read all the text, substituting anything which matches a macro
name with the macro's body (or script name with the result of the execution of
the script). This makes macro systems slower (they have to check for
macro/script names everywhere, not just in a delimited section) and more risky
(if we choose a macro/script name that normally occurs in the text we'll end
up with a mess) than embedded systems. On the other hand because they work on
the whole text not just delimited bits, macro systems can perform processing
that embedded systems can't. Macro systems are used extensively, for example
the CPP, C pre-processor, with its #DEFINE's, etc.
Essentially, embedded systems print all text until they hit an opening
delimiter. They then execute any code up until the closing delimiter. The text
that results replaces everything between and including the delimeters. They
then carry on printing text until they hit an opening delimeter and so on
until they've finished processing all the text. This module now provides both
approaches.
=head2 Creating macro objects with C<new()>
For macro processing:
my $Macro = Text::MacroScript->new ;
For embedded macro processing:
my $Macro = Text::MacroScript->new( -embedded => 1 ) ;
# Delimiters default to <: and :>
Or specify your own delimiters:
my $Macro = Text::MacroScript->new( -opendelim => '[[', -closedelim => ']]' ) ;
Or specify one delimiter to use for both (probably not wise):
my $Macro = Text::MacroScript->new( -opendelim => '%%' ) ;
# -closedelim defaults to -opendelim, e.g. %% in this case
The full list of options that may be specified at object creation:
C<-comment> optional integer; 1 = create the C<%%[]> comment macro; default 0.
C<-file> optional array reference of strings; read macros and scripts from the
file(s) given - they are C<%LOAD>ed so are treated as already embedded if we
are doing embedded processing. Default is a reference to an empty array.
C<-macro> optional array reference of macros, in the form:
my $Macro = Text::MacroScript->new(
-macro => [
["name1"=>"body1"],
["name2"=>"body2"],
["name3"=>"body3"],
],
) ;
Default is a reference to an empty array.
C<-script> optional array reference of scripts, in the form:
my $Macro = Text::MacroScript->new(
-script => [
["name1"=>"body1"],
["name2"=>"body2"],