This repository has been archived by the owner on Jun 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udeck.pl
executable file
·6499 lines (4842 loc) · 172 KB
/
udeck.pl
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
#!/usr/bin/perl
# Copyright (C) 2010-2012 Chris Reuter; GPLv2+Exception; No Warranty.
# The turtle lives 'twixt plated decks
# Which practically conceal its sex.
# I think it clever of the turtle
# In such a fix to be so fertile.
# -- Ogden Nash
# This is an initial implementation of the Deck programming language.
#
# Note that this source code violates a number of guidelines for
# writing good Perl code. While this was done for good (IMHO)
# reasons, it means that this program should not be considered an
# example of how to write clean, maintainable Perl code. For that, I
# strongly recommend reading Damien Conway's book "Perl Best
# Practices".
use strict;
use warnings;
use feature "switch";
# Forward-declare NIL as an alias for LL::Nil::NIL.
sub NIL {return LL::Nil::NIL()}
# ---------------------------------------------------------------------------
package LL::Name;
# NEVER SET THIS VARIABLE. Instead, use 'local' to create a localized
# version and modify that.
our $Namespace = 'Main';
sub IsQualified {
my ($name) = @_;
return $name =~ /\:\:/;
}
sub Normalize {
my ($name) = @_;
# Sanity check!
die "Undefined argument to Normalize().\n" unless defined($name);
die "Normalize: Expecting string, not reference!\n"
unless ref($name) eq '';
return $name if IsQualified($name);
return $Namespace . '::' . $name;
}
# Split a name into ($namespace, $name) pairs
sub SplitName {
my ($name) = @_;
my @np = split (/::/, $name);
my $namePart = pop @np;
my $namespacePart = join ("::", @np);
return ($namespacePart, $namePart);
}
# Test if $name is a member of namespace $namespace. If $name is
# unqualified, the answer is always false.
sub IsMemberOf {
my ($name, $namespace) = @_;
return 0 unless IsQualified($name);
my ($ns, $nm) = SplitName($name);
return 1 if $namespace eq $ns;
}
# Test if $name is legally accessible from the current namespace
# (assuming it exists, that is). Basically, it is either public or
# it's private but to the current namespace.
sub IsLegallyAccessible {
my ($name) = @_;
return 1 unless IsQualified($name);
my ($ns, $namePart) = SplitName($name);
return 1 if $ns eq $Namespace;
return 1 unless $namePart =~ /^_/;
return 0;
}
# ---------------------------------------------------------------------------
package LL::GlobalContext;
sub new {
my ($class) = @_;
return bless {
# Reserved fields:
' namespaces' => {}, # The set of declared namespaces
' imported symbols' => {}, # The set of names that are imports
' forward decls' => {}, # The set of forward proc decl'ns
' consts' => {}, # <- list of const names
}, $class;
}
sub _chkns {
my ($self, $ns) = @_;
die "Undefined namespace '$ns'\n"
unless defined($self->{' namespaces'}->{$ns});
}
# Ensure $name is a valid Deck variable
sub checkName {
my ($self, $name) = @_;
(LL::Symbol->new($name))->checkValidName(" as variable name.");
}
sub names {
my ($self) = @_;
return grep { $_ !~ /^ / } keys %{$self};
}
sub present {
my ($self, $name) = @_;
$name = LL::Name::Normalize($name);
return exists($self->{$name});
}
# Test for the presence of $name without qualifying the name
sub presentAsIs {
my ($self, $name) = @_;
exists($self->{$name}) and return 1;
return 0;
}
sub lookup {
my ($self, $name) = @_;
$name = LL::Name::Normalize($name);
exists($self->{$name}) and return $self->{$name};
die "Unknown variable: '$name'\n"; # not reached.
}
sub isConst {
my ($self, $name) = @_;
$name = LL::Name::Normalize($name);
exists($self->{$name}) and return !! $self->{' consts'}->{$name};
die "Unknown variable: '$name'\n"; # not reached.
}
sub defNamespace {
my ($self, $ns) = @_;
$self->checkName($ns);
$self->{' namespaces'}->{$ns} = 1;
}
# Create the subnamespace in the macro namespace ('__') for $name.
sub ensureMacroNamespace {
my ($self, $name) = @_;
$name = '__::' . LL::Name::Normalize($name);
my ($ns) = LL::Name::SplitName($name);
$self->defNamespace($ns);
}
sub hasNamespace {
my ($self, $ns) = @_;
return exists($self->{' namespaces'}->{$ns});
}
sub def {
my ($self, $name) = @_;
die "def: Expecting string, not reference!\n" unless ref($name) eq '';
$name = LL::Name::Normalize($name);
$self->checkName($name);
$self->checkScopeFor($name);
die "Redefinition of name '$name'.\n"
if exists($self->{$name});
return $self->{$name} = main::NIL;
}
sub set {
my ($self, $name, $value) = @_;
die "set: Expecting string, not reference!\n" unless ref($name) eq '';
$name = LL::Name::Normalize($name);
die "Attempted to modify a const: $name.\n"
if defined($self->{' consts'}->{$name});
exists($self->{$name}) and do {
$self->{$name} = $value;
return $value;
};
fail ("Unknown variable: '$name'\n"); # not reached
}
sub defset {
my ($self, $name, $value) = @_;
$self->def($name);
$self->set($name, $value);
return $value;
}
sub defsetconst {
my ($self, $name, $value) = @_;
$name = LL::Name::Normalize($name);
$self->defset($name, $value);
$self->{' consts'}->{$name} = 1;
return $value;
}
# Modifies a const. Not something that user code should ever do.
sub setGlobalConst {
my ($self, $name, $value) = @_;
$name = LL::Name::Normalize($name);
die "setGlobalConst called on a non-const name '$name'\n"
unless defined($self->{' consts'}->{$name});
delete($self->{' consts'}->{$name});
$self->set($name, $value);
$self->{' consts'}->{$name} = 1;
return $value;
}
# Ensure $name is valid for this context
sub checkScopeFor {
my ($self, $name) = @_;
# We allow qualified names here but the namespace must be declared.
my ($namespace, $baseName) = LL::Name::SplitName($name);
$self->_chkns($namespace);
return 1;
}
# Copy all public names in namespace $src to namespace $dest
sub importPublic {
my ($self, $src, $dest, $withNames, $withoutNames, $renameNames) = @_;
$self->_chkns($src);
$self->_chkns($dest);
my @srcNames = ();
foreach my $key (keys %{$self}) {
next if $key =~ /^\s/; # Skip internal variables
# Skip existing imports
next if defined($self->{' imported symbols'}->{$key});
my ($namespace, $name) = LL::Name::SplitName($key);
next unless $namespace eq $src;
next if $name =~ /^_/;
my $newVar = "${dest}::${name}";
if ($withNames) {
next unless exists($withNames->{$name});
$newVar = "${dest}::" . $withNames->{$name};
} elsif ($withoutNames) {
next if exists($withoutNames->{$name});
} elsif ($renameNames && defined($renameNames->{$name})) {
$newVar = "${dest}::" . $renameNames->{$name};
}
die "Importing name '$key' into '$dest' as '$newVar' overwrites existing " .
"name.\n"
if exists($self->{$newVar});
$self->defsetconst($newVar, $self->{"${src}::${name}"});
$self->{' imported symbols'}->{$newVar} = 1;
}
return;
}
# Add a forward declaration to the list
sub addForward {
my ($self, $name, $args) = @_;
$args ||= 1; # Ensure $args is a true value.
$name = LL::Name::Normalize($name);
die "Forward declaration on undefined name '$name'\n"
unless defined($self->{$name});
$self->{' forward decls'}->{$name} = $args;
}
sub getForward {
my ($self, $name) = @_;
return $self->{' forward decls'}->{$name};
}
# Return the arg. list for $name if it is an mproc (i.e. defined with
# an arg. list); undef otherwise.
sub mprocForwardArgs {
my ($self, $name) = @_;
my $list = $self->{' forward decls'}->{$name};
return unless defined($list);
return $list;
}
# Clear all decl's in the given namespace (defaults to current) and
# return the list of deleted names.
sub clearForwards {
my ($self) = @_;
my $namespace = $LL::Name::Namespace;
my @forwards = ();
for my $forward (keys %{$self->{' forward decls'}}) {
next unless $forward =~ /^${namespace}\:\:/;
push @forwards, $forward;
delete($self->{' forward decls'}->{$forward});
}
return @forwards;
}
# ---------------------------------------------------------------------------
package LL::ContextId;
# Instances don't need to do anything except be unique and instances
# of LL::ContextId.
sub new {
my ($class) = @_;
return bless {}, $class;
}
# ---------------------------------------------------------------------------
package LL::CompileState;
use Data::Dumper;
sub new {
my ($class, $desc, $isVararg, $parent, $prefix, $isGlobal, $isClass,
$namespace) = @_;
# If there's no parent, we default to the global namespace
if (!$parent && !$isGlobal) {
$parent = LL::CompileState->new($desc, 0, undef, "", 1, 0);
}
my $self =
{names => {},
args => [],
tempCount => 0,
parent => $parent,
isGlobal => $isGlobal,
isVararg => $isVararg,
desc => $desc,
indent => ($parent && $parent->{indent}) || 0,
hasDynSub => 0,
isClass => $isClass,
varPrefix => $prefix,
namespace => $namespace,
};
return bless $self, $class;
}
# Create an instance from field lists. This gets used to recreate
#sub newFrom {
# my ($class, $parent, $args, $vars, $isGlobal) = @_;
#}
sub desc {my ($self) = @_; return $self->{desc}}
sub isVararg {my ($self) = @_; return $self->{isVararg}}
sub args {my ($self) = @_; return [ @{$self->{args}} ]}
sub names {my ($self) = @_; return [ sort keys %{$self->{names}} ]}
sub namespace{my ($self) = @_; return $self->{namespace} }
sub hasDynSub {my ($self) = @_; return $self->{hasDynSub}}
sub foundDynSub {
my ($self) = @_;
return $self->{hasDynSub} = 1;
}
sub indent {my ($self) = @_; return ' ' x $self->{indent} };
sub indentBy {
my ($self, $num) = @_;
$self->{indent} += $num;
}
sub localDeclVarNames {
my ($self) = @_;
my %names = %{ $self->{names} };
for my $arg (@{ $self->{args} }) {
delete $names{$arg};
}
return [sort keys %names];
}
sub addRef {
my ($self, $name, $defIndex, $isConst, $isInstVar) = @_;
$self->{names}->{$name} = [$defIndex, $isConst, $isInstVar || 0];
}
sub addClass {
my ($self, $class) = @_;
for my $name ($class->names()) {
$self->addRef($name, -1, $class->isConst($name), 1);
}
}
sub addArgRef {
my ($self, $name, $isConst) = @_;
push @{$self->{args}}, $name;
$self->addRef($name, -1, $isConst);
}
sub hasRef {
my ($self, $name) = @_;
return defined($self->{names}->{$name});
}
sub isConst {
my ($self, $name) = @_;
return $self->_getRef($name)->[1];
}
sub _getRef {
my ($self, $name) = @_;
defined($self->{names}->{$name}) and return $self->{names}->{$name};
defined($self->{parent}) and return $self->{parent}->_getRef($name);
return unless $LL::Main::Globals->present($name);
return [-1, $LL::Main::Globals->isConst($name), 0];
}
sub isUndefined {
my ($self, $name) = @_;
# Ensure that $name is legal in the current namespace. Should only
# do anything in the global namespace.
return 1 if !LL::Name::IsLegallyAccessible($name);
return !$self->_getRef($name);
}
sub lookupExpr {
my ($self, $name) = @_;
# Ensure that $name is legal in the current namespace (global only!)
return undef unless LL::Name::IsLegallyAccessible($name);
# If this represents a global context, check the global namespace.
if ($self->{isGlobal}) {
my $normName = LL::Name::Normalize($name);
my $expr = "\$LL::Main::Globals->{'$normName'}";
return $expr if $LL::Main::Globals->present($normName);
return $expr if defined($self->{names}->{$name});
return undef;
}
# If it's defined in $self...
return $self->perlVar($name) if defined($self->{names}->{$name});
# See if it's in the parent.
return $self->{parent}->lookupExpr($name) if $self->{parent};
# Not found.
return undef;
}
# Given name $name, return the name of a Perl variable that will hold
# it underneath. Non-word variables will be converted. Instance
# variables are converted to hash field access expressions.
sub perlVar {
my ($self, $name) = @_;
die "Qualified name to _perlVar.\n"
if LL::Name::IsQualified($name);
die "Escaped name got through!\n"
if $name =~ /^\\/;
if ($self->{isClass}) {
my $name = $self->{varPrefix}.$name;
return '$V_self->{\'' . $name . '\'}';
}
return "\$V_$name" if $name =~ /^\w+$/;
my %escapes = ('-' => 'minus',
'.' => 'dot',
'|' => 'pipe',
'!' => 'bang',
'@' => 'at',
"\$" => 'buck',
'%' => 'percent',
'^' => 'caret',
'&' => 'and',
'*' => 'star',
'+' => 'plus',
'=' => 'eq',
'?' => 'huh',
'<' => 'lt',
'>' => 'gt',
'/' => 'slash');
my $esc = sub {
$_ = shift;
defined($escapes{$_}) && return $escapes{$_};
return sprintf ("x%x", ord($_));
};
$name =~ s/(.)/'_'.$esc->($1)/eg;
return "\$VV$name";
}
# Return an expression that defines local variable $name. $name must
# be defined in $self--it may not be inherited from a parent
# namespace.
sub declExpr {
my ($self, $name) = @_;
die "Unknown name '$name'\n" if $self->isUndefined($name); # Sanity check
# Globals are special so we handle them separately.
if ($self->{isGlobal}) {
my $def = $self->{names}->{$name}->[1] ? 'defsetconst' : 'defset';
return "\$LL::Main::Globals->$def('$name', NIL);";
}
return 'my ' . $self->perlVar($name) . ' = NIL;';
}
# Return perl source that will create a new instance of $self
sub perlConstructorSrc {
my ($self) = @_;
my $src = Data::Dumper->Dump([$self]);
# Strip the assignment off the front. This is a bit hacky.
$src =~ s/^\s*\$VAR1\s*=\s*//;
return $src;
}
# Return a sorted list of all names held by $self or any of its
# parents that are not global.
sub _allLocalNames {
my ($self) = @_;
return () if $self->{isGlobal} || $self->{isClass};
my @names = keys %{$self->{names}};
push @names, $self->{parent}->_allLocalNames()
if $self->{parent};
@names = sort @names;
return @names;
}
# Emit a series of expressions that reference all of the variables.
# The expression will probably be optimized away but it's enough to
# force Perl to create the variable.
sub forcedRefExpression {
my ($self) = @_;
return "" if $self->{isGlobal};
my $nameList = join(',', map {$self->perlVar($_)} $self->_allLocalNames());
my $expr = $self->indent() . "($nameList) if 0;\n";
return $expr;
}
# Return a temp. name. This will be declared by the compiler in the
# preamble. $num is the number of the temp and declaring a temp will
# also create all previous temps. $num defaults to 0 if omitted.
sub temp {
my ($self, $num) = @_;
$num ||= "0";
$num++;
$self->{tempCount} = $num
if ($num > $self->{tempCount});
return "\$deckTemp$num";
}
# Test if any temp names were requested.
sub hasTemps {
my ($self) = @_;
return $self->{tempCount} > 0;
}
# Return the list of temp names in an array.
sub tempNames {
my ($self) = @_;
return map {$self->temp($_)} (0 .. $self->{tempCount} - 1);
}
# ---------------------------------------------------------------------------
package LL::Object;
sub new {
my ($class, $ref, $xxx) = @_;
# Test to catch the case where you pass an array instead of its
# reference
die "Extra argument to 'new'\n" if $xxx;
die "Attempted to instantiate abstract class 'LL::Stringlike'\n"
if ($class eq 'LL::Stringlike');
# Turn $ref into a reference if it isn't one
if (!ref($ref)) {
my $v = $ref;
$ref = \$v;
}
return bless $ref, $class;
}
# Printable type name, used by check*().
sub _nm {
my ($self) = @_;
my $cl = $self->class();
my $nm = $cl && $cl->{name};
if (!$nm) {
$nm = ref($self);
$nm =~ s/^LL:://;
}
return $nm;
}
sub checkType {
my ($self, $type, $name) = @_;
my $fname = "";
$fname = " in '$name'" if $name;
$self->isa("LL::$type")
or die "Expected 'LL::$type'; got @{[ref($self)]}$fname.\n";
}
# Exit with a message and backtrace as a result of unexpected type.
sub tbt ( $ ) {
my ($msg) = @_;
LL::Main::backtrace("Type error: $msg");
}
sub checkNumber {tbt "Expected number, got @{[(shift)->_nm()]}@_"}
sub checkByte {tbt "Expected integer from 0 to 255, got @{[(shift)->_nm()]}@_"}
sub checkString {tbt "Expected string, got @{[(shift)->_nm()]}@_"}
sub checkList {tbt "Expected list, got @{[(shift)->_nm()]}@_"}
sub checkSymbol {tbt "Expected symbol, got @{[(shift)->_nm()]}@_"}
sub checkQuote {tbt "Expected quoted expr, got @{[(shift)->_nm()]}@_"}
sub checkQtLoL {tbt "Expected quoted LoL, got @{[(shift)->_nm()]}@_"}
sub checkQtSym {tbt "Expected quoted Symbol, got @{[(shift)->_nm()]}@_"}
sub checkLoL {tbt "Expected LoL, got @{[(shift)->_nm()]}@_"}
sub checkFun {tbt "Expected procedure, got @{[(shift)->_nm()]}@_"}
sub checkClass {tbt "Expected class, got @{[(shift)->_nm()]}@_"}
sub checkStruct {tbt "Expected struct, got @{[(shift)->_nm()]}@_"}
sub checkLocalName {tbt "Expected unqualified name, got @{[(shift)->_nm()]}@_"}
sub checkValidName {tbt "Expected valid name, got @{[(shift)->_nm()]}@_"}
sub checkNonOperatorSymbol {tbt "Expected non-symbol name, got @{[(shift)->_nm()]}@_"}
sub isAtom {return 0}
sub isSymbol {return 0}
sub isLocalName {return 0}
sub isStringlike {0}
sub isString {0}
sub isInterpString {return 0}
sub isOperator {return 0}
sub isUnescapedOperator {return 0}
sub isEscapedOperator {return 0}
sub isEol {return 0}
sub isEof {return 0}
sub isExplicitEol {return 0}
sub isParen {return 0}
sub isRoundParen {return 0}
sub isLiteral {return 0}
sub isEmptyList {return 0}
sub isList {return 0}
sub isByteArray {return 0}
sub isInfixList {return 0}
sub isQuote {return 0}
sub isNil {return 0}
sub isMacro {return 0}
sub isProcedure {return 0}
sub isContinuation {return 0}
sub isCallable {return 0}
sub isTrue {return 1}
sub isNumber {return 0}
sub isQtLoL {return 0} # Is a quoted list containing only lists
sub isQtList {return 0} # Is a quoted list?
sub isQtSym {return 0} # Is a quoted Symbol?
sub isLoL {return 0} # Is an list containing only lists
sub isPerlObj {return 0}
sub isClass {return 0}
sub isStruct {return 0}
sub isUndefinedProcedure {return 0}
sub matchesOpen {return 0}
sub storeStr {my ($self) = @_; return "${$self}"}
sub printStr {my ($self) = @_; return $self->storeStr()};
sub perlForm {my ($self) = @_; tbt "No perl form for @{[$self->printStr]}"}
sub equals {
my ($self, $other) = @_;
return LL::Main::boolObj(ref($self) eq ref($other) &&
$self->_inTypeEq($other));
}
sub _inTypeEq {my ($self, $other) = @_; return $self == $other }
sub checkIndexable {
my ($self) = @_;
tbt "Expecting indexable type, got @{[ref($self)]}"
unless $self->isIndexable();
}
# Return the corresponding Deck class for $self. This won't work
# until initGlobals has been called.
{
my %builtinClasses; # Registry of built-in classes
sub class {
my ($self) = @_;
my $name = ref($self);
$name =~ s/^LL:://
or die "Invalid class name '$name'\n";
return $builtinClasses{$name};
}
# Register $deckClass as a builtin class so that 'class' can find
# it.
sub registerBuiltin {
my ($class, $name, $deckClass) = @_;
$builtinClasses{$name} = $deckClass;
}
# Force a method cache refresh of all classes.
sub refreshAllBuiltinClassMethodCaches {
my ($class) = @_;
for my $cl (values %builtinClasses) {
$cl->refreshCache();
}
}
}
# Call deck method named by $name on $self. All arguments must go
# through decktype correctly. The result is still a deckType
sub deckCall {
my ($self, $name, @args) = @_;
@args = map { LL::Main::decktype($_) } @args;
my $class = $self->class();
$class or die "deckCall on internal class.\n";
my $method = $class->lookup($name);
my $result = $method->($self, @args);
return $result;
}
# Builtin-type behaviours
sub isIndexable {my ($self) = @_;
$self->deckCall('isIndexable_get')->perlForm()}
sub at {my ($self, @args) = @_;
$self->deckCall('at', @args)}
sub atPut {my ($self, @args) = @_;
$self->deckCall('atPut', @args)}
sub size {my ($self) = @_;
$self->deckCall('size_get')->perlForm()}
package LL::Number;
use base 'LL::Object';
sub new {
my ($class, $numOrRef, $xxx) = @_;
# Force Perl to turn $numOrRef into a number.
$numOrRef += 0 unless ref($numOrRef);
${$numOrRef} += 0 if ref($numOrRef);
return $class->SUPER::new($numOrRef, $xxx);
}
sub checkNumber {}
sub checkByte {
my ($self) = @_;
my $val = ${$self};
$self->SUPER::checkByte()
unless ( $val >= 0 && $val <= 255 && $val eq int($val) );
}
sub isTrue {my ($self) = @_; !! ${$self} }
sub isLiteral {return 1}
sub isNumber {return 1}
sub _inTypeEq {my ($self, $other) = @_; return ${$self} == ${$other} }
sub perlForm {my ($self) = @_; return ${$self}}
sub perlConstructorSrc {
my ($self) = @_;
return "LL::Number->new(${$self})";
}
package LL::Stringlike;
use base 'LL::Object';
sub equals {my ($self, $other) = @_;
return LL::Main::boolObj(${$self} eq ${$other})}
sub printStr {my ($self) = @_; return $ {$self} }
sub isStringlike {1}
sub isTrue {my ($self) = @_; return ${$self} ne ''}
sub isIndexable {return 1}
sub perlForm {my ($self) = @_; return ${$self}}
sub _sanitizeIndex {
my ($self, $index) = @_;
$index->checkNumber();
die "Index out of range: ${$index}\n"
if (int(${$index}) > length (${$self}) - 1 ||
int(${$index}) < -length(${$self}) );
return int(${$index});
}
sub size {my ($self) = @_; return length(${$self}) }
sub at {
my ($self, $index) = @_;
return LL::String->new( substr(${$self}, $self->_sanitizeIndex($index), 1) );
}
sub atPut {
my ($self, $index, $value) = @_;
$value->checkString();
die "Attempted to store a multi-character string inside another string.\n"
if length(${$value}) != 1;
$index = $self->_sanitizeIndex($index);
substr(${$self}, $index, 1) = ${$value};
return $value;
}
package LL::String;
use base 'LL::Stringlike';
sub checkString {}
sub isAtom {return 1}
sub isLiteral {return 1} # ???
sub storeStr {my ($self) = @_; return "\"${$self}\""};
sub isString {return 1}
sub perlConstructorSrc {
my ($self) = @_;
my $selfStr = LL::Main::perlLit(${$self});
return "LL::String->new($selfStr)";
}
# Interpolated string.
package LL::InterpString;
use base 'LL::String';
sub isInterpString {return 1}
package LL::ByteArray;
use base 'LL::Stringlike';
sub isByteArray {return 1}
sub new {
my ($class, @bytes) = @_;
for my $byte (@bytes) {
$byte->checkByte();
}
my $contents = join("", map { chr(${$_}) } @bytes);
my $self = \$contents;
return bless $self, $class;
}
sub newSized {
my ($class, $size) = @_;
my $contents = "\0" x $size;
my $self = \$contents;
return bless $self, $class;
}
sub newContaining {
my ($class, $contents) = @_;
die "Expecting scalar reference, got '$contents'\n"
unless ref($contents) eq 'SCALAR';
my $self = $contents;
return bless $self, $class;
}
sub isAtom {return 1}
sub storeStr {
my ($self) = @_;
my $body = join (" ", map {sprintf '0x%02x', ord($_)} split(//, ${$self}) );
return "[byteArray $body]";
}
sub printStr {my ($self) = @_; return $self->storeStr() }
sub at {
my ($self, $index) = @_;
my $char = substr(${$self}, $self->_sanitizeIndex($index), 1);
return LL::Number->new(ord($char));
}
sub atPut {
my ($self, $index, $value) = @_;
$value->checkByte();
$index = $self->_sanitizeIndex($index);
substr(${$self}, $index, 1) = chr(${$value});