-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathh.eyp
1377 lines (1272 loc) · 37 KB
/
h.eyp
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
# h.eyp: Compiler for Warren's simple H language.
# Char and int are the same. No structs, unions.
#
# (c) Warren Toomey, 2016. GPL3 license.
#
%token IDENTIFIER CONSTANT STRINGLITERAL
%token INC_OP DEC_OP LEFT_OP RIGHT_OP LE_OP GE_OP EQ_OP NE_OP AND_OP OR_OP
%token CHAR INT VOID RECURSIVE
%token IF ELSE WHILE DO GOTO CONTINUE BREAK RETURN
%left WEAK
%right ELSE
%start translation_unit
%{
use Data::Dumper;
### GLOBALS ###
my ( $IN, $OUT ); # Filehandles for input & output files
my $Basename; # Basename of both files
my @TokenQueue; # Stack of tokens not yet read
my $Incomment; # Are we in a multi-line comment?
my $Linenumber; # What line number we are on
my $Optimise=1; # Are optimisations turned on?
my @Constlist; # List of constants in array initialisation
my %Global; # List of known global identifiers
my @GlobaLine; # Output lines for the globals
my $Isvoid=0; # Set if we see the keyword 'void'
my $Isrecursive=0; # Set if we see the keyword 'recursive'
my %Functype; # Hash of void and recursive types per function
my %Local; # List of known per-function identifiers
# ->{fnname}->{id}
my %PPosn= ( # The parameter names and position for each function
'putchar' => [ 'c' ],
'printn' => [ 'n' ],
'open' => [ 'buf', 'how' ],
'read' => [ 'fd', 'buf', 'cnt' ],
'write' => [ 'fd', 'buf', 'cnt' ],
'close' => [ 'fd' ],
'creat' => [ 'buf' ],
'seek' => [ 'fd', 'offset', 'how' ],
'link' => [ 'dir', 'src', 'dst' ],
'unlink' => [ 'buf' ],
'setuid' => [ 'uid' ],
'rename' => [ 'old', 'new' ],
'chdir' => [ 'dir' ],
'chmod' => [ 'file', 'mode' ],
'chown' => [ 'file', 'uid' ],
);
my $Last_functionid=""; # Name of the last function that was created
my $Calledfn=""; # Name of function being called, needed for arguments
my %Const; # List of numeric constants used
my @FinalLine; # Array of references to arrays which contain all
# the generated assembly code lines
my @Forstack; # Stack of line arrayrefs of third expressions in FOR
# List of temp locations. We shift to get one,
# unshift to return it
my @Templocn; # List of available temporary locations
my $Tempnum= 20; # Number of available temporary locations
my $Line=[ ]; # List of assembly code lines we have generated
# but which have not yet been added to the final
# set of lines in @FinalLine
my %Keyword= ( # List of keywords in the grammar
'break' => 'BREAK',
'char' => 'CHAR',
'continue' => 'CONTINUE',
'do' => 'DO',
'else' => 'ELSE',
'for' => 'FOR',
'goto' => 'GOTO',
'if' => 'IF',
'int' => 'INT',
'return' => 'RETURN',
'recursive'=> 'RECURSIVE',
'void' => 'VOID',
'while' => 'WHILE',
);
my %Function=( # List of known function identifiers
'printn' => 'proto',
'getchar' => 'proto',
'putchar' => 'proto',
'.exit' => 'proto',
'.open' => 'proto',
'.read' => 'proto',
'.write' => 'proto',
'.close' => 'proto',
'.getuid' => 'proto',
'.creat' => 'proto',
'.seek' => 'proto',
'.link' => 'proto',
'.unlink' => 'proto',
'.setuid' => 'proto',
'.rename' => 'proto',
'.time' => 'proto',
'.chdir' => 'proto',
'.chmod' => 'proto',
'.chown' => 'proto',
'.fork' => 'proto',
);
my %Syscall= ( # List of known system calls to translate
'exit' => '.exit', # The three built-in functions putchar,
'open' => '.open', # getchar and printn are included here so that
'read' => '.read', # we don't save/load locals on the stack when
'write' => '.write', # we call them
'close' => '.close',
'getuid' => '.getuid',
'creat' => '.creat',
'seek' => '.seek',
'link' => '.link',
'unlink' => '.unlink',
'setuid' => '.setuid',
'rename' => '.rename',
'time' => '.time',
'chdir' => '.chdir',
'chown' => '.chown',
'chmod' => '.chmod',
'fork' => '.fork',
'printn' => 'printn',
'getchar' => 'getchar',
'putchar' => 'putchar',
);
# Simple method to print error and die
sub Die
{
my $err= shift;
print(STDERR "$err on $Basename.h line $Linenumber\n");
exit(1);
}
# Declare a new global identifier id. If there is a
# value, print the label and the value.
sub new_globalid
{
my ($id, $type, $val)= @_;
Die("$id global already declared") if (defined($Global{$id}));
Die("Cannot declare $id as type void") if ($Isvoid);
Die("Cannot declare $id as type recursive") if ($Isrecursive);
$Global{$id}=$type;
return if (!defined($val));
push(@GlobaLine, "$id:");
push(@GlobaLine, " $val");
}
my $Nextpnum; # The position of the next parameter
# Declare a new local identifier for the current function
# If how is 1, we will allocate storage for it.
# If how is 0, we don't as it is an array.
# Parameters to a function are treated as locals.
sub new_localid
{
my ($fn,$id, $how)= @_;
Die("Cannot declare $id as type void") if ($Isvoid);
Die("Cannot declare $id as type recursive") if ($Isrecursive);
# If we already have a definition for this local,
# ignore it if this is from a prototype
if (defined($Local{$fn}{$id})) {
if ($Function{$fn} eq 'proto') {
# However, check that it's in the same position
Die("$fn: $id not in same position as prototype")
if ($PPosn{$fn}[$Nextpnum] ne $id);
$Nextpnum++; return;
}
Die("$fn: $id local already declared");
}
# This was not defined beforehand.
# Define the local and store its position
$Local{$fn}{$id}=$how;
$PPosn{$fn}[$Nextpnum++]= $id;
}
# Declare and create a new array. If $Last_functionid has a
# value, then this is a local array, so we need to decorate its
# name with the function's name. Otherwise, it is a global array.
# Return the id
sub new_array
{
my ($id, $valref)= @_;
# Make this a local variable if $Last_functionid has a value
if ($Last_functionid) {
new_localid($Last_functionid, $id,0);
$id= "$Last_functionid.$id";
} else {
new_globalid($id, 'array');
}
# Strings are dealt with elsewhere
return ($id) if (!defined($valref));
# Create a pointer to the array base
push(@GlobaLine, "$id: $id.base");
push(@GlobaLine, "$id.base:");
# Output the contents of the array
foreach my $val (@$valref) {
push(@GlobaLine, " $val");
}
return($id);
}
# Given an identifier arrayref, see if this is a local or
# a global. Return a local identifier ref or the original.
# Return a string with identifier and any 'i'
#
# Expression identifiers are represented as an arrayref with two or
# three elements: the identifier, 'i' if it needs an
# indirect reference, and an optional third value which
# is the array offset expression (i.e. also an arrayref).
# The second element is 'array' if there is an offset.
sub getid
{
my ($idref, $how)= @_;
Die("undefined id in getid from $how") if (!defined($idref));
my ($id, $ind, $offset)= @$idref;
# Free up a temporary location
if ($id=~ m{^.temp\d$}) {
unshift(@Templocn, $id);
}
# Add the function name if this is a local identifier
$id= "$Last_functionid.$id"
if (defined($Local{$Last_functionid}{$id}));
# Arrays are hard because we have to create a pointer to
# the element, and then we can return the pointer.
if ($ind eq 'array') {
my ($offid, $offind) = @$offset;
# If this isn't a lac, save the current AC
my $temp= tempdac() if ($how ne 'lac');
Die("can't index an array more than once") if ($offind eq 'array');
$offset= getid($offset); # Get the real offset name
# Get the pointer to the array element into .ptr
# and then get back the saved AC. .ptr is now
# pointing at the array element
push(@$Line, ['lac', $id]);
push(@$Line, ['tad', "$offset"]);
push(@$Line, ['dac', '.ptr']);
lac($temp) if ($how ne 'lac');
$id='.ptr'; $ind=' i';
}
return("$id$ind");
}
#### LABEL CODE
my @loopstack; # Stack of labels for each loop
my @ifstack; # Stack of labels for each selection statement
my $lifref; # Points to either the loopstack or the ifstack
# Return a new label
my $label=0;
sub new_label
{
$label++;
return("LL$label");
}
#### FUNCTION CODE
# Declare a new function. The definition is always "proto" when we are
# called, and stays that way after a function prototype. It changes to
# "real" when the function is really defined.
sub new_functionid
{
my ($id, $definition)= @_;
Die("$id function conflicts with global") if (defined($Global{$id}));
Die("$id function already declared")
if (defined($Function{$id}) && $Function{$id} eq "real");
$Function{$id}=$definition; # proto or real
$Nextpnum=0; # Params for this function start at 0
$Last_functionid=$id;
# Mark the type of function
$Functype{$id}{void}=1 if $Isvoid;
$Functype{$id}{recursive}=1 if $Isrecursive;
}
# Print out the label of the function just created
# We do this for real function declarations, not just prototypes
sub print_function_label
{
$Function{$Last_functionid}= 'real';
push(@$Line, [ "$Last_functionid: 0" ]);
}
# Check and return a function name. Translate system calls to
# ones starting with a dot, so we don't tread on the assembler's toes
sub get_functionid
{
my $id= shift;
$id= $Syscall{$id} if (defined($Syscall{$id}));
Die("$id function not yet declared") if (!defined($Function{$id}));
return($id);
}
### STRING LITERAL CODE
my @Stringlit; # List of string literals and their identifiers
my $strlabel=0;
# Return a new string label
sub new_strlabel
{
$strlabel++;
return("STR$strlabel");
}
# Add a new string literal. Make a label if none
sub add_strliteral
{
my ($s, $label)= @_;
$label= new_strlabel() if (!defined($label));
push(@Stringlit, [ $s, $label ]);
return($label);
}
### TEMPORARY LOCATIONS CODE
#
# When I first wrote the compiler, I thought I could keep the
# last expression result in the AC. This doesn't work for
# exprssions like if (x + 2 > y - 4). Now, every expression is
# saved in a temporary location and reloaded as required. We
# rely on the optimiser to remove pointless store/loads.
#
# Expand an identifier and load it into the AC
sub lac
{
my $id= shift;
if (!defined($id)) {
Die("No expression value, perhaps a void function");
}
push(@$Line, ['lac', getid($id, 'lac')]);
}
# Expand an identifier and store into it from the AC
sub dac
{
my ($id, $who)= @_;
return if (!defined($id));
#push(@$Line, ['dac', getid($id, 'dac'), "\t\t\" $who"]);
push(@$Line, ['dac', getid($id, 'dac')]);
}
# Reset the temporary locations
sub reset_temp_locations
{
@Templocn= ();
foreach my $i (1 .. $Tempnum) {
push(@Templocn, ".temp$i");
}
}
# Temporarily store the AC and return an
# identifier for the temporary storage
sub tempdac
{
Die("out of temp locations") if (@Templocn==0);
my $temp= shift(@Templocn);
push(@$Line, ['dac', $temp]);
return([ $temp, '' ]);
}
### CONSTANTS CODE
# Create a new constant to be written out later
sub new_const
{
my $c= shift;
my $label;
# Negative constants have labels starting with m (minus)
# Positive constants have labels starting with d (decimal)
if ($c<0) {
my $absc= abs($c);
$label= "m$absc";
} else {
$label= "d$c";
}
$Const{$label}=$c;
return($label);
}
### FUNCTION CALLING CODE
# For functions which are recursive, save their local variables
# and the return address onto the stack.
sub save_locals
{
my $fname= shift;
# If the caller is a recursive function, then save all our local
# variables onto the stack. However, don't do this when we are calling
# a system call
if (defined($Functype{$Last_functionid}{recursive}) &&
!defined($Syscall{$fname})) {
# Firstly save the return address
push(@$Line, ['lac', "$Last_functionid"]);
push(@$Line, ['dac', '.stkptr i']);
# Now save the locals
foreach my $local (@{ $PPosn{$Last_functionid} }) {
push(@$Line, ['lac', "$Last_functionid.$local"]);
push(@$Line, ['dac', '.stkptr i']);
}
}
}
# Call the named function. For recursive function callers, also
# restore the local variables and the return address from the stack.
sub call_function
{
my $fname= shift;
my $temp;
my $localcnt;
# Output the code to call the function, and
# store the returned value of the non-void function
push(@$Line, ['jms', get_functionid($fname) ]);
$temp= tempdac() if (!defined($Functype{$fname}{void}));
# If the caller is a recursive function, retrieve our local variables
if (defined($Functype{$Last_functionid}{recursive}) &&
!defined($Syscall{$fname})) {
$localcnt= 1+ scalar(@{ $PPosn{$Last_functionid} }); # +1 for return addr
new_const( -$localcnt);
push(@$Line, ['lac', '.stkptr']);
push(@$Line, ['tad', "m$localcnt"]);
push(@$Line, ['dac', '.stkptr']);
# Firstly reload the return address
push(@$Line, ['lac', '.stkptr i']);
push(@$Line, ['dac', "$Last_functionid"]);
# Now reload the locals
foreach my $local (@{ $PPosn{$Last_functionid} }) {
push(@$Line, ['lac', '.stkptr i']);
push(@$Line, ['dac', "$Last_functionid.$local"]);
}
# And reset the stack pointer
push(@$Line, ['lac', '.stkptr']);
push(@$Line, ['tad', "m$localcnt"]);
push(@$Line, ['dac', '.stkptr']);
}
# Return nothing or the temporary value
if (defined($Functype{$fname}{void})) {
return(undef);
} else {
return($temp);
}
}
%}
%%
translation_unit:
global_declarations
;
global_declarations:
global_declaration
| global_declaration global_declarations
;
global_declaration:
type_specifier global_declaration_list ';'
{ # Reset the void/recursive flags for the next function declaration
$Isvoid=0; $Isrecursive=0;
}
| type_specifier function_definition
;
global_declaration_list:
global_id_declaration
| global_id_declaration ',' global_declaration_list
;
global_id_declaration:
ptr_identifier.d
{ # A new global variable with a default zero value
new_globalid($d,'',0);
}
| ptr_identifier.d '=' CONSTANT.c
{ # A new global variable with a specific value
new_globalid($d, '',$c);
}
| array_declaration
;
local_declaration:
type_specifier local_declaration_list ';'
{ # Reset the void/recursive flags for the next function declaration
$Isvoid=0; $Isrecursive=0;
}
;
local_declaration_list:
local_id_declaration
| local_id_declaration ',' local_declaration_list
;
local_id_declaration:
ptr_identifier.p
{ # A new local variable in this function named $p
new_localid($Last_functionid, $p, 1);
}
| ptr_identifier.p '=' bit_expression.e
{ # A new local variable in this function named $p
new_localid($Last_functionid, $p, 1);
# Load the expression and save it into $p
lac($e); dac([$p,''], 'local_id_declaration');
}
| array_declaration
;
array_declaration:
ptr_identifier.d '[' CONSTANT.c ']'
{
# Build a list of zero values
my @zlist;
foreach my $count (1 .. $c) {
push(@zlist, 0);
}
new_array($d, \@zlist);
}
| ptr_identifier.d '[' ']' '=' '{' constant_list.l '}'
{ # Create a new array initialised with the constant list
new_array($d, $l);
}
| ptr_identifier.d '[' ']' '=' STRINGLITERAL.s
{ # Create a new array with no element list, but then
# add the string literal and point the array at it
my $id= new_array($d, undef);
add_strliteral($s, $id);
}
;
constant_list:
CONSTANT.c
{ # Return an arrayref with one element
[ $c ];
}
| constant_list.l ',' CONSTANT.c
{ # Return an arrayref with an extra element
push(@$l, $c); $l;
}
;
ptr_identifier:
IDENTIFIER.i
{ $i; }
| pointer IDENTIFIER.i
{ $i; }
;
type_specifier:
type
| recursive type
;
type:
VOID
{ $Isvoid=1; }
| CHAR
| INT
;
recursive:
RECURSIVE
{ $Isrecursive=1; }
;
pointer:
'*'
;
function_definition:
function_declarator ';'
| function_declarator
{ print_function_label();
reset_temp_locations();
}
compound_statement
{ # Output the code to return from the functions
push(@$Line, ['jmp', "$Last_functionid i"]);
}
;
function_declarator:
ptr_identifier.f '(' ')'
{ # Declare the function as a prototype for now
# and then reset the void/recursive flags for later
new_functionid($f,'proto');
$Isvoid=0; $Isrecursive=0;
}
| ptr_identifier.f '('
{ # Declare the function as a prototype for now
# and then reset the void/recursive flags for later
new_functionid($f,'proto');
$Isvoid=0; $Isrecursive=0;
}
parameter_list ')'
;
parameter_list:
parameter_declaration
| parameter_list ',' parameter_declaration
;
parameter_declaration:
type_specifier ptr_identifier.p
{ # Create the parameter as a new local, and
# reset the void/recursive flags
new_localid($Last_functionid, $p, 1);
$Isvoid=0; $Isrecursive=0;
}
;
function_expression:
IDENTIFIER.f '(' ')'
{ save_locals($f); call_function($f); }
| IDENTIFIER.f '('
{ # We have parameters, so start them at zero
$Nextpnum=0; $Calledfn= $f; save_locals($f); }
argument_list ')'
{ call_function($f); }
;
argument_list:
argument.a
{ # Get the name of the function's param at this position
my $pname= $PPosn{$Calledfn}[$Nextpnum++];
lac($a); dac(["$Calledfn.$pname",''], 'argument_list');
}
| argument_list ',' argument.a
{ # Get the name of the function's param at this position
my $pname= $PPosn{$Calledfn}[$Nextpnum++];
lac($a); dac(["$Calledfn.$pname",''], 'argument_list2');
}
;
# Expression identifiers are represented as an arrayref with two or
# three elements: the identifier, 'i' if it needs an
# indirect reference, and an optional third value which
# is the array offset expression (i.e. also an arrayref).
# The second element is 'array' if there is an offset.
lvalue_expression:
IDENTIFIER.i
{ [ $i, '' ]; }
| '*' IDENTIFIER.i
{ [ $i, ' i' ]; }
| IDENTIFIER.i '[' bit_expression.e ']'
{ [ $i, 'array', $e ]; }
;
basic_expression:
lvalue_expression
| postop_expression
| CONSTANT.c
{ # Create a constant, get its id and return an idref
$c= new_const($c); [ $c, '']; }
| STRINGLITERAL.s
{ # Create a string literal, get its id and return an idref
my $id= add_strliteral($s);
[ $id, '' ]; }
| function_expression
| '(' bit_expression.b ')'
{ $b; }
;
unary_expression:
basic_expression
| '~' basic_expression.e
{
lac($e);
push(@$Line, ['cma']);
tempdac();
}
| '!' basic_expression.e
{ my $temp= tempdac();
lac($e);
# Set the temp to 0 if $e is non-zero, 1 if $e is zero
push(@$Line, ['sza']);
push(@$Line, ['jmp', '1f']);
push(@$Line, ['lac', '.d1']);
push(@$Line, ['dac', $temp->[0]]);
push(@$Line, ['jmp', '2f']);
push(@$Line, ['1: dzm', $temp->[0]]);
push(@$Line, ['2:']);
$temp;
}
;
multiplicative_expression:
unary_expression
| unary_expression.lhs '*' multiplicative_expression.rhs
{
lac($rhs);
push(@$Line, ['dac', '.+4']);
lac($lhs);
push(@$Line, ['cll; mul; ..; lacq']);
tempdac();
}
| unary_expression.lhs '/' multiplicative_expression.rhs
{
lac($rhs);
push(@$Line, ['dac', '.+4']);
lac($lhs);
push(@$Line, ['cll; idiv; ..; lacq']);
tempdac();
}
| unary_expression.lhs '%' multiplicative_expression.rhs
{
lac($rhs);
push(@$Line, ['dac', '.+4']);
lac($lhs);
push(@$Line, ['cll; idiv; ..']);
tempdac();
}
;
additive_expression:
multiplicative_expression
| additive_expression.lhs '+' multiplicative_expression.rhs
{
lac($lhs);
push(@$Line, ['tad', getid($rhs, 'rhsadd')]);
tempdac();
}
| additive_expression.lhs '-' multiplicative_expression.rhs
{
lac($lhs);
push(@$Line, ['cma']);
push(@$Line, ['tad', getid($rhs, 'rhssub')]);
push(@$Line, ['cma']);
tempdac();
}
;
shift_expression:
additive_expression
| shift_expression.lhs LEFT_OP CONSTANT.c
{ lac($lhs);
push(@$Line, ['lls', $c]);
tempdac();
}
| shift_expression.lhs RIGHT_OP CONSTANT.c
{ lac($lhs);
push(@$Line, ['lrss', $c]);
tempdac();
}
;
bit_expression:
shift_expression
| bit_expression.lhs '&' shift_expression.rhs
{
lac($lhs);
push(@$Line, ['and', getid($rhs, 'rhsand') ]);
tempdac();
}
| bit_expression.lhs '^' shift_expression.rhs
{
lac($lhs);
push(@$Line, ['xor', getid($rhs, 'rhsxor') ]);
tempdac();
}
| bit_expression.lhs '|' shift_expression.rhs
{
lac($rhs);
push(@$Line, ['lmq']);
lac($lhs);
push(@$Line, ['omq']);
tempdac();
}
;
# Save a zero or non-zero result into a temp location
relational_expression:
bit_expression
| bit_expression.lhs '<' bit_expression.rhs
{
lac($lhs);
push(@$Line, ['cma']);
push(@$Line, ['tad', getid($rhs, 'rhs<') ]);
push(@$Line, ['cma']);
push(@$Line, ['sma']);
push(@$Line, ['cla']); # Not true, now zero
tempdac();
}
| bit_expression.lhs '>' bit_expression.rhs
{
lac($rhs);
push(@$Line, ['cma']);
push(@$Line, ['tad', getid($lhs, 'lhs>')]);
push(@$Line, ['cma']);
push(@$Line, ['sma']);
push(@$Line, ['cla']); # Not true, now zero
tempdac();
}
| bit_expression.lhs LE_OP bit_expression.rhs
{
lac($rhs);
push(@$Line, ['cma']);
push(@$Line, ['tad', getid($lhs, 'lhs<=') ]);
push(@$Line, ['cma']);
push(@$Line, ['spa']);
push(@$Line, ['jmp', '1f']);
push(@$Line, ['lac', '.d1']); # True, now one
push(@$Line, ['jmp', '2f']);
push(@$Line, ['1: cla']); # Not true, now zero
push(@$Line, ['2:']);
tempdac();
}
| bit_expression.lhs GE_OP bit_expression.rhs
{
lac($lhs);
push(@$Line, ['cma']);
push(@$Line, ['tad', getid($rhs, 'rhs>=') ]);
push(@$Line, ['cma']);
push(@$Line, ['spa']);
push(@$Line, ['jmp', '1f']);
push(@$Line, ['lac', '.d1']); # True, now one
push(@$Line, ['jmp', '2f']);
push(@$Line, ['1: cla']); # Not true, now zero
push(@$Line, ['2:']);
tempdac();
}
| bit_expression.lhs EQ_OP bit_expression.rhs
{
my $third= new_label();
lac($lhs);
push(@$Line, ['sad', getid($rhs, 'rhs==') ]);
push(@$Line, ['jmp', '1f']);
push(@$Line, ['cla']); # Not true, now zero
push(@$Line, ['jmp', '2f']);
push(@$Line, ['1: lac', '.d1']); # True, now one
push(@$Line, ['2:']);
tempdac();
}
| bit_expression.lhs NE_OP bit_expression.rhs
{
lac($lhs);
push(@$Line, ['sad', getid($rhs, 'rhs!=') ]);
push(@$Line, ['jmp', '1f']);
push(@$Line, ['lac', '.d1']); # True, now one
push(@$Line, ['jmp', '2f']);
push(@$Line, ['1: cla']); # Not true, now zero
push(@$Line, ['2:']);
tempdac();
}
;
logical_expression:
relational_expression
| relational_expression.lhs AND_OP logical_expression.rhs
{ # We can't just "and" them because both might be non-zero
# but the "and" result might be zero.
lac($lhs);
push(@$Line, ['sna']);
push(@$Line, ['jmp', '1f']);
lac($rhs);
push(@$Line, ['sna']);
push(@$Line, ['jmp', '1f']);
push(@$Line, ['lac', '.d1']);
push(@$Line, ['jmp', '2f']);
push(@$Line, ['1: cla']);
push(@$Line, ['2:']);
tempdac();
}
| relational_expression.lhs OR_OP logical_expression.rhs
{
lac($rhs);
push(@$Line, ['lmq']);
lac($lhs);
push(@$Line, ['omq']);
tempdac();
}
;
argument:
logical_expression
;
true_false_expression:
logical_expression.b
{
lac($b);
push(@$Line, ['lac', getid($b, 'lac')]);
push(@$Line, ['sna']);
push(@$Line, ['jmp', $lifref->[-1]->[0]]);
}
;
statement:
labeled_statement
| assignment_statement ';'
| function_expression ';'
| selection_statement
| iteration_statement
| jump_statement
| compound_statement
| postop_statement
;
labeled_statement:
IDENTIFIER.i ':'
{ push(@$Line, [ "$i:" ]); }
statement
;
assignment_statement:
lvalue_expression.l '=' bit_expression.e
{ lac($e); dac($l, 'assignment_statement'); reset_temp_locations(); }
;
selection_statement:
if_head %prec WEAK
{ push(@$Line, ["$ifstack[-1]->[0]:"]);
pop(@ifstack);
}
| if_head
{ push(@$Line, ['jmp', $ifstack[-1]->[1]]);
push(@$Line, ["$ifstack[-1]->[0]:"]);
}
ELSE statement
{ push(@$Line, ["$ifstack[-1]->[1]:"]);
pop(@ifstack);
}
;
if_head:
IF
{ # Generate false and end labels for this IF
my $false= new_label();
my $end= new_label();
push(@ifstack, [ $false, $end ]);
$lifref= \@ifstack;
}
'(' true_false_expression ')'
{ reset_temp_locations(); }
statement
;
iteration_statement:
WHILE
{ # Generate start and end labels for this loop
my $start= new_label();
my $end= new_label();
push(@loopstack, [ $end, $start ]);
$lifref= \@loopstack;
push(@$Line, ["$start:"]);
}
'(' true_false_expression ')'
statement
{ push(@$Line, ['jmp', $loopstack[-1]->[1]]);
push(@$Line, ["$loopstack[-1]->[0]:"]);
pop(@loopstack);
reset_temp_locations();
}
| DO
{ # Generate start and end labels for this loop
my $start= new_label();
my $end= new_label();
push(@loopstack, [ $end, $start ]);
$lifref= \@loopstack;
push(@$Line, ["$start:"]);
}
statement WHILE '(' true_false_expression ')' ';'
{ push(@$Line, ['jmp', $loopstack[-1]->[1]]);
push(@$Line, ["$loopstack[-1]->[0]:"]);
pop(@loopstack);
reset_temp_locations();
}
| FOR
'(' assignment_statement ';'
{ # Generate start and end labels for this loop
my $start= new_label();
my $end= new_label();
push(@loopstack, [ $end, $start ]);
$lifref= \@loopstack;
push(@$Line, ["$start:"]);
}
true_false_expression ';'
{ # Move all the current lines over to FinalLine
# and empty $Line for the third statement
push(@FinalLine, $Line); $Line= [];
reset_temp_locations();
}
third_for_expression ')' statement
{
# Move all the current lines over to FinalLine
push(@FinalLine, $Line); $Line= [];
# Pop off the most recent FOR third statement code
# and save in the FinalLine array
push(@FinalLine, pop(@Forstack));
# Now add in the jump at the end of the loop
push(@$Line, ['jmp', $loopstack[-1]->[1]]);
push(@$Line, ["$loopstack[-1]->[0]:"]);
pop(@loopstack);
}
;
third_for_expression:
assignment_statement
{
# Push the third statement code onto the Forstack
push(@Forstack, $Line); $Line= [];
}
| postop_expression
{
# Push the third statement code onto the Forstack
push(@Forstack, $Line); $Line= [];
}
;
jump_statement:
GOTO IDENTIFIER.i ';'
{ push(@$Line, [ 'jmp', $i ]); }
| CONTINUE ';'
{ push(@$Line, ['jmp', $loopstack[-1]->[1]]); }
| BREAK ';'
{ push(@$Line, ['jmp', $loopstack[-1]->[0]]); }