forked from pmichaud/pmtcl
/
main.pm
876 lines (757 loc) · 21 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
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
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 $result := set($var);
while @args {
$result := ~$result ~ @args.shift;
}
set($var, $result);
}
our sub apply(*@args) {
return '';
}
our sub binary(*@args) {
}
## "break" is special -- see "return"
INIT {
GLOBAL::break := -> *@args {
if +@args {
error('wrong # args: should be "break"');
}
my $exception := pir::new__ps('Exception');
$exception<type> := 66; # TCL_BREAK / CONTROL_LOOP_LAST
pir::throw($exception);
}
}
our sub catch(*@args) {
if +@args < 1 || +@args > 2 {
error('wrong # args: should be "catch script ?resultVarName? ?optionVarName?"');
}
my $code := @args[0];
my $retval := 0; # TCL_OK
my $result;
try {
$result := Partcl::Compiler.eval($code);
CATCH {
$retval := 1; # TCL_ERROR
$result := $!<message>;
}
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
} else {
# This isn't a standard tcl control type. Give up.
pir::rethrow($!);
}
$result := $!<message>;
}
};
if +@args == 2 {
set(@args[1], $result);
}
return $retval;
}
# TODO: implement ~user syntax
our sub cd(*@args) {
if +@args > 1 {
error('wrong # args: should be "cd ?dirName?"');
}
my $dir;
if @args == 1 {
$dir := @args[0];
} else {
$dir := pir::new__ps('Env'){'HOME'};
}
my $OS := pir::new__ps('OS');
$OS.chdir($dir);
}
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);
}
}
our sub eof(*@args) {
if +@args != 1 {
error('wrong # args: should be "eof channelId"')
}
my $chan := _getChannel(@args[0]);
return 0;
}
## "error" is special -- see "return"
INIT {
GLOBAL::error := -> *@args {
my $message := '';
if +@args < 1 || +@args > 3 {
$message := 'wrong # args: should be "error message ?errorInfo? ?errorCode?"';
} else {
$message := @args[0];
}
if +@args >= 2 {
our %GLOBALS;
%GLOBALS{'errorInfo'} := @args[1];
my $errorCode := @args[2] // 'NONE';
%GLOBALS{'errorCode'} := $errorCode;
}
my $exception := pir::new__ps('Exception');
# use EXCEPTION_SYNTAX_ERROR - just a generic type
$exception<type> := 56;
$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 fileevent(*@args) {
}
our sub flush(*@args) {
if +@args != 1 {
error('wrong # args: should be "flush channelId"');
}
my $ioObj := _getChannel(@args[0]);
if pir::can__ips($ioObj, 'flush') {
$ioObj.flush();
}
return '';
}
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);
my $loop := 1;
while $loop && expr($cond) {
eval($body);
eval($incr);
CONTROL {
if $!<type> == 65 { # CONTROL_LOOP_NEXT
eval($incr);
} elsif $!<type> == 66 { # CONTROL_LOOP_LAST
$loop := 0;
}
}
}
'';
}
# TODO: do this correctly! This is a very naive implementation.
our sub foreach(*@args) {
if +@args == 0 || +@args % 2 == 0 {
error('wrong # args: should be "foreach varList list ?varList list ...? command"');
}
my $var := @args[0];
my @list := split(@args[1],' ');
my $body := @args.pop; # Body is always last
for @list -> $val {
set($var,$val);
eval($body);
}
}
our sub format(*@args) {
}
our sub gets(*@args) {
}
our sub glob(*@args) {
my $dir := ".";
while @args[0] ne '--' && pir::substr(@args[0],0,1) eq '-' {
my $opt := @args.shift;
$dir := @args.shift if $opt eq '-directory';
}
my @files := pir::new__ps('OS').readdir($dir);
my @globs;
for @args -> $pat {
@globs.push( FileGlob::Compiler.compile($pat) );
}
my @retval := pir::new__ps('TclList');
for @files -> $f {
my $matched := 0;
for @globs -> $g {
$matched := 1 if ?Regex::Cursor.parse($f, :rule($g), :c(0));
}
@retval.push($f) if $matched;
}
return @retval;
}
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 if(*@args) {
# while @args {
Q:PIR {
if_loop:
$P0 = find_lex '@args'
unless $P0 goto if_done
};
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);
}
}
# }
Q:PIR {
goto if_loop
if_done:
};
'';
}
our sub incr (*@args) {
if +@args < 1 || +@args > 2 {
error('wrong # args: should be "incr varName ?increment?"');
}
my $var := @args[0];
my $val := @args[1];
# incr auto-vivifies
try {
set($var);
CATCH {
set($var,0);
}
}
return set($var, pir::add__Iii(set($var), $val // 1));
}
our sub join(*@args) {
if +@args < 1 || +@args > 2 {
error('wrong # args: should be "join list ?joinString?"');
}
pir::join(@args[1] // " ", @args[0].getList());
}
our sub lappend(*@args) {
if +@args < 1 {
error('wrong # args: should be "lappend varName ?value value ...?"');
}
my $var := @args.shift();
my @list;
# lappend auto-vivifies
try {
@list := set($var);
CATCH {
@list := set($var, pir::new__ps('TclList'));
}
}
@list := @list.getList();
for @args -> $elem {
@list.push($elem);
}
return set($var,@list);
}
our sub lassign(*@args) {
if +@args < 2 {
error('wrong # args: should be "lassign list varName ?varName ...?"');
}
my @list := @args.shift().getList();
my $listLen := +@list;
my $pos := 0;
for @args -> $var {
if $pos < $listLen {
set($var, @list.shift());
} else {
set($var,'');
}
$pos++;
}
return @list;
}
our sub linsert(*@args) {
if +@args < 2 {
error('wrong # args: should be "linsert list index element ?element ...?"')
}
my @list := @args.shift().getList();
#if user says 'end', make sure we use the end (imagine one element list)
my $oIndex := @args.shift();
my $index := @list.getIndex($oIndex);
if pir::substr__ssii($oIndex,0,3) eq 'end' {
$index++;
} else {
if $index > +@list { $index := +@list; }
if $index < 0 { $index := 0;}
}
pir::splice__vppii(@list, @args, $index, 0);
return @list;
}
our sub list(*@args) {
return @args;
}
our sub lindex(*@args) {
if +@args < 1 {
error('wrong # args: should be "lindex list ?index...?"');
}
my $list := @args.shift();
my @indices;
if +@args == 0 {
return $list;
} elsif +@args == 1 {
@indices := Partcl::Grammar.parse(
@args[0], :rule<list>, :actions(Partcl::Actions)
).ast;
} else {
@indices := @args;
}
my $result := $list;
while (@indices) {
$result :=
Partcl::Grammar.parse($result, :rule<list>, :actions(Partcl::Actions) ).ast;
my $index := $result.getIndex(@indices.shift()); # not a TclList?
my $size := +$result;
if $index < 0 || $index >= $size {
$result := '';
} else {
$result := $result[$index];
}
}
return $result;
}
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 lrange(*@args) {
if +@args != 3 {
error('wrong # args: should be "lrange list first last"')
}
my @list := @args[0].getList();
my $from := @list.getIndex(@args[1]);
my $to := @list.getIndex(@args[2]);
if $from < 0 { $from := 0}
my $listLen := +@list;
if $to > $listLen { $to := $listLen - 1 }
my @retval := pir::new__ps('TclList');
while $from <= $to {
@retval.push(@list[$from]);
$from++;
}
return @retval;
}
our sub lrepeat(*@args) {
if +@args < 2 {
error('wrong # args: should be "lrepeat positiveCount value ?value ...?"');
}
my $count := @args.shift.getInteger();
if $count < 1 {
error('must have a count of at least 1');
}
my @result := pir::new__ps('TclList');
while $count {
for @args -> $elem {
@result.push($elem);
}
$count--;
}
return @result;
}
our sub lreplace(*@args) {
if +@args < 3 {
error('wrong # args: should be "lreplace list first last ?element element ...?"');
}
my @list := pir::clone__pp(@args.shift().getList());
my $first := @list.getIndex(@args.shift());
my $last := @list.getIndex(@args.shift());
if +@list == 0 {
pir::splice__vppii(@list, @args, 0, 0);
return @list;
}
$last := +@list -1 if $last >= +@list;
$first := 0 if $first < 0;
if $first >= +@list {
error("list doesn't contain element $first");
}
my $count := $last - $first + 1;
if $count >= 0 {
pir::splice__vppii(@list, @args, $first, $count);
return @list;
}
pir::splice__vppii(@list, @args, $first, 0);
return @list;
}
our sub lreverse(*@args) {
if +@args != 1 {
error('wrong # args: should be "lreverse list"');
}
return @args[0].getList().reverse();
}
sub dumper($what, $label = 'VAR1') {
pir::load_bytecode('dumper.pbc');
my &dumper := Q:PIR {
%r = get_root_global ['parrot'], '_dumper'
};
&dumper($what, $label);
}
our sub lset(*@args) {
if +@args < 2 {
error('wrong # args: should be "lset listVar index ?index...? value"');
}
my $name := @args.shift;
my $value := @args.pop;
my $original_list := set($name); # Error if $name not found - don't viv
if @args == 0
|| (@args == 1 && @args[0].getList == 0) {
set($name, $value);
}
else {
if pir::isa__ips($original_list, 'String') {
$original_list := pir::box__ps($original_list);
}
my @result := pir::clone__pp($original_list).getList;
my @sublist := @result;
my @previous;
my $index;
for @args -> $arg {
@previous := @sublist;
$index := @previous.getIndex: $arg;
if $index < 0 || $index >= @previous {
error('list index out of range');
}
if pir::typeof__sp(@previous[$index]) eq 'String' {
@previous[$index] := pir::box__ps(@previous[$index]);
}
@previous[$index] := @sublist := @previous[$index].getList;
}
@previous[$index] := $value;
set($name, @result);
}
}
our sub lsort(*@args) {
return '';
}
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 pwd () {
return pir::new__ps('OS').'cwd'();
}
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));
}
our sub rename(*@args) {
if +@args != 2 {
error('wrong # args: should be "rename oldName newName"');
}
}
## "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(*@args) {
if +@args < 1 || +@args > 2 {
error('wrong # args: should be "set varName ?newValue?"');
}
my $varname := @args[0];
my $var :=
Q:PIR {
.local pmc varname, lexpad
varname = find_lex '$varname'
lexpad = find_dynamic_lex '%LEXPAD'
%r = vivify lexpad, varname, ['Undef']
};
my $value := @args[1];
if pir::defined($value) {
pir::copy__0PP($var, $value)
} elsif ! pir::defined($var) {
error("can't read \"$varname\": no such variable");
}
return $var;
}
our sub socket(*@args) {
}
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 subst(*@args) {
}
our sub switch(*@args) {
if +@args < 3 {
error('wrong # args: should be "switch ?switches? string pattern body ... ?default body?"');
}
my $regex := 0;
my $glob := 0;
my $nocase := 0;
while @args[0] ne '--' && pir::substr(@args[0],0,1) eq '-' {
my $opt := @args.shift;
$regex := 1 if $opt eq '-regex';
$glob := 1 if $opt eq '-glob';
$nocase := 1 if $opt eq '-nocase';
}
my $string := @args.shift();
if +@args % 2 == 1 {
error('extra switch pattern with no body');
}
while @args {
my $pat := @args.shift;
my $body := @args.shift;
if $nocase {
$pat := pir::downcase($pat);
$string := pir::downcase($string);
}
my $cmp := $string eq $pat;
if $regex {
my $re := ARE::Compiler.compile($pat);
$cmp := ?Regex::Cursor.parse($string, :rule($re), :c(0));
}
if $glob {
my $globber := StringGlob::Compiler.compile($pat);
$cmp := ?Regex::Cursor.parse($string, :rule($globber), :c(0));
}
if $cmp || (+@args == 0 && $pat eq 'default') {
return eval($body);
}
}
}
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 := pir::set__iP(@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(*@args) {
for @args -> $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 upvar(*@args) {
}
our sub variable(*@args) {
}
our sub vwait(*@args) {
}
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;
}
# vim: filetype=perl6: