forked from pmichaud/pmtcl
/
main.pm
478 lines (408 loc) · 12 KB
/
main.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
our sub after(*@args) {
if +@args < 1 {
error('wrong # args: should be "after option ?arg arg ...?"')
}
pir::sleep__vN(+@args[0] / 1000);
'';
}
our sub append(*@args) {
if +@args < 1 {
error('wrong # args: should be "append varName ?value value ...?"');
}
my $var := @args.shift;
my $lexpad := pir::find_dynamic_lex__Ps('%LEXPAD');
my $result := $lexpad{$var};
while @args {
$result := ~$result ~ @args.shift;
}
set($var, $result);
}
## "break" is special -- see "return"
INIT {
GLOBAL::break := -> $message = '' {
my $exception := pir::new__ps('Exception');
$exception<type> := 66; # TCL_BREAK / CONTROL_LOOP_LAST
pir::throw($exception);
}
}
our sub catch($code, $varname?) {
my $retval := 0; # TCL_OK
my $result;
try {
$result := Partcl::Compiler.eval($code);
CONTROL {
my $parrot_type := $!<type>;
# XXX using numeric type ids is potentially fragile.
if $parrot_type == 58 { # CONTROL_RETURN
$retval := 2; # TCL_RETURN
} elsif $parrot_type == 66 { # CONTROL_LOOP_LAST
$retval := 3; # TCL_BREAK
} elsif $parrot_type == 65 { # CONTROL_LOOP_NEXT
$retval := 4; # TCL_CONTINUE
} elsif $parrot_type == 62 { # CONTROL_ERROR
$retval := 1; # TCL_ERROR
} else {
# This isn't a standard tcl control type. Give up.
pir::rethrow($!);
}
$result := $!<message>;
}
};
if $varname {
my $lexpad := pir::find_dynamic_lex__Ps('%LEXPAD');
$lexpad{$varname} := $result;
}
return $retval;
}
our sub concat(*@args) {
my $result := @args ?? _tcl::string_trim(@args.shift) !! '';
while @args {
$result := $result ~ ' ' ~ _tcl::string_trim(@args.shift);
}
$result;
}
## "continue" is special -- see "return"
INIT {
GLOBAL::continue := -> $message = '' {
my $exception := pir::new__ps('Exception');
$exception<type> := 65; # TCL_CONTINUE / CONTROL_LOOP_NEXT
pir::throw($exception);
}
}
## "error" is special -- see "return"
INIT {
GLOBAL::error := -> $message = '' {
my $exception := pir::new__ps('Exception');
$exception<type> := 62; # CONTROL_ERROR
$exception<message> := $message;
pir::throw($exception);
}
}
our sub eval(*@args) {
if +@args < 1 {
error('wrong # args: should be "eval arg ?arg ...?"');
}
my $code := concat(|@args);
our %EVALCACHE;
my &sub := %EVALCACHE{$code};
unless pir::defined__IP(&sub) {
&sub := Partcl::Compiler.compile($code);
%EVALCACHE{$code} := ⊂
}
&sub();
}
our sub exit(*@args) {
if +@args > 1 {
error('wrong # args: should be "exit ?returnCode?"');
}
my $code := @args[0] // 0;
pir::exit__vi($code);
}
our sub expr(*@args) {
my $code := pir::join(' ', @args);
if $code ne '' {
our %EXPRCACHE;
my &sub := %EXPRCACHE{$code};
unless pir::defined__IP(&sub) {
my $parse :=
Partcl::Grammar.parse(
$code,
:rule('TOP_expr'),
:actions(Partcl::Actions)
);
&sub := PAST::Compiler.compile($parse.ast);
%EXPRCACHE{$code} := ⊂
}
&sub();
} else {
error("empty expression\nin expression \"\"");
}
}
our sub for(*@args) {
if +@args != 4 {
error('wrong # args: should be "for start test next command"');
}
my $init := @args[0];
my $cond := @args[1];
my $incr := @args[2];
my $body := @args[3];
eval($init);
while expr($cond) {
eval($body);
eval($incr);
}
'';
}
our sub if(*@args) {
while @args {
my $expr := @args.shift;
my $body := @args.shift;
$body := @args.shift if $body eq 'then';
if expr($expr) { return eval($body); }
if @args {
my $else := @args.shift;
if $else ne 'elseif' {
$else := @args.shift if $else eq 'else';
return eval($else);
}
}
}
'';
}
our sub incr (*@args) {
if +@args < 1 || +@args > 2 {
error('wrong # args: should be "incr varName ?increment?"');
}
my $lexpad := pir::find_dynamic_lex__Ps('%LEXPAD');
my $var := @args[0];
my $val := @args[1];
return set($var, pir::add__Nnn($lexpad{$var}, $val // 1));
}
our sub join(*@args) {
if +@args < 1 || +@args > 2 {
error('wrong # args: should be "join list ?joinString?"');
}
my $list := @args[0];
my $joinString := @args[1];
my @list :=
Partcl::Grammar.parse($list, :rule<list>, :actions(Partcl::Actions) ).ast // pir::new__Ps('TclList');
$joinString := " " unless pir::defined($joinString);
pir::join($joinString, @list);
}
our sub global (*@args) {
our %GLOBALS;
## my %CUR_LEXPAD := DYNAMIC::<%LEXPAD>
my %CUR_LEXPAD := pir::find_dynamic_lex__Ps('%LEXPAD');
for @args {
%CUR_LEXPAD{$_} := %GLOBALS{$_};
}
'';
}
our sub list(*@args) {
return @args;
}
our sub lindex($list, $pos) {
my @list :=
Partcl::Grammar.parse($list, :rule<list>, :actions(Partcl::Actions) ).ast;
return @list[$pos];
}
our sub llength(*@args) {
if +@args != 1 {
error('wrong # args: should be "llength list"')
}
my @list :=
Partcl::Grammar.parse(@args[0], :rule<list>, :actions(Partcl::Actions) ).ast;
return +@list;
}
our sub proc(*@args) {
if +@args != 3 {
error('wrong # args: should be "proc name args body"');
}
my $name := @args[0];
my $args := @args[1];
my $body := @args[2];
my $parse :=
Partcl::Grammar.parse( $body, :rule<TOP_proc>, :actions(Partcl::Actions) );
my $block := $parse.ast;
my @params :=
Partcl::Grammar.parse($args, :rule<list>, :actions(Partcl::Actions) ).ast;
for @params {
my @argument :=
Partcl::Grammar.parse($_, :rule<list>, :actions(Partcl::Actions) ).ast;
if +@argument == 1 {
$block[0].push(
PAST::Op.new( :pasttype<bind>,
PAST::Var.new( :scope<keyed>,
PAST::Var.new( :name('lexpad'), :scope<register> ),
$_
),
PAST::Var.new( :scope<parameter> )
)
);
} elsif +@argument == 2 {
$block[0].push(
PAST::Op.new( :pasttype<bind>,
PAST::Var.new( :scope<keyed>,
PAST::Var.new( :name('lexpad'), :scope<register> ),
@argument[0]
),
PAST::Var.new(
:scope<parameter>,
:viviself(PAST::Val.new( :value(@argument[1]) ))
)
)
);
}
}
$block.name($name);
$block.control('return_pir');
PAST::Compiler.compile($block);
'';
}
our sub puts(*@args) {
my $nl := 1;
if @args[0] eq '-nonewline' {
@args.shift; $nl := 0;
}
if @args[0] eq 'stdout' { @args.shift }
if @args[0] eq 'stderr' {
@args.shift;
pir::printerr(@args[0]);
pir::printerr("\n") if $nl;
} else {
pir::print(@args[0]);
pir::print("\n") if $nl;
}
'';
}
our sub regexp(*@args) {
if +@args <2 {
error('wrong # args: should be "regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?"')
}
my $exp := @args.shift();
my $string := @args.shift();
## my &dumper := Q:PIR { %r = get_root_global ['parrot'], '_dumper' };
## &dumper(ARE::Compiler.compile($exp, :target<parse>));
my $regex := ARE::Compiler.compile($exp);
?Regex::Cursor.parse($string, :rule($regex), :c(0));
}
## "return" is special -- we want to be able to throw a
## CONTROL_RETURN exception without the sub itself catching
## it. So we create a bare block for the return (bare blocks
## don't catch return exceptions) and bind it manually into
## the (global) namespace when loaded.
INIT {
GLOBAL::return := -> $result = '' { return $result; }
}
our sub set($varname, $value?) {
my $var :=
Q:PIR {
.local pmc varname, lexpad
varname = find_lex '$varname'
lexpad = find_dynamic_lex '%LEXPAD'
%r = vivify lexpad, varname, ['Undef']
};
pir::copy__0PP($var, $value) if pir::defined($value);
$var;
}
our sub source($filename) {
Partcl::Compiler.evalfiles($filename);
}
our sub split(*@args) {
if +@args < 1 || +@args > 2 {
error('wrong # args: should be "split string ?splitChars?"')
}
my $string := ~@args[0];
my $splitChars := @args[1] // " \r\n\t";
if $string eq '' {
return '';
}
if $splitChars eq '' {
return pir::split__Pss('',$string);
}
my @result;
my $element := '';
for $string -> $char {
my $active := 1;
for $splitChars -> $sc {
if $active {
if $char eq $sc {
@result.push($element);
$element := '';
$active := 0;
}
}
}
if $active {
$element := $element ~ $char;
}
};
@result.push($element);
@result := list(|@result); # convert to a TclList
return @result;
}
our sub switch ($string, *@args) {
unless @args {
pir::printerr("wrong # args: should be ``switch ?switches? string pattern body ... ?default body?''");
return;
}
if +@args % 2 == 1 {
pir::printerr("extra switch pattern with no body");
return;
}
while @args {
my $pat := @args.shift;
my $body := @args.shift;
if $string eq $pat || (+@args == 0 && $pat eq 'default') {
eval($body);
last;
}
}
}
our sub time(*@args) {
if +@args < 1 || +@args > 2 {
error('wrong # args: should be "time command ?count?"');
}
my $command := @args[0];
my $count;
if +@args == 2 {
$count := +@args[1];
} else {
$count := 1;
}
if $count == 0 {
return '0 microseconds per iteration';
}
my $start := pir::time__N();
my $loop := pir::set__IP($count);
while $loop {
eval($command);
$loop--;
}
my $end := pir::time__N();
my $ms_per := pir::set__IP(($end-$start)*1000000 / $count);
return $ms_per ~ ' microseconds per iteration';
}
our sub unset($varname) {
Q:PIR {
$P1 = find_lex '$varname'
$P2 = find_dynamic_lex '%LEXPAD'
delete $P2[$P1]
}
}
our sub uplevel($level, *@args) {
## my %LEXPAD := DYNAMIC::<%LEXPAD>
my %LEXPAD := pir::find_dynamic_lex__Ps('%LEXPAD');
## 0x23 == '#'
if pir::ord($level) == 0x23 {
$level := %LEXPAD.depth - pir::substr($level, 1);
}
## walk up the chain of outer contexts
while $level > 0 {
%LEXPAD := %LEXPAD.outer;
$level := $level - 1;
}
## now evaluate @args in the current context
my $code := concat(|@args);
Partcl::Compiler.eval($code);
}
our sub while (*@args) {
if +@args != 2 {
error('wrong # args: should be "while test command"');
}
my $cond := @args[0];
my $body := @args[1];
while expr($cond) {
eval($body);
}
}
## EXPAND is a helper sub for {*} argument expansion; it probably
## doesn't belong in the global namespace but this is a convenient
## place to test it for now. It takes a string and splits it up
## into a list of elements, honoring braces and backslash
## expansion (similar to the Tcl_SplitList function). The actual
## parsing and expansion is handled by the <list> token in
## Partcl::Grammar .
our sub EXPAND($args) {
Partcl::Grammar.parse($args, :rule<list>, :actions(Partcl::Actions) ).ast;
}