-
Notifications
You must be signed in to change notification settings - Fork 1
/
badig.py
2042 lines (1549 loc) · 68.8 KB
/
badig.py
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
'''
Basic Dignified
v2.0
A modern take on 8 bit classic Basics
Support for any classic Basic though description modules
Copyright (C) 2018-2022 - Fred Rique (farique)
https://github.com/farique1/basic-dignified
The complete suite includes:
Syntax Highlight, Theme, Build System, Comment Preference and Auto Completion
for Sublime Text 3 and 4
Tokenizers for some systems.
Basic DignifieR
Convert classic Basic to Dignified format
badig.py <source> <destination> [args...]
badig.py -h for help.
'''
# Standard libraries
import re
import sys
import time
import os.path
from collections import namedtuple, defaultdict
# Custom modules
from support.helper import IO
from support.helper import Infolog
from support.badig_settings import Settings
# if coming from a module
# pass the file name as argument to the init() method
# Badig is not being called by a module anymore
# But it is left here in case it's needed
external = None
if __name__ != '__main__':
external = [os.path.basename(sys.argv[1])]
# Initialize settings
stg = Settings()
stg.init(external)
# Classic modules
Classic = stg.Classic
Tools = stg.Tools
# Dignified module
Dignified = stg.Dignified
# Initlalize Infolog
infolog = Infolog()
# Apply verbose
infolog.level = stg.verbose_level
# Convert information to the logger module format -----------------------------
class Info():
'''Convert the information to the infolog module and send it
lvl = Message level
desc = Message description
tok = Current token being addressed
bullet = Bullet format override
show_file = Show filename on the message'''
def log(lvl, desc, tok=None, bullet=None, show_file=False):
if tok:
data_pack = namedtuple('data_pack', 'lin col offset text file')
tok = data_pack(tok.pos.lin,
tok.pos.col,
tok.pos.offset,
tok.pos.text,
tok.pos.file)
infolog.log(lvl, desc, tok, bullet, show_file)
# Language descriptions -------------------------------------------------------
class Description(Dignified.Description, Classic.Description):
'''Describes the classic and dignified versions of Basic
Mix Dignified and Classic modules and adds global descriptions'''
def __init__(self):
super(Description, self).__init__()
# General
self.tab = r'\t'
self.space = r'\s'
self.newline = r'\r'
self.newline_str = '\r'
self.newline_classic = '\r\n'
if stg.CURRENT_SYSTEM == 'WINDOWS':
self.newline_str_n = '\n'
else:
self.newline_str_n = '\r'
# General groups
# Badig now adds the EOF token by finding the last coded line
# Check if nothing else is broken then delete these lines
# m_eof = r'^EOF$'
m_newline = r'^\r+$'
m_spaces = r'^[^\S\r\n]$'
# Regex groups
# main_eof = fr'(?P<eof>{m_eof})'
main_new = fr'(?P<newline>{m_newline})'
main_spc = fr'(?P<spaces>{m_spaces})'
# Groups assembled for compiling (Order is important)
self.main_groups = (''
# Badig now adds the EOF token by finding the last coded line
# Check if nothing else is broken then delete these lines
# fr'{main_eof}|'
fr'{main_new}|'
fr'{main_spc}')
# Compiling all groups (Order is important)
self.commands = re.compile(''
fr'{self.main_groups}|'
fr'{self.dignified_groups}|'
fr'{self.classic_groups}|'
fr'{self.d_idnttp}',
re.I)
def join_commands(self, *args):
'''Join list items with individual regex terminators'''
l = []
[l.extend(a) for a in args]
l = r'$|^'.join(l)
return fr'(^{l}$)'
# Token -----------------------------------------------------------------------
class Token:
'''Define and creates the token object
tok = Token type
val = Token value
pos = Position object'''
def __init__(self, tok='', val=None, pos=None):
self.tok = tok
self.val = val
self.pos = pos
self.c_idnttp_grp = Description().c_idnttp_grp
if self.tok:
self.tok = self.tok.upper()
@property
def uval(self):
'''Create an uppercase value'''
return str(self.val).upper()
@property
def lval(self):
'''Create a lowercase value'''
return str(self.val).lower()
@property
def var_name(self):
'''Give variable identifier'''
g = re.match(self.c_idnttp_grp, self.val)
var_name = g.group(1)
return str(var_name).lower()
@property
def val_w_file(self):
'''Give variable + file name'''
val_w_file = self.var_name
val_w_file += f'@{self.pos.file}'
return str(val_w_file).lower()
@property
def var_type(self):
'''Give variable type'''
g = re.match(self.c_idnttp_grp, self.val)
var_type = g.group(2)
return str(var_type).lower()
def copy(self):
'''Make a copy of the object'''
return Token(self.tok, val=self.val, pos=self.pos.copy())
def __repr__(self):
'''Nicer way of representing the object information'''
# 1 show the file, 0 hide it
file = '' if 1 else f' --------- {os.path.basename(self.pos.file)}'
return (''
f'{self.pos.lin:02} | '
f'{self.pos.col:02} | '
f'{self.tok} | '
f'{repr(str(self.val))[1:-1]}'
f'{file}')
# Position --------------------------------------------------------------------
class Position:
'''Define and create the positional information object for the token
d_code = The code listing
lin = Line position
col = Column position
offset = Amount to compensate for leading spaces
when displaying the position glyph on error messages'''
def __init__(self, d_code, lin=0, col=0, offset=0):
self.lin = lin
self.col = col + 1 # Columns start with 1, not 0
self.d_code = d_code
self.offset = offset
self.text = d_code[self.lin].text
self.file = d_code[self.lin].file
self.code_len = len(d_code)
def __repr__(self):
'''Nicer way for representing the object information'''
return (f'{self.lin:02} | '
f'{self.col:02} | '
f'{self.text.rstrip()} | '
f'{self.file} | '
f'{self.code_len}')
def copy(self, d_code=None, lin=None, col=None, offset=None):
'''Makes a copy of the object'''
lin = self.lin if lin is None else lin
col = self.col if col is None else col
lead_spc = (len(self.text) - len(self.text.lstrip()))
offset = lead_spc if offset is None else offset
d_code = self.d_code if d_code is None else d_code
return Position(d_code=d_code, lin=lin, col=col, offset=offset)
# Lexer -----------------------------------------------------------------------
class Lexer:
'''Scanner to read the text file and create the tokens
stg = Settings object
d_code = File to process'''
def __init__(self, stg, d_code):
self.d_code = d_code
# This is jerry rigged to repeat the last line
# because the advance(), advance_line(), and get_token()
# functions are ignoring the last one when addinf the EOF token
self.d_code.append(d_code[:-1][0])
self.stg = stg
self.des = Description()
self.pos = Position(d_code, lin=0, col=-1)
# Run classic module lexer initialization
self.clc = Classic.Lexer(self, self.stg, Token)
self.clc.initialization()
# General -----------------------------------------------------------------
def advance(self):
'''Read the current character and advance the cursor
Returning None means the end of the program'''
current_char = self.pos.text[self.pos.col]
self.pos.col += 1
if self.pos.col >= len(self.pos.text):
advanced = self.advance_line()
if advanced is None:
return None
return current_char
def advance_line(self):
'''Advance one line and prepare it for processing
Returning None means the end of the program'''
self.pos.lin += 1
self.pos.col = 0
nl = self.des.newline_str
if self.pos.lin <= self.pos.code_len - 1:
self.pos.text = self.d_code[self.pos.lin].text.rstrip() + nl
return self.pos.text
else:
return None
def lookahead(self):
'''Look at the current character without advancing'''
return self.pos.text[self.pos.col]
def get_token(self):
'''Makes a token based on the word or character matched.
Get characters until no match is found
then uses the last positive match
If end of program reached, return the EOF token'''
partial = ''
match_group = ''
last_pos = self.pos.copy()
while True:
next_char = self.lookahead()
g = self.des.commands.match(partial + next_char)
if not g:
if not partial:
match_group = None
partial = next_char
return Token(tok=match_group,
val=partial.strip(' '),
pos=last_pos)
advanced = self.advance()
if advanced is None:
return Token(tok='EOF',
val='EOF',
pos=last_pos)
partial += advanced
match_group = g.lastgroup
# Literals ----------------------------------------------------------------
def get_lit_block(self, tk):
'''Get a classic comment block
tk = Initial token'''
partial = ''
rem_block = [tk]
val_len = len(tk.val)
nl = self.des.newline
nls = self.des.newline_str
if not self.pos.text[self.pos.col + 1:]:
self.advance_line()
self.pos.col -= 1
last_pos_lit = self.pos.copy(col=max(self.pos.col, 0))
while True:
partial += self.advance()
next_char = self.lookahead()
last_pos_close = self.pos.copy(col=self.pos.col - (val_len))
if re.match(nl, next_char):
g = re.match(tk.val, partial[-val_len:])
if g:
partial = partial[:-val_len]
partial = partial.strip(nls)
# if not alone in a line with a comment block indicator
if not (not partial[:-val_len].strip() and g):
rem_block.append(Token(tok='C_LIBREM',
val=partial,
pos=last_pos_lit))
if g:
rem_block.append(Token(tok='C_C_BREM',
val=tk.val,
pos=last_pos_close))
break
if self.pos.lin + 1 >= self.pos.code_len:
return None
last_pos_lit = self.pos.copy(lin=self.pos.lin + 1, col=0)
partial = ''
if tk.tok == 'D_O_EREM':
rem_block = []
return rem_block
def get_lit_line(self, tok, end, part, l_pos):
'''Get a literal line of type depending on passed arguments
tok: Token of the matched literal
end: A character to end the capture
part: First part of the literal string
l_pos: Start position of the string'''
nl = self.des.newline
nls = self.des.newline_str
if self.lookahead() == nls:
return None
while True:
last_chr = self.advance()
part += last_chr
next_chr = self.lookahead()
g = re.match(fr'{end}|{nl}', next_chr)
if g:
if g.group() != nls:
part = part + self.advance()
break
return Token(tok=tok,
val=part,
pos=l_pos)
# Process -----------------------------------------------------------------
def lex(self):
'''Go through the code, get the tokens, adjust them and outputs a list'''
# Create the token list header
self.tk = Token('NEWLINE', self.des.newline_str, self.pos.copy())
self.lexer = [Token('PROGRAM', 'PROGRAM', self.pos.copy()), self.tk]
self.last_tok = self.tk
self.advance_line()
while True:
self.last_tok = self.lexer[-1]
self.tk = self.get_token()
if not self.tk.val:
continue
# Errors ----------------------------------------------------------
# Character not recognized at that location
if not self.tk.tok:
Info.log(1, f'Character not recognized in this context: '
f'{self.tk.val}', self.tk)
# Unfinished part of potential matches
elif self.tk.tok == 'C_PARTLS' or self.tk.tok == 'D_PARTLS':
Info.log(1, f'Token incomplete: {self.tk.val}', self.tk)
# Fix toggle rems not at the start of a line
# convert to correct tokens of # and ident/number
if self.tk.tok == 'D_TGLREM' \
and self.lexer[-1].tok != 'NEWLINE' \
and self.lexer[-1].tok != 'D_TGLREM' \
and self.lexer[-1].tok != 'D_INSTRC':
g = re.match(self.des.d_togremchk, self.tk.val)
tok = self.des.commands.match(g.group(1))
self.lexer.append(Token(tok=tok.lastgroup,
val=g.group(1),
pos=self.pos.copy()))
tok = self.des.commands.match(g.group(2))
self.tk = (Token(tok=tok.lastgroup,
val=g.group(2),
pos=self.pos.copy()))
# Literal blocks --------------------------------------------------
elif (self.tk.tok == 'C_O_BREM' or self.tk.tok == 'D_O_EREM') \
and self.last_tok.tok == 'NEWLINE':
last_tok = self.tk.copy()
rem_block = self.get_lit_block(self.tk)
if rem_block is None:
Info.log(1, f'Block not closed from: {self.tk.val}', last_tok)
self.lexer.extend(rem_block)
continue
# Literal lines ---------------------------------------------------
# Dignified exclusive rems
elif self.tk.tok == 'D_LINREM':
self.pos.col = len(self.pos.text) - 1
continue
# Classic line rems (comment block indicator not at the start of a line)
elif self.tk.tok == 'C_O_BREM' and self.last_tok.tok != 'NEWLINE':
self.lexer.append(Token(tok='C_LINREM',
val=self.des.c_altrem,
pos=self.pos.copy(col=self.pos.col - 2)))
self.tk = self.get_lit_line(tok='C_LITREM',
end=self.des.newline,
part=self.des.c_altrem,
l_pos=self.pos.copy(col=self.pos.col - 1))
# Classic line rems
elif self.tk.tok == 'C_LINREM':
self.lexer.append(self.tk)
lit_rem = self.get_lit_line(tok='C_LITREM',
end=self.des.newline,
part='',
l_pos=self.pos.copy(col=self.pos.col))
if not lit_rem:
continue
self.tk = lit_rem
# Quotes
elif self.tk.tok == 'C_QUOTES':
self.pos.col -= 1
self.tk = self.get_lit_line(tok='C_LITQUO',
end=self.des.c_quotes,
part='',
l_pos=self.pos.copy(col=self.pos.col))
# Classic module functions ----------------------------------------
# Lex functions on the classic module
# and deal with their response
else:
ctk = self.clc.lexing()
if ctk is None:
continue
elif ctk:
self.tk = ctk
# Create list -----------------------------------------------------
self.lexer.append(self.tk)
# EOF -------------------------------------------------------------
if self.tk.tok == 'EOF':
break
return self.lexer
# Parser ----------------------------------------------------------------------
class Parser:
'''Process the list of tokens sent by the lexer
stg = Setings object
lexed = List of tokens
des = Language description object
short_vars = List of short named vars used
(prevent conflict on included files)'''
def __init__(self, stg, lexed, des, include_vars):
self.tok_list_in = lexed
self.stg = stg
self.reset_pass()
self.des = des
self.des.c_hard_short_vars.update(include_vars[0])
self.des.c_hard_long_vars.update(include_vars[1])
self.des.d_declares.update(include_vars[2])
# Run initialization on the classic module
self.clc = Classic.Parser(self, stg, Token)
self.clc.initialization()
def reset_pass(self):
'''Reset the variables to prepare for another pass at the token list'''
self.len = len(self.tok_list_in)
self.index = 0
self.tk = self.tok_list_in[0]
self.tk.pos.lin = 0
self.tk.pos.col = 1
self.tok_list_out = [self.tk]
def next_tok(self):
'''Advance and get the next token on the token list'''
if self.index + 1 <= self.len:
self.index += 1
self.tk = self.tok_list_in[self.index]
return self.tk
def prev_tok(self):
'''Recede and get the previous token on the token list'''
if self.index - 1 > 0:
self.index -= 1
self.tk = self.tok_list_in[self.index]
return self.tk
def peek_ahead(self, offset=1):
'''Get the next token in the input list without advancing'''
return self.tok_list_in[self.index + offset]
def last_tok(self, offset=-1):
'''Get the last token on the output list'''
return self.tok_list_out[offset]
# Defines -----------------------------------------------------------------
def get_defines(self):
'''Get the defines definitions'''
do = self.des.d_defdop
dc = self.des.d_defdcl
se = self.des.d_defsep
def_grp = namedtuple('def_grp', 'repl varv')
while True:
self.next_tok()
def_def = self.get_in_bracket(f'{do}{dc}')
if not def_def:
self.prev_tok()
Info.log(1, f'Define definition blank.', self.tk)
if not re.match(self.des.d_identf, def_def.val):
Info.log(1, f'Invalid define name: {def_def.val}', def_def)
def_var = None
def_rep = self.get_defined_content(f'{do}{dc}', 2)
if def_rep[1]:
def_var = def_rep[1][0][0]
def_rep = def_rep[0]
if def_def.lval in self.des.d_defines:
Info.log(1, f'Define name duplicated: {def_def.val}', def_def)
self.des.d_defines[def_def.lval] = (def_grp(def_rep, def_var))
tk = self.next_tok()
if tk.val != se:
if tk.tok != 'NEWLINE':
Info.log(1, f'Expecting: {se}', self.tk)
break
def get_defined_content(self, delim, recur=1):
'''Get the content of the defined define and its variable if any
delim = Open and closing characters delimiting the content
recur = Recursions before delimiter character balance error'''
assert len(delim) == 2
do = delim[0]
dc = delim[1]
if self.tk.val != do:
Info.log(1, f'Expecting: {do}', self.tk)
var = []
part = []
balance = [do]
while True:
tk = self.next_tok()
if tk.tok == 'NEWLINE' and balance:
Info.log(1, f'Unbalanced {do}{dc}', self.tk)
elif tk.val == do:
if len(balance) >= recur:
Info.log(1, f'Too many opened "{do}"', self.tk)
balance.append(do)
pos = self.tk.pos
var.append(self.get_defined_content(f'{do}{dc}'))
part.append(Token(tok='D_DEFVAR',
val='VAR',
pos=pos))
self.prev_tok()
continue
elif tk.val == dc:
if not balance:
Info.log(1, f'Too many closed "{dc}"', self.tk)
balance.pop()
if not balance:
return part, var
continue
part.append(tk)
def replace_define(self):
'''Replace the defines for their content throughout the code'''
do = self.des.d_defdop
dc = self.des.d_defdcl
vo = self.des.d_defvop
vc = self.des.d_defvcl
define = []
def_var = []
balance = [vo]
def_def = self.get_in_bracket(f'{do}{dc}')
if not def_def:
Info.log(1, f'Define blank.', self.tk)
if not def_def.lval.replace(self.des.d_idsnake, '').isalnum() \
and def_def.lval != self.des.c_print_alt:
Info.log(1, f'{def_def.val} invalid define name.', def_def)
if def_def.lval not in self.des.d_defines:
Info.log(1, f'{def_def.val} define not defined.', def_def)
if self.tk.tok == 'C_SYMBOL' and self.tk.val == vo:
while True:
tk = self.next_tok()
if tk.tok == 'NEWLINE' and balance:
Info.log(1, f'Missing {vc}', tk)
# If define has variable, recurse it
elif tk.val == do:
def_var.extend(self.replace_define())
continue
elif tk.val == vo:
balance.append(tk.val)
elif tk.val == vc:
balance.pop()
if not balance:
break
def_var.append(tk)
self.next_tok()
insert_var = self.des.d_defines[def_def.lval].varv
if def_var:
insert_var = def_var
for d in self.des.d_defines[def_def.lval].repl:
if d.tok == 'D_DEFVAR':
for v in insert_var:
define.append(v.copy())
continue
d.pos.lin = def_def.pos.lin
d.pos.col = def_def.pos.col
define.append(d.copy())
self.prev_tok()
return define
# Declares ----------------------------------------------------------------
def get_declares(self):
'''Get the declares definitions'''
vc = self.des.c_var_valid_chars
while True:
# Get long variable
dec_long = self.next_tok()
if not re.match(self.des.d_identf, dec_long.lval):
Info.log(1, f'Invalid declared variable: {dec_long.val}', dec_long)
if len(dec_long.lval) == 1:
Info.log(1, f'Declared variable too short: {dec_long.lval}', dec_long)
if dec_long.uval in self.des.c_reserved_kw:
Info.log(1, f'Variable is a reserved keyword: {dec_long.lval}', dec_long)
# If there is no assignment (:)
if self.peek_ahead().val == self.des.d_decsep \
or self.peek_ahead().tok == 'NEWLINE':
for var in self.des.d_declares:
val_n_file = var.split('@')[0]
if dec_long.lval[:vc] == self.des.d_declares[var]:
Info.log(2, f'Declared variable conflict: '
f'{dec_long.lval} '
f'{val_n_file}:{self.des.d_declares[var]}', dec_long)
if dec_long.val_w_file == var:
Info.log(1, f'Long variable already reserved: '
f'{dec_long.lval} '
f'{val_n_file}:{self.des.d_declares[var]}', dec_long)
for var in self.des.c_hard_long_vars:
if dec_long.lval[:vc] == var.var_name[:vc]:
Info.log(2, f'Reserved long variable conflict: '
f'{dec_long.lval} {var.var_name}', dec_long)
for var in self.des.c_hard_short_vars:
if dec_long.lval[:vc] == var:
Info.log(2, f'Reserved short variable conflict: '
f'{dec_long.lval} {var}', dec_long)
if len(dec_long.lval) == vc:
self.des.c_hard_short_vars.update({dec_long.lval})
else:
self.des.c_hard_long_vars.update({dec_long})
if self.peek_ahead().tok == 'NEWLINE':
break
if self.peek_ahead().val == self.des.d_decsep:
self.next_tok()
continue
self.next_tok()
# Get short variable
dec_short = self.next_tok()
if not re.match(self.des.c_varsna, dec_short.lval):
Info.log(1, f'Invalid declared short variable: {dec_short.lval}', dec_short)
for var in self.des.d_declares:
val_n_file = var.split('@')[0]
if dec_long.val_w_file == var:
Info.log(1, f'Long variable already declared: '
f'{dec_long.lval}:{dec_short.lval} '
f'{val_n_file}:{self.des.d_declares[var]}', dec_short)
if dec_short.lval == self.des.d_declares[var]:
Info.log(1, f'Short variable already declared: '
f'{dec_long.lval}:{dec_short.lval} '
f'{val_n_file}:{self.des.d_declares[var]}', dec_short)
for var in self.des.c_hard_long_vars:
if dec_long.val_w_file == var.val_w_file:
Info.log(1, f'Long variable already reserved: '
f'{dec_long.lval}:{dec_short.lval} '
f'{var.lval}', dec_long)
for var in self.des.c_hard_long_vars:
if dec_short.lval == var.var_name[:vc]:
Info.log(2, f'Reserved long variable conflict: '
f'{dec_long.lval}:{dec_short.lval} '
f'{var.var_name}', dec_short)
for var in self.des.c_hard_short_vars:
if dec_short.lval == var:
Info.log(2, f'Reserved short variable conflict: '
f'{dec_long.lval}:{dec_short.lval} '
f'{var}', dec_short)
self.des.d_declares[dec_long.val_w_file] = dec_short.lval
tk = self.next_tok()
if tk.val != self.des.d_decsep:
if tk.tok != 'NEWLINE':
Info.log(1, f'Expecting: {self.des.d_decsep}', self.tk)
break
# Labels ------------------------------------------------------------------
def get_label_lines(self):
'''Get line and loop labels'''
label = None
lo = self.des.d_labdop
lc = self.des.d_labdcl
# line labels
if self.last_tok().tok == 'NEWLINE':
label = self.get_in_bracket(f'{lo}{lc}')
self.prev_tok()
# Loop labels
elif self.last_tok(-2).tok == 'NEWLINE':
label = self.last_tok()
self.loop_labels.append(label)
self.tok_list_out.pop()
if label is None:
Info.log(1, f'Label error.', self.tk)
if not label:
Info.log(1, f'Label blank.', self.tk)
if not re.match(self.des.d_identf, label.val):
Info.log(1, f'Invalid label name: {label.val}', label)
self.tk = Token(tok='D_LBLLIN',
val=label.lval,
pos=self.tk.pos)
def get_jump_labels(self):
'''Get labels on jump instructions'''
lo = self.des.d_labdop
lc = self.des.d_labdcl
goto = self.get_in_bracket(f'{lo}{lc}')
self.prev_tok()
tk_pos = self.peek_ahead(-1).pos
self.tk = Token(tok='D_LBLJMP',
val=goto.lval,
pos=tk_pos)
def get_loop_label_return(self):
'''Get loop labels return'''
if not self.loop_labels:
Info.log(1, f'Loop label close without open.', self.tk)
label = self.loop_labels.pop()
# Add : if } not at the start of a line
if self.last_tok().tok != 'NEWLINE' \
and self.last_tok().tok != 'C_INSTSP':
self.tok_list_out.extend(self.tok_str(self.des.c_instsp_str))
self.tok_list_out.extend(self.tok_str(self.des.c_loop_back))
self.tk = Token(tok='D_LBLRET',
val=label.lval,
pos=self.tk.pos)
def get_labels_exit(self):
'''Get loop labels exit'''
self.tok_list_out.extend(self.tok_str(self.des.c_loop_back))
self.tk = Token(tok='D_LBLEXT',
val=self.loop_labels[-1].lval,
pos=self.tk.pos)
# Helper function ---------------------------------------------------------
def get_in_bracket(self, delim):
'''Get content inside delimiters.
delim: Opening and closing delimiter characters'''
assert len(delim) == 2
do = delim[0]
dc = delim[1]
if self.tk.val != do:
Info.log(1, f'Expecting: {do}', self.tk)
content = self.next_tok()
if content.val == dc:
return ''
if self.next_tok().val != dc:
Info.log(1, f'Closing "{dc}" not found.', self.tk)
self.next_tok()
return content
# Functions ---------------------------------------------------------------
def get_func_def(self):
'''Get function definitions and its arguments'''
fe = self.des.d_funcequal
func = self.next_tok()
if self.in_func:
Info.log(1, f'Already inside a function.', self.in_func)
if func.lval in self.des.d_functions:
Info.log(1, f'Function name duplicated: {func.val}', func)
func_def_args_tmp = self.get_func_args(func)
self.func_def_args = [] # this is the a in: func(a=b)
self.func_def_equl = [] # this is the b in: func(a=b)
for args in func_def_args_tmp:
new_equ = []
new_arg = args
if not args:
Info.log(1, f'Function definition missing argument: '
f'{func.val}', func)
if args[0].tok != 'D_IDNTTP':
Info.log(1, f'Function definition only takes variables: '
f'{args[0].val}', args[0])
if len(args) > 1:
if args[1].val != fe:
Info.log(1, f'Function definition only takes one variable: '
f'{args[1].val}', args[1])
new_arg = [args[0]]
new_equ = args[2:]
self.func_def_args.append(new_arg)
self.func_def_equl.append(new_equ)
if not all(i for i in self.func_def_args):
Info.log(1, f'Empty argument in function definition.', func)
self.tk.pos.col = 1
self.tk = Token(tok='D_FUNCDF',
val=func.lval,
pos=self.tk.pos.copy())
self.in_func = func
def get_func_ret(self):
'''Get function return and its variables'''
ret_tok = []
ret_list = []
last_ret_tok = self.tk
fs = self.des.d_funcsep
ar = self.des.c_altrem