/
Compiler.pm
345 lines (299 loc) · 9.3 KB
/
Compiler.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
package WebTek::Compiler;
# max demmelbauer
# 12-03-08
#
# compiles webtek-templates into perlcode with the following rules
#
# Terminale:
# ==========
# CHAR -> .
# EQUAL -> =
# UNEVAL -> ~
# DOT -> \.
# PIPE -> \|
# ESCAPE -> \\
# QUOTE_START -> " | ' | q\{ | q\[ | q\(
# QUOTE_END -> " | ' | \} | \] | \)
# SPACE -> \s+
# NAME -> \w+
# MACRO_START -> <%
# MACRO_END -> %>
#
# NonTerminale:
# =============
# Template -> ( Macro | CHAR )*
# Macro -> MACRO_START
# SPACE
# NAME ( DOT NAME )*
# ( Param )*
# ( PIPE SPACE NAME ( Param )* )*
# SPACE
# MACRO_END
# Param -> NAME EQUAL QUOTE_START Template QUOTE_END
# |
# NAME UNEVAL QUOTE_START ( CHAR )* QUOTE_END
use strict;
use WebTek::Util qw( assert );
my $String;
my $LineNo;
my $CharNo;
my $Handler;
my @QuoteEnd;
# --------------------------------------------------------------------------
# terminal symbols
# --------------------------------------------------------------------------
sub CHAR { '.' }
sub EQUAL { '=' }
sub UNEVAL { '~' }
sub SPACE { '\s+' }
sub NAME { '\w+' }
sub MACRO_START { '<%' }
sub MACRO_END { '%>' }
sub DOT { '\.' }
sub PIPE { '\|' }
sub ESCAPE { '\\' }
sub QUOTES { {
'"' => '"',
"'" => "'",
"q{" => '\}',
"q[" => '\]',
"q(" => '\)',
} }
sub QUOTE_START { '(\'|"|q\{|q\[|q\()' }
sub QUOTE_END { $QuoteEnd[$#QuoteEnd] }
# --------------------------------------------------------------------------
# public methods
# --------------------------------------------------------------------------
sub compile {
my $class = shift;
$Handler = shift;
my $string = shift;
#... compile code
my $handler = ref $Handler && $Handler;
my $cache_key = WebTek::Cache::key('compiler', $handler, $string);
my $code = WebTek::Cache::cache()->get($cache_key);
unless ($code) {
$code = to_perl($class->parse($string));
WebTek::Cache::cache()->set($cache_key, $code);
}
#... eval code
my $compiled = eval "sub { my (\$handler, \$params) = \@_; return $code }";
assert $compiled, "cannot compile code: $code, details: $@";
return $compiled;
}
sub parse {
my $class = shift;
$String = shift;
$LineNo = 1;
$CharNo = 0;
@QuoteEnd = ();
return template();
}
# --------------------------------------------------------------------------
# utils
# --------------------------------------------------------------------------
sub syntax_error {
my $msg = $_[0] && ": $_[0]";
die "syntax_error at line $LineNo, char $CharNo$msg\n";
}
sub macro_error {
my $msg = $_[0] && ": $_[0]";
die "macro_error $msg\n";
}
sub quote_start { # finds the coresponding quote end-tag
my $left = shift;
push @QuoteEnd, QUOTES->{$left};
}
sub quote_end { pop @QuoteEnd }
sub compact { # compact ['a','b','c',{},] to ['abc',{}]
my $array = shift;
my $compact = undef;
my @compact = ();
foreach my $item (@$array) {
if (ref $item) {
push @compact, $compact if defined $compact;
push @compact, $item;
$compact = undef;
} else {
$compact .= $item;
}
}
push @compact, $compact if defined $compact;
return \@compact;
}
sub to_perl { # converts an array (from the template method) to perlcode
my $array = shift;
my @code;
foreach my $item (@$array) {
if (ref $item) {
if ($item->{'type'} eq 'macro') {
my ($name, %params, @filters);
#... process params
foreach my $key (keys %{$item->{'params'}}) {
$params{$key} = to_perl($item->{'params'}->{$key});
}
#... extract params: if,unless,prefix,suffix,failmode,default
my ($if, $unless, $prefix, $suffix, $failmode, $default) =
delete @params{qw( if unless prefix suffix failmode default )};
my $silent = ($failmode eq '"silent"');
#... process name
my ($macro, @handlers) = reverse split /\./, $item->{'name'};
if ($handlers[-1] eq 'param') {
shift @handlers;
my $get = join ".", (reverse(@handlers), $macro);
#$macro = "\$params->get('$get')";
$macro = "\$params->{'$macro'}";
} else {
my $h = join "", map "->_handler('$_')", reverse @handlers;
my $p = join ",", map "'$_'=>$params{$_}", keys %params;
$macro = "\$handler$h->_macro('$macro', {$p})";
}
#... process filters
foreach my $filter (@{$item->{'filters'}}) {
my ($f, @handlers) = reverse split /\./, $filter->{'name'};
my $h = join "", map "->_handler('$_')", reverse @handlers;
my %p;
foreach my $key (keys %{$filter->{'params'}}) {
$p{$key} = to_perl($filter->{'params'}->{$key});
}
my $p = join ",", map "'$_'=>$p{$_}", keys %p;
$macro = "\$handler$h->_filter('$f', $macro, {$p})";
}
#... composite special params
my $util = "WebTek::Compiler::Util";
$macro = "$util\::default($macro, $default)" if defined $default;
if ($prefix or $suffix) {
$prefix ||= "''";
$suffix ||= "''";
$macro = "$util\::prefix_suffix($macro, $prefix, $suffix)";
}
$macro = "( $if ? $macro : undef )" if defined $if;
$macro = "( $unless ? undef : $macro )" if defined $unless;
$macro = "( eval { $macro } || undef )" if $silent;
push @code, $macro;
}
} else {
$item =~ s/\\/\\\\/g;
$item =~ s/"/\\"/g;
$item =~ s/\n/\\n/g;
$item =~ s/\r/\\r/g;
$item =~ s/\t/\\t/g;
$item =~ s/\$/\\\$/g;
$item =~ s/\@/\\\@/g;
push @code, "\"$item\"";
}
}
return @code ? join(" . ", @code) : "''";
}
# --------------------------------------------------------------------------
# scanner
# --------------------------------------------------------------------------
sub lookahead { $String =~ /^$_[0]/s ? 1 : undef }
sub match {
#... check for a syntax error
unless (&lookahead) {
my $string = substr $String, 0, index $String, "\n";
syntax_error("expected $_[0] but found '$string'");
}
#... do the match
$String =~ s/^($_[0])//s;
my $match = $1;
#... update line-number
my $start = 0;
while ($start = index($match, "\n", $start) + 1) {
$LineNo++;
$CharNo = 0;
}
#... update char-number
my $length = length $match;
my $newline = rindex $match, "\n";
$CharNo += $newline ne -1 ? $length - $newline : $length;
#... return match
return $match;
}
# --------------------------------------------------------------------------
# parser
# --------------------------------------------------------------------------
sub template {
my $tpl = [];
while (defined( my $part = macro() || lookahead(CHAR) && match(CHAR) )) {
push @$tpl, $part;
}
return compact($tpl);
}
sub macro {
#... check for an macro
return undef unless lookahead(MACRO_START);
my $line_number = $LineNo;
#... match marco-start
match(MACRO_START);
match(SPACE);
#... match name
my $name = match(NAME);
while (lookahead(DOT)) { $name .= match(DOT) . match(NAME) }
#... match params
match(SPACE);
my $params = {};
while ( my @param = param() ) { $params = { %$params, @param } }
#... match filters
my $filters = [];
while ( lookahead(PIPE) ) {
match(PIPE);
match(SPACE);
my $f_name = match(NAME);
my $f_params = {};
match(SPACE);
while ( my @param = param() ) { $f_params = { %$f_params, @param } }
push @$filters, { 'name' => $f_name, 'params' => $f_params };
}
#... match macro-end
match(MACRO_END);
#... return hash representing the macro
return {
'type' => 'macro',
'name' => $name,
'params' => $params,
'filters' => $filters,
'line_number' => $line_number,
};
}
sub param {
return () unless lookahead(NAME);
my $name = match(NAME);
my $type = lookahead(UNEVAL) ? match(UNEVAL) : match(EQUAL);
quote_start(match(QUOTE_START));
my $value = value($type);
quote_end(match(QUOTE_END));
match(SPACE);
return $name => $value;
}
sub value {
my $type = shift;
my $escape = 0;
my $value = [];
while (not lookahead(QUOTE_END) or $escape) {
my $part = ($type eq EQUAL)
? macro() || lookahead(CHAR) && match(CHAR)
: lookahead(CHAR) && match(CHAR);
if (defined $part) {
pop @$value if $part eq QUOTE_END;
push @$value, $part;
$escape = $part eq ESCAPE;
} else {
my $end = QUOTE_END;
$end =~ s/\\//g;
syntax_error("cannot find quote end char '$end'");
}
}
return compact($value);
}
package WebTek::Compiler::Util;
sub default {
my ($string, $default) = @_;
return length $string ? $string : $default;
}
sub prefix_suffix {
my ($string, $prefix, $suffix) = @_;
return length $string ? $prefix . $string . $suffix : $string;
}
1;