-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathzxbparser.py
More file actions
executable file
·3645 lines (2771 loc) · 96.4 KB
/
zxbparser.py
File metadata and controls
executable file
·3645 lines (2771 loc) · 96.4 KB
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/env python3
# --------------------------------------------------------------------
# SPDX-License-Identifier: AGPL-3.0-or-later
# © Copyright 2008-2024 José Manuel Rodríguez de la Rosa and contributors.
# See the file CONTRIBUTORS.md for copyright details.
# See https://www.gnu.org/licenses/agpl-3.0.html for details.
# --------------------------------------------------------------------
import math
import sys
from collections.abc import Callable
from math import pi as PI
# typings
from typing import NamedTuple, cast
import src.api.config
import src.api.dataref
import src.api.options
import src.api.utils
# Symbol Classes
from src import arch
# Global containers
from src.api import errmsg, opcodestemps
from src.api import global_ as gl
from src.api.check import (
check_and_make_label,
check_class,
common_type,
is_dynamic,
is_ender,
is_null,
is_number,
is_numeric,
is_static,
is_static_str,
is_string,
is_unsigned,
)
from src.api.config import OPTIONS
from src.api.constants import CLASS, CONVENTION, SCOPE, TYPE, LoopType
from src.api.debug import __DEBUG__
from src.api.errmsg import error, warning
from src.api.global_ import LoopInfo
# Compiler API
from src.api.symboltable.symboltable import SymbolTable
# Lexers and parsers, etc
from src.ply import yacc
from src.symbols import sym
from src.symbols.id_ import SymbolID
from src.symbols.symbol_ import Symbol
from src.symbols.type_ import Type
from src.zxbc import zxblex
from src.zxbc.zxblex import tokens # noqa
# ----------------------------------------------------------------------
# Function level entry ID in which scope we are into. If the list
# is empty, we are at global scope
# ----------------------------------------------------------------------
FUNCTION_LEVEL: list[SymbolID] = gl.FUNCTION_LEVEL
# ----------------------------------------------------------------------
# Function calls pending to check
# Each scope pushes (prepends) an empty list
# ----------------------------------------------------------------------
FUNCTION_CALLS = gl.FUNCTION_CALLS
# ----------------------------------------------------------------------
# Initialization routines to be called automatically at program start
# ----------------------------------------------------------------------
INITS = gl.INITS
# ----------------------------------------------------------------------
# Global Symbol Table
# ----------------------------------------------------------------------
SYMBOL_TABLE = gl.SYMBOL_TABLE = SymbolTable()
# ----------------------------------------------------------------------
# Defined user labels. They all are prepended _label_. Line numbers 10,
# 20, 30... are in the form: __label_10, __label_20, __label_30...
# ----------------------------------------------------------------------
LABELS = {}
# ----------------------------------------------------------------------
# True if we're in the middle of a LET sentence. False otherwise.
# ----------------------------------------------------------------------
LET_ASSIGNMENT: bool = False
# ----------------------------------------------------------------------
# True if PRINT sentence has been used.
# ----------------------------------------------------------------------
PRINT_IS_USED: bool = False
# ----------------------------------------------------------------------
# Last line number output for checking program key board BREAK
# ----------------------------------------------------------------------
last_brk_linenum: int = 0
# ----------------------------------------------------------------------
# Start of parsing
# ----------------------------------------------------------------------
class Id(NamedTuple):
"""Encapsulates an ID name and its line number where it was read"""
name: str
lineno: int
def init():
"""Initializes parser state"""
global LABELS
global LET_ASSIGNMENT
global PRINT_IS_USED
global SYMBOL_TABLE
global ast
global data_ast
global optemps
global last_brk_linenum
LABELS = {}
LET_ASSIGNMENT = False
PRINT_IS_USED = False
last_brk_linenum = 0
ast = None
data_ast = None # Global Variables AST
opcodestemps.init()
optemps = opcodestemps.OpcodesTemps()
gl.INITS.clear()
del gl.FUNCTION_CALLS[:]
del gl.FUNCTION_LEVEL[:]
del gl.FUNCTIONS[:]
SYMBOL_TABLE = gl.SYMBOL_TABLE = src.api.symboltable.symboltable.SymbolTable()
# DATAs info
gl.DATA_LABELS_REQUIRED.clear()
gl.DATA_LABELS.clear()
gl.DATA_IS_USED = False
del gl.DATAS[:]
gl.DATA_PTR_CURRENT = src.api.utils.current_data_label()
gl.DATA_FUNCTIONS = []
gl.error_msg_cache.clear()
# ----------------------------------------------------------------------
# "Macro" functions. Just return more complex expressions
# ----------------------------------------------------------------------
def _TYPE(type_: TYPE) -> sym.TYPE | None:
"""returns an internal type converted to a SYMBOL_TABLE type."""
assert isinstance(type_, TYPE)
return SYMBOL_TABLE.basic_types[type_]
def _TYPEREF(type_: TYPE, *, implicit: bool = True) -> sym.TYPEREF:
"""Returns a typing annotation"""
return sym.TYPEREF(_TYPE(type_), 0, implicit=implicit)
# ----------------------------------------------------------------------
# Utils
# ----------------------------------------------------------------------
def mark_entry_as_accessed(entry: sym.ID):
"""Marks the entry as accessed (needed) only if in the global
scope
"""
assert isinstance(entry, sym.ID)
if FUNCTION_LEVEL and entry.token == "FUNCTION": # Not in global scope
return
entry.accessed = True
def convert_to_function(entry: sym.ID, class_: CLASS, lineno: int):
"""The given entry is converted to function if it is not already."""
assert class_ in (CLASS.function, CLASS.sub)
if check_class(entry, class_, lineno):
if entry.class_ == class_:
return
entry.to_function(lineno, class_=class_)
# ----------------------------------------------------------------------
# Wrapper functions to make AST nodes
# ----------------------------------------------------------------------
def make_nop():
"""NOP does nothing."""
return sym.NOP()
def make_number(value, lineno: int, type_=None):
"""Wrapper: creates a constant number node."""
return sym.NUMBER(value, type_=type_, lineno=lineno)
def make_typecast(type_: sym.TYPING, node: sym.EXPR | None, lineno: int) -> sym.TYPECAST | sym.EXPR | None:
"""Wrapper: returns a Typecast node"""
if node is None or node.type_ is None:
return None # syntax / semantic error
if isinstance(type_, sym.TYPEREF):
type_ = type_.type_
assert isinstance(type_, sym.TYPE)
result = sym.TYPECAST.make_node(type_, node, lineno)
assert isinstance(result, None | sym.TYPECAST | sym.EXPR), f"{result.__class__.__name__} != TYPECAST | EXPR"
return result
def make_binary(lineno: int, operator, left, right, func=None, type_=None):
"""Wrapper: returns a Binary node"""
return sym.BINARY.make_node(operator, left, right, lineno, func, type_)
def make_unary(
lineno: int,
operator: str,
operand: sym.EXPR | None,
func=Callable,
type_: sym.TYPE | None = None,
) -> sym.UNARY | sym.NUMBER | sym.STRING | None:
"""Wrapper: returns a Unary node"""
if operand is None: # syntax / semantic error
return None
return sym.UNARY.make_node(lineno, operator, operand, func, type_)
def make_builtin(
lineno: int,
fname: str,
operands: Symbol | tuple | list | None,
func: Callable | None = None,
type_: sym.TYPE | None = None,
) -> sym.BUILTIN | sym.NUMBER:
"""Wrapper: returns a Builtin function node.
Can be a Symbol, tuple, or list of Symbols
If operand is an iterable, they will be expanded.
"""
if operands is None:
operands = []
assert isinstance(operands, Symbol | tuple | list)
assert isinstance(type_, sym.TYPE | None)
# TODO: In the future, builtin functions will be implemented in an external stdlib, like POINT or ATTR
__DEBUG__(f'Creating BUILTIN "{fname}"', 1)
if not isinstance(operands, list | tuple):
operands = [operands]
return sym.BUILTIN.make_node(lineno, fname, func, type_, *operands)
def make_constexpr(lineno, expr):
return sym.CONSTEXPR(expr, lineno=lineno)
def make_strslice(lineno: int, s, lower, upper):
"""Wrapper: returns String Slice node"""
return sym.STRSLICE.make_node(lineno, s, lower, upper)
def make_sentence(lineno: int, sentence: str, *args, sentinel=False):
"""Wrapper: returns a Sentence node"""
return sym.SENTENCE(lineno, gl.FILENAME, sentence, *args, is_sentinel=sentinel)
def make_asm_sentence(asm: str, lineno: int, sentinel: bool = False):
"""Creates a node for an ASM inline sentence"""
return sym.ASM(asm, lineno, gl.FILENAME, is_sentinel=sentinel)
def make_block(*args):
"""Wrapper: Creates a chain of code blocks."""
return sym.BLOCK.make_node(*args)
def make_var_declaration(entry):
"""This will return a node with a var declaration.
The children node contains the symbol table entry.
"""
return sym.VARDECL(entry)
def make_array_declaration(entry: sym.ID) -> sym.ARRAYDECL:
"""This will return a node with the symbol as an array."""
return sym.ARRAYDECL(entry)
def make_func_declaration(
func_name: str,
lineno: int,
class_: CLASS,
type_: sym.TYPEREF | None = None,
) -> sym.FUNCDECL | None:
"""This will return a node with the symbol as a function or sub."""
return sym.FUNCDECL.make_node(func_name, lineno, class_, type_=type_)
def make_arg_list(node, *args):
"""Wrapper: returns a node with an argument_list."""
result = sym.ARGLIST.make_node(node, *args)
return result
def make_argument(expr, lineno: int, byref=None, name: str = None):
"""Wrapper: Creates a node containing an ARGUMENT"""
if expr is None:
return None # There were a syntax / semantic error
if byref is None:
byref = OPTIONS.default_byref
return sym.ARGUMENT(expr, lineno=lineno, byref=byref, name=name)
def make_param_list(node, *args):
"""Wrapper: Returns a param declaration list (function header)"""
return sym.PARAMLIST.make_node(node, *args)
def make_sub_call(id_, lineno, arg_list):
"""This will return an AST node for a sub/procedure call."""
return sym.CALL.make_node(id_, arg_list, lineno, gl.FILENAME)
def make_func_call(id_, lineno, arg_list):
"""This will return an AST node for a function call."""
return sym.FUNCCALL.make_node(id_, arg_list, lineno, gl.FILENAME)
def make_array_access(id_, lineno, arglist):
"""Creates an array access. A(x1, x2, ..., xn).
This is an RVALUE (Read the element)
"""
for i, arg in enumerate(arglist):
value = make_typecast(
Type.by_name(src.api.constants.TYPE.to_string(gl.BOUND_TYPE)),
arg.value,
arg.lineno,
)
if value is None: # semantic error?
return None # return error
arg.value = value
return sym.ARRAYACCESS.make_node(id_, arglist, lineno, gl.FILENAME)
def make_array_substr_assign(lineno: int, id_: str, arg_list, substr, expr_) -> sym.SENTENCE | None:
if arg_list is None or substr is None or expr_ is None:
return None # There were errors
entry = SYMBOL_TABLE.access_call(id_, lineno)
if entry is None:
return None # There were errors
if entry.type_ != Type.string:
error(lineno, "Array '%s' is not of type String" % id_)
return None # There were errors
arr = make_array_access(id_, lineno, arg_list)
if arr is None:
return None # There were errors
expr_ = make_typecast(arr.type_, expr_, lineno)
if expr_ is None:
return None # There were errors
str_idx_type = _TYPE(gl.STR_INDEX_TYPE)
s0 = make_typecast(str_idx_type, substr[0], lineno)
if s0 is None:
return None # There were errors
s1 = make_typecast(str_idx_type, substr[1], lineno)
if s1 is None:
return None # There were errors
if OPTIONS.string_base:
base = make_number(OPTIONS.string_base, lineno, _TYPE(gl.STR_INDEX_TYPE))
s0 = make_binary(lineno, "MINUS", s0, base, func=lambda x, y: x - y)
s1 = make_binary(lineno, "MINUS", s1, base, func=lambda x, y: x - y)
return make_sentence(lineno, "LETARRAYSUBSTR", arr, s0, s1, expr_)
def make_call(id_: str, lineno: int, args: sym.ARGLIST):
"""This will return an AST node for a function call/array access.
A "call" is just an ID followed by a list of arguments.
E.g. a(4)
- a(4) can be a function call if 'a' is a function
- a(4) can be a string slice if 'a' is a string variable: a$(4)
- a(4) can be an access to an array if 'a' is an array
This function will inspect the id_. If it is undeclared, then
id_ will be taken as a forwarded function.
"""
if args is None:
return None
assert isinstance(args, sym.ARGLIST)
entry = SYMBOL_TABLE.access_call(id_, lineno)
if entry is None:
return None
if entry.class_ is CLASS.unknown and entry.type_ == Type.string and len(args) == 1 and is_numeric(args[0]):
entry = entry.to_var() # A scalar variable. e.g a$(expr)
if entry.class_ == CLASS.array: # An already declared array
arr = sym.ARRAYLOAD.make_node(id_, args, lineno, gl.FILENAME)
if arr is None:
return None
if arr.offset is not None:
offset = make_typecast(Type.uinteger, make_number(arr.offset, lineno=lineno), lineno)
arr.append_child(offset)
return arr
if entry.class_ in (CLASS.var, CLASS.const): # An already declared/used string var
if len(args) > 1:
errmsg.syntax_error_not_array_nor_func(lineno, id_)
return None
if entry.class_ == CLASS.var:
entry = SYMBOL_TABLE.access_var(id_, lineno)
if entry is None:
return None
if len(args) == 1:
if entry.class_ == CLASS.var:
return make_strslice(lineno, entry, args[0].value, args[0].value)
# it's a const
return make_strslice(lineno, sym.STRING(entry.value, lineno), args[0].value, args[0].value)
mark_entry_as_accessed(entry)
return entry
return make_func_call(id_, lineno, args)
def make_param_decl(
id_: str,
lineno: int,
typedef: sym.TYPEREF,
*,
is_array: bool,
default_value: sym.SYMBOL | None = None,
):
"""Wrapper that creates a param declaration"""
return SYMBOL_TABLE.declare_param(id_, lineno, typedef, default_value, is_array=is_array)
def make_type(typename, lineno, implicit=False):
"""Converts a typename identifier (e.g. 'float') to
its internal symbol table entry representation.
Creates a type usage symbol stored in a AST
E.g. DIM a As Integer
will access Integer type
"""
assert isinstance(typename, str)
if not SYMBOL_TABLE.check_is_declared(typename, lineno, "type"):
return None
type_ = sym.TYPEREF(SYMBOL_TABLE.get_entry(typename), lineno, implicit=implicit)
return type_
def make_bound(lower, upper, lineno):
"""Wrapper: Creates an array bound"""
return sym.BOUND.make_node(lower, upper, lineno)
def make_bound_list(node, *args):
"""Wrapper: Creates an array BOUND LIST."""
return sym.BOUNDLIST.make_node(node, *args)
def make_label(id_: str, lineno: int):
"""Creates a label entry. Returns None on error."""
id_ = str(id_) # Labels can be numbers and must be converted to strings
entry = SYMBOL_TABLE.declare_label(id_, lineno)
if entry:
gl.DATA_LABELS[id_] = gl.DATA_PTR_CURRENT # This label points to the current DATA block index
return entry
def make_break(lineno: int, p):
"""Checks if --enable-break is set, and if so, calls
BREAK keyboard interruption for this line if it has not been already
checked"""
global last_brk_linenum
if not OPTIONS.enable_break or lineno == last_brk_linenum or is_null(p):
return None
last_brk_linenum = lineno
return make_sentence(lineno, "CHKBREAK", make_number(lineno, lineno, Type.uinteger))
# ----------------------------------------------------------------------
# Operators precedence
# ----------------------------------------------------------------------
precedence = (
("nonassoc", "ID", "ARRAY_ID"),
("left", "OR"),
("left", "AND"),
("left", "XOR"),
("right", "NOT"),
("left", "LT", "GT", "EQ", "LE", "GE", "NE"),
("left", "BOR"),
("left", "BAND", "BXOR", "SHR", "SHL"),
("left", "BNOT", "PLUS", "MINUS"),
("left", "MOD"),
("left", "MUL", "DIV"),
("right", "UMINUS"),
("right", "POW"),
("left", "RP"),
("right", "LP"),
("right", "ELSE"),
("left", "CO"),
("left", "LABEL"),
("left", "NEWLINE"),
)
# ----------------------------------------------------------------------
# Grammar rules
# ----------------------------------------------------------------------
def p_start(p):
"""start : program"""
global ast, data_ast
make_label(gl.ZXBASIC_USER_DATA, 0)
make_label(gl.ZXBASIC_USER_DATA_LEN, 0)
if PRINT_IS_USED:
OPTIONS.__DEFINES["___PRINT_IS_USED___"] = 1
if zxblex.IN_STATE:
p.type = "NEWLINE"
p_error(p)
sys.exit(1)
ast = p[0] = p[1]
__end = make_sentence(p.lexer.lineno, "END", make_number(0, lineno=p.lexer.lineno), sentinel=True)
if not is_null(ast):
if isinstance(ast, sym.BLOCK) and not is_ender(ast[-1]):
ast.append_child(__end)
else:
ast = __end
SYMBOL_TABLE.check_labels()
SYMBOL_TABLE.check_classes()
if gl.has_errors:
return
__DEBUG__("Checking pending labels", 1)
if not src.api.check.check_pending_labels(ast):
return
__DEBUG__("Checking pending calls", 1)
if not src.api.check.check_pending_calls():
return
data_ast = make_sentence(p.lexer.lineno, "BLOCK")
# Appends variable declarations at the end.
for var in SYMBOL_TABLE.vars_:
data_ast.append_child(make_var_declaration(var))
# Appends arrays declarations at the end.
for var in SYMBOL_TABLE.arrays:
data_ast.append_child(make_array_declaration(var))
def p_program_program_line(p):
"""program : program_line"""
p[0] = make_block(p[1], make_break(p.lineno(1), p[1]))
def p_program(p):
"""program : program program_line"""
p[0] = make_block(p[1], p[2], make_break(p.lineno(2), p[2]))
def p_program_line(p):
"""program_line : preproc_line NEWLINE
| label_line NEWLINE
| statements NEWLINE
| statements_co NEWLINE
| co_statements NEWLINE
| co_statements_co NEWLINE
| NEWLINE
"""
p[0] = make_nop() if len(p) == 2 else p[1]
def p_co_statements_co(p):
"""co_statements_co : co_statements CO
| co_statements_co CO
| CO
"""
p[0] = p[1] if len(p) == 3 else make_nop()
def p_co_statements(p):
"""co_statements : co_statements_co statement"""
p[0] = make_block(p[1], p[2])
def p_statements_co(p):
"""statements_co : statements CO
| statements_co CO
"""
p[0] = p[1]
def p_statements_statement(p):
"""statements : statement
| statements_co statement
"""
if len(p) == 2:
p[0] = make_block(p[1])
else:
p[0] = make_block(p[1], p[2])
def p_var_decls(p):
"""statement : var_decl"""
p[0] = p[1]
def p_label(p):
"""label : LABEL"""
p[0] = make_label(p[1], p.lineno(1))
def p_program_line_label(p):
"""label_line : label statements
| label co_statements
"""
lbl = p[1]
p[0] = make_block(lbl, p[2]) if len(p) == 3 else lbl
def p_label_line_label_line_co(p):
"""label_line : label_line_co"""
p[0] = p[1]
def p_label_line_co(p):
"""label_line_co : label statements_co %prec CO
| label co_statements_co %prec CO
| label %prec CO
"""
lbl = p[1]
p[0] = make_block(lbl, p[2]) if len(p) == 3 else lbl
def p_program_line_co(p):
"""program_co : program %prec CO
| program label_line_co
| program co_statements_co %prec CO
| program statements_co %prec CO
"""
p[0] = p[1] if len(p) == 2 else make_block(p[1], p[2])
def p_var_decl(p):
"""var_decl : DIM idlist typedef"""
for vardata in p[2]:
SYMBOL_TABLE.declare_variable(vardata[0], vardata[1], p[3])
p[0] = None # Variable declarations are made at the end of parsing
def p_var_decl_at(p):
"""var_decl : DIM idlist typedef AT expr"""
p[0] = None
if p[2] is None or p[3] is None or p[5] is None:
return
if len(p[2]) != 1:
error(p.lineno(1), "Only one variable at a time can be declared this way")
return
idlist = p[2][0]
entry = SYMBOL_TABLE.declare_variable(idlist[0], idlist[1], p[3])
if entry is None:
return
if p[5].token == "CONSTEXPR":
tmp = p[5].expr
entry.addr = tmp
elif not is_static(p[5]):
errmsg.syntax_error_address_must_be_constant(p.lineno(4))
return
else:
entry.addr = make_typecast(_TYPE(gl.PTR_TYPE), p[5], p.lineno(4))
mark_entry_as_accessed(entry)
if entry.scope == SCOPE.local:
SYMBOL_TABLE.make_static(entry.name)
def p_var_decl_ini(p):
"""var_decl : DIM idlist typedef EQ expr
| CONST idlist typedef EQ expr
"""
p[0] = None
keyword, idlist, typedef, expr = p[1], p[2], p[3], p[5]
if len(idlist) != 1:
error(p.lineno(1), "Initialized variables must be declared one by one.")
return
if expr is None:
return
if is_static(expr) and isinstance(expr, sym.UNARY):
expr = make_constexpr(p.lineno(4), expr) # Delayed constant evaluation
if typedef.implicit:
typedef = sym.TYPEREF(expr.type_, p.lexer.lineno, implicit=True)
value = make_typecast(typedef.type_, expr, p.lineno(4))
defval = value if is_static(expr) and value.type_ != Type.string else None
if keyword == "DIM":
SYMBOL_TABLE.declare_variable(idlist[0].name, idlist[0].lineno, typedef, default_value=defval)
else:
# keyword == "CONST"
if defval is None:
if not is_static_str(value):
errmsg.syntax_error_not_constant(p.lineno(4))
return
defval = value
SYMBOL_TABLE.declare_const(idlist[0].name, idlist[0].lineno, typedef, default_value=defval)
if defval is None: # Okay do a delayed initialization
p[0] = make_sentence(
p.lineno(1),
"LET",
SYMBOL_TABLE.access_var(idlist[0].name, p.lineno(1)),
value,
)
def p_singleid(p):
"""singleid : ID
| ARRAY_ID
"""
p[0] = Id(name=p[1], lineno=p.lineno(1))
def p_idlist_id(p):
"""idlist : singleid"""
p[0] = [p[1]]
def p_idlist_idlist_id(p):
"""idlist : idlist COMMA singleid"""
p[1].append(p[3])
p[0] = p[1]
def p_arr_decl(p):
"""var_decl : var_arr_decl
| var_arr_decl_addr
"""
p[0] = None
def p_arr_decl_attr(p):
"""var_arr_decl_addr : var_arr_decl AT expr"""
arr_decl, expr = p[1], p[3]
if arr_decl is None or expr is None:
p[0] = None
return
if expr.token == "CONSTEXPR":
expr = expr.expr
if expr.token == "UNARY" and expr.operator == "ADDRESS": # Must be an ID
if expr.operand.token == "ARRAYACCESS":
if expr.operand.offset is None:
error(
p.lineno(4),
"Address is not constant. Only constant subscripts are allowed",
)
return
else:
if expr.operand.token not in ("ID", "VAR", "LABEL"):
error(p.lineno(3), "Only addresses of identifiers are allowed")
return
expr.operand.has_address = True
elif not is_static(expr):
errmsg.syntax_error_address_must_be_constant(p.lineno(3))
return
arr_entry = SYMBOL_TABLE.access_array(arr_decl[0], arr_decl[1])
arr_entry.addr = make_typecast(_TYPE(gl.PTR_TYPE), expr, p.lineno(2))
if arr_entry.scope == SCOPE.local:
SYMBOL_TABLE.make_static(arr_entry.name)
p[0] = p[1]
def p_decl_arr(p):
"""var_arr_decl : DIM idlist LP bound_list RP typedef"""
if len(p[2]) != 1:
error(p.lineno(1), "Array declaration only allows one variable name at a time")
else:
id_, lineno = p[2][0]
SYMBOL_TABLE.declare_array(id_, lineno, p[6], p[4])
p[0] = p[2][0]
def p_arr_decl_initialized(p):
"""var_decl : DIM idlist LP bound_list RP typedef RIGHTARROW const_vector
| DIM idlist LP bound_list RP typedef EQ const_vector
"""
def check_bound(boundlist, remaining):
"""Checks if constant vector bounds matches the array one"""
lineno = p.lineno(8)
if not boundlist: # Returns on empty list
if not isinstance(remaining, list):
return True # It's OK :-)
error(
lineno,
"Unexpected extra vector dimensions. It should be %i" % len(remaining),
)
return False
if not isinstance(remaining, list):
error(
lineno,
"Mismatched vector size. Missing %i extra dimension(s)" % len(boundlist),
)
return False
if len(remaining) != boundlist[0].count:
error(
lineno,
"Mismatched vector size. Expected %i elements, got %i." % (boundlist[0].count, len(remaining)),
)
return False # It's wrong. :-(
for row in remaining:
if not check_bound(boundlist[1:], row):
return False
return True
p[0] = None
if p[4] is None or p[6] is None or p[8] is None:
return
if not check_bound(p[4].children, p[8]):
return
id_, lineno = p[2][0]
SYMBOL_TABLE.declare_array(id_, lineno, p[6], p[4], default_value=p[8])
entry = SYMBOL_TABLE.get_entry(id_)
if entry is None:
return
if p[6] == Type.string or entry.type_ == Type.string:
errmsg.syntax_error_cannot_initialize_array_of_type(p.lineno(1), Type.string)
return
def p_bound_list(p):
"""bound_list : bound"""
p[0] = make_bound_list(p[1])
def p_bound_list_bound(p):
"""bound_list : bound_list COMMA bound"""
p[0] = make_bound_list(p[1], p[3])
def p_bound(p):
"""bound : expr"""
p[0] = make_bound(make_number(OPTIONS.array_base, lineno=p.lineno(1)), p[1], p.lexer.lineno)
def p_bound_to_bound(p):
"""bound : expr TO expr"""
p[0] = make_bound(p[1], p[3], p.lineno(2))
def p_const_vector(p):
"""const_vector : LBRACE const_vector_list RBRACE
| LBRACE const_number_list RBRACE
"""
p[0] = p[2]
def p_const_vector_elem_list(p):
"""const_number_list : expr"""
if p[1] is None:
return
if not is_static(p[1]):
if isinstance(p[1], sym.UNARY):
tmp = make_constexpr(p.lineno(1), p[1])
else:
errmsg.syntax_error_not_constant(p.lexer.lineno)
p[0] = None
return
else:
tmp = p[1]
p[0] = [tmp]
def p_const_vector_elem_list_list(p):
"""const_number_list : const_number_list COMMA expr"""
if p[1] is None or p[3] is None:
return
if not is_static(p[3]):
if isinstance(p[3], sym.UNARY):
tmp = make_constexpr(p.lineno(2), p[3])
else:
errmsg.syntax_error_not_constant(p.lineno(2))
p[0] = None
return
else:
tmp = p[3]
if p[1] is not None:
p[1].append(tmp)
p[0] = p[1]
def p_const_vector_list(p):
"""const_vector_list : const_vector"""
p[0] = [p[1]]
def p_const_vector_vector_list(p):
"""const_vector_list : const_vector_list COMMA const_vector"""
if len(p[3]) != len(p[1][0]):
error(p.lineno(2), "All rows must have the same number of elements")
p[0] = None
return
p[0] = p[1] + [p[3]]
def p_staement_func_decl(p):
"""statement : function_declaration"""
p[0] = p[1]
def p_statement_border(p):
"""statement : BORDER expr"""
p[0] = make_sentence(p.lineno(1), "BORDER", make_typecast(Type.ubyte, p[2], p.lineno(1)))
def p_statement_plot(p):
"""statement : PLOT expr COMMA expr"""
p[0] = make_sentence(
p.lineno(1),
"PLOT",
make_typecast(Type.ubyte, p[2], p.lineno(3)),
make_typecast(Type.ubyte, p[4], p.lineno(3)),
)
def p_statement_plot_attr(p):
"""statement : PLOT attr_list expr COMMA expr"""
p[0] = make_sentence(
p.lineno(1),