-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
687 lines (550 loc) · 26.5 KB
/
main.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
"""Interprets pseudocode."""
from sys import argv
from re import findall
from re import compile
from dataclasses import dataclass
@dataclass
class Line:
"""Holds information about a line of pseudocode."""
text: str
index: int
indent: int
@dataclass
class BlockInitiator:
"""Holds information about a block initiator"""
initiator: str = ""
index: int = 0
condition: any = ""
entered_case: bool = False
var: str = ""
stop: any = ""
step: any = ""
def is_in_quotes(string, index):
"""Checks if a char in a string is surrounded by quotes."""
return string[:index].count('"') % 2 == 1
def find_last_non_quoted_string(string, to_find):
"""Finds last occurrence of a substring in a string that isn't surrounded by quotes.
Returns -1 if unsuccesful."""
index = string.rfind(to_find)
while index != -1:
if not is_in_quotes(string, index):
return index
index = string.rfind(to_find, 0, index)
return index
def find_closing_pars(expr : str, open_par, par_type: str = '()'):
"""Returns end index of a bracket pair."""
levels_deep = 1
i = open_par+1
while levels_deep > 0:
if expr[i] == par_type[0]:
levels_deep += 1
elif expr[i] == par_type[1]:
levels_deep -= 1
i += 1
if (i >= len(expr) and levels_deep > 0):
raise SyntaxError("expected '" + par_type[1] + "'")
return i-1
def to_bool(string):
"""Attempts to typecast a string to a boolean."""
if isinstance(string, bool):
return string
if (string == "true" or string == "True"):
return True
if (string == "false" or string == "False"):
return False
raise SyntaxError("expected a boolean value.")
def float_or_bool_or_string(val : str):
"""Attempts to automatically typecast a string."""
try:
try:
return to_bool(val)
except SyntaxError:
return rounded_float(val)
except ValueError:
return val
def var_or_not(val : str, variables : dict):
"""Checks if a string is a variable name. If not, returns a typecasted value of the string."""
if (val[0] == "\"" and val[-1] == "\"") or (val[0] == "'" and val[-1] == "'" and len(val) == 3):
return val[1:-1]
try:
try:
return to_bool(val)
except SyntaxError:
return rounded_float(val)
except Exception as exc:
is_valid_var_name(val)
if variable_is_array(val, validify_var_name=False):
return read_from_array(variables, val)
#else
if val in variables.keys():
return variables[val]
raise SyntaxError("value not assigned.") from exc
def rounded_float(num):
"""Typecasts to a float, rounded to 8 decimal places."""
return round(float(num), 8)
def eval_expression(expr, variables : dict):
"""Evaluates expressions recursively."""
if not isinstance(expr, str):
return expr
expr = expr.strip(' ')
if expr.startswith('nicht '):
return not to_bool(eval_expression(expr[6:], variables))
open_par = expr.find('(')
while open_par != -1:
closing_par = find_closing_pars(expr, open_par, '()')
expr = expr[:open_par] \
+ str(eval_expression(expr[open_par+1:closing_par], variables)) \
+ expr[closing_par+1:]
open_par = expr.find('(')
# handle array accesses
open_square = expr.find('[')
while open_square != -1:
closing_quare = find_closing_pars(expr, open_square, '[]')
expr = expr[:open_square+1] \
+ str(eval_expression(expr[open_square+1:closing_quare], variables)) \
+ expr[closing_quare:]
open_square = expr.find('[', closing_quare)
connector_groups = [[' oder ', ' und '], ['==', '!=', '<', '>', '<=', '>='],
['+', '-'], [' div ', ' mod ', '%', '/', '*'], ['^']]
for group in connector_groups:
last_connector = -1
for connector in group:
last_found = find_last_non_quoted_string(expr, connector)
if last_found >= last_connector:
last_connector = last_found
last_connector_string = connector
if last_connector >= 0:
splits = [expr[:last_connector], expr[last_connector+len(last_connector_string):]]
match (last_connector_string):
case ' und ':
return eval_expression(splits[0], variables) \
and eval_expression(splits[1], variables)
case ' oder ':
return eval_expression(splits[0], variables) \
or eval_expression(splits[1], variables)
case '==':
return eval_expression(splits[0], variables) \
== eval_expression(splits[1], variables)
case '!=':
return eval_expression(splits[0], variables) \
!= eval_expression(splits[1], variables)
case '<':
return eval_expression(splits[0], variables) \
< eval_expression(splits[1], variables)
case '>':
return eval_expression(splits[0], variables) \
> eval_expression(splits[1], variables)
case '<=':
return eval_expression(splits[0], variables) \
<= eval_expression(splits[1], variables)
case '>=':
return eval_expression(splits[0], variables) \
>= eval_expression(splits[1], variables)
case '^':
return eval_expression(splits[0], variables) \
** eval_expression(splits[1], variables)
case ' div ':
return int(eval_expression(splits[0], variables)) \
/ int(eval_expression(splits[1], variables))
case ' mod ' | '%':
return eval_expression(splits[0], variables) \
% eval_expression(splits[1], variables)
case '/':
return eval_expression(splits[0], variables) \
/ eval_expression(splits[1], variables)
case '*':
return eval_expression(splits[0], variables) \
* eval_expression(splits[1], variables)
case '+':
return eval_expression(splits[0], variables) \
+ eval_expression(splits[1], variables)
case '-':
if splits[0] == "":
return -eval_expression(splits[1], variables)
#else
return eval_expression(splits[0], variables) \
- eval_expression(splits[1], variables)
if expr.startswith('sqrt '):
return var_or_not(expr[5:], variables) ** 0.5
return var_or_not(expr, variables)
def get_all_tokens(line : str):
"""Indexes all 'tokens' of a line."""
#remove comments
line_comment_pos = line.find('//')
if line_comment_pos != -1:
line = line[:line_comment_pos]
line_comment_pos = line.find('//')
block_comment_start_pos = line.find('/*')
while block_comment_start_pos != -1:
line = line[:block_comment_start_pos] + line[line.find('*/')+2:]
block_comment_start_pos = line.find('/*')
tokens = []
in_quotations = False
split_line = []
last_append_index = 0
for (i, char) in enumerate(line):
if char == "\"":
in_quotations = not in_quotations
if (not in_quotations and char == " ") or i == len(line)-1:
to_append = line[last_append_index:i+1].strip(" ")
if to_append != "":
split_line.append(to_append)
last_append_index = i+1
for token in split_line:
#turn "foo<=bar>=baz[g]" into ["foo", "<", "=", "bar", ">", "=", "baz", "[", "g", "]"]
i = 0
in_quotations = False
while i < len(token):
if token[i] == "\"":
in_quotations = not in_quotations
if not in_quotations:
if (token[i] in ['<', '>', '=', '!', '[', ']']):
if token[:i] != '':
tokens.append(token[:i])
tokens.append(token[i])
token = token[i+1:]
i = -1
i += 1
if token != '':
tokens.append(token)
return tokens
def is_valid_var_name(string):
"""Checks if a variable name breaks conventions."""
if variable_is_array(string):
return
for (i, char) in enumerate(string.lower()):
if ((char < 'a' or char > 'z') and (char < '0' or char > '9') and char != '_')\
or (i == 0 and char >= '0' and char <= '9'):
raise SyntaxError(f"'{string}' is not a valid variable name.")
def get_indent_step(lines):
"""Gets amount of spaces per indent in the input file."""
for line in lines:
if line.indent > 0:
return line.indent
return 0
def better_join(elems : list, char : chr):
"""To be used instead of str.join()"""
out = ""
for (i, elem) in enumerate(elems):
out += elem
if (i >= len(elems)-1 or (elem + elems[i+1] not in ['<=', '>=', '!=', '=='])):
out += char
return out
def indent_of_last_key(block_initiators : dict, key_str : str):
"""Returns indent of most recent block initiator key."""
last_indent = -1
for key in block_initiators.keys():
if block_initiators[key].initiator == key_str:
last_indent = key
return last_indent
def variable_is_array(token: str, validify_var_name: bool = True):
"""Checks if a variable is an array"""
brackets_open = token.find("[")
brackets_close = token.rfind("]")
if brackets_open == -1:
return False
if brackets_close != len(token)-1:
raise SyntaxError("Expected closing brackets ']'")
if validify_var_name:
if token[brackets_open-1] == " ": is_valid_var_name(token[:brackets_open-1])
else: is_valid_var_name(token[:brackets_open])
return True
def dynamic_array_address_translation(var_name: str, variables: dict):
"""
Takes an array address of the form \"foo[123]\" and separates it into its parts.
If the index is an expression it evaluates it.
Returns a dictionary of the form:
{
"stripped_var_name": "foo"
"index": 123
}
"""
opening_brackets = var_name.find('[')
closing_brackets = var_name.rfind(']')
var_name_without_brackets = var_name[:opening_brackets].strip()
inside_brackets = var_name[opening_brackets+1:closing_brackets]
index = int(eval_expression(inside_brackets, variables))
return {
"stripped_var_name": var_name_without_brackets,
"index": index
}
def assign_to_array(variables: dict, var_name: str, value: any):
"""Assigns a value to an array."""
address_parts = dynamic_array_address_translation(var_name, variables)
if address_parts["stripped_var_name"] not in variables:
variables[address_parts["stripped_var_name"]] = {}
variables[address_parts["stripped_var_name"]][address_parts["index"]] = eval_expression(value, variables)
def read_from_array(variables: dict, var_name: str):
"""Gets a value from an array."""
address_parts = dynamic_array_address_translation(var_name, variables)
if address_parts["stripped_var_name"] not in variables or address_parts["index"] not in variables[address_parts["stripped_var_name"]]:
raise SyntaxError("Value not assigned.")
return variables[address_parts["stripped_var_name"]][address_parts["index"]]
def main_thread(lines):
"""Function to handle interpretation of input file."""
variables = {}
block_initiators = {}
output = ""
indent_step = get_indent_step(lines)
max_indent = 0
line_index = 0
try:
while True:
while line_index < len(lines):
line = lines[line_index]
tokens = get_all_tokens(line.text)
if (len(tokens) == 0 or line.indent > max_indent):
line_index += 1
continue
if line.indent < max_indent:
begin_indent = max(indent_of_last_key(block_initiators, "solange")
, indent_of_last_key(block_initiators, "für"))
if (tokens[0] != "solange" and tokens != ["wiederhole"]) \
or begin_indent >= line.indent:
if begin_indent > -1:
if (line.indent <= begin_indent \
and line_index > block_initiators[begin_indent].index):
line_index = block_initiators[begin_indent].index
continue
max_indent = line.indent
for key in list(block_initiators.keys()):
if key > max_indent:
block_initiators.pop(key)
#get index of token that ends with a colon, if there is one
colon_index = -1
i = 0
while i < len(tokens):
if tokens[i].endswith(':'):
colon_index = i
i += 1
index = 1
after_text = False
match (tokens[0]):
case "lies":
tokens[1:] = ''.join(tokens[1:]).split(',')
while index < len(tokens):
is_valid_var_name(tokens[index])
value = float_or_bool_or_string((input(
"Enter a value for " + tokens[index] + ": ")))
if variable_is_array(tokens[index], validify_var_name=False):
assign_to_array(variables, tokens[index], value)
else:
variables[tokens[index]] = value
temp_out = value
if isinstance(temp_out, float):
if int(temp_out) == temp_out:
temp_out = int(temp_out)
else:
temp_out = round(temp_out, 8)
output += f"Enter a value for {tokens[index]}: {temp_out}\n"
index += 1
case "schreibe":
tokens[1:] = findall(r'(?:[^,"]|"[^"]*")+', better_join(tokens[1:], " "))
while index < len(tokens):
tokens[index] = tokens[index].strip()
if (tokens[index].startswith("\"") and tokens[index].endswith("\"")):
temp_out = tokens[index][1:-1].replace("\\n", "\n")
output += temp_out
print(temp_out, end="")
after_text = True
else:
temp_out = eval_expression(tokens[index], variables)
if isinstance(temp_out, float):
if int(temp_out) == temp_out:
temp_out = int(temp_out)
else:
temp_out = round(temp_out, 8)
if after_text:
output += str(temp_out)
print(str(temp_out), end="")
after_text = False
else:
temp_out = f"The value of '{tokens[index]}' is \"{temp_out}\"\n"
output += temp_out
print(temp_out, end="")
index += 1
case "falls":
condition = eval_expression(better_join(tokens[1:], ' '), variables)
block_initiators[line.indent] = \
BlockInitiator(initiator="falls",condition=condition,entered_case=False)
max_indent += indent_step
case "dann":
if ((not line.indent - indent_step in block_initiators) or \
block_initiators[line.indent - indent_step].initiator != "falls"):
raise SyntaxError("expected 'falls' before 'dann'.")
if len(tokens) > 1:
lines.insert(\
line_index+1,\
Line(\
better_join(tokens[1:],' '),line.index,line.indent+indent_step\
)\
)
lines[line_index].text = (' ' * line.indent) + tokens[0]
if block_initiators[line.indent - indent_step].condition:
max_indent += indent_step
else:
#find next 'sonst' at the correct indent, otherwise move to end
i = line_index
while (\
i < len(lines) and\
len(lines[i].text) - len(lines[i].text.lstrip(' ')) >= line.indent\
):
if lines[i].text.lstrip(" ").startswith("sonst"):
break
i += 1
line_index = i-1
case "sonst":
if (not line.indent - indent_step in block_initiators) or\
block_initiators[line.indent - indent_step].initiator != "falls":
raise SyntaxError("expected 'falls' before 'sonst'.")
if len(tokens) > 1:
lines.insert(\
line_index+1,\
Line(better_join(tokens[1:], ' '),\
line.index,\
line.indent + indent_step)\
)
line.text = (' ' * line.indent) + tokens[0]
if not block_initiators[line.indent - indent_step].condition:
max_indent += indent_step
case other if colon_index != -1: #case
if (not line.indent - indent_step in block_initiators) or\
block_initiators[line.indent - indent_step].initiator != "falls":
raise SyntaxError("expected 'falls' before case.")
initiator = block_initiators[line.indent - indent_step]
if len(tokens) > 1:
lines.insert(line_index+1,\
Line(better_join(tokens[colon_index+1:], ' '),\
line.index,\
line.indent + indent_step))
line.text = (' '*line.indent) + better_join(tokens[:colon_index+1], ' ')
tokens = get_all_tokens(line.text)
expression = [tokens[i] for i in range(len(tokens)-1)]
expression.append(tokens[-1][:-1])
sonst = False
if tokens[0] == "sonst:":
if initiator.entered_case:
line_index += 1
continue
sonst = True
if sonst or initiator.condition == \
eval_expression(better_join(expression, ' '), variables):
max_indent += indent_step
initiator.entered_case = True
case "solange":
if tokens[-1] == "wiederhole":
expression = better_join(tokens[1:-1], ' ')
else:
expression = better_join(tokens[1:], ' ')
condition = eval_expression(expression, variables)
if tokens[-1] != "wiederhole":
if block_initiators[line.indent].initiator != "wiederhole":
raise SyntaxError("expected 'wiederhole' at the end of the line.")
if condition:
line_index = block_initiators[line.indent].index
max_indent -= indent_step
continue
if condition:
block_initiators[line.indent] = BlockInitiator(\
initiator="solange",\
condition=condition,\
index=line_index)
max_indent += indent_step
elif line.indent in block_initiators:
block_initiators.pop(line.indent)
case "wiederhole":
max_indent += indent_step
block_initiators[line.indent] = \
BlockInitiator(initiator="wiederhole", index=line_index)
case "für":
#only do this the first time
if line.indent not in block_initiators or block_initiators[line.indent].initiator == "falls":
if tokens[-1] != "wiederhole":
raise SyntaxError("expected 'wiederhole' at the end of the line.")
if len(tokens) < 3:
raise SyntaxError("expected variable after 'für'.")
var = tokens[1]
if (len(tokens) < 4 or tokens[2] != 'von'):
raise SyntaxError("expected 'von' after variable.")
if "bis" not in tokens:
raise SyntaxError("expected 'bis' after value.")
bis_index = tokens.index('bis')
start = tokens[3:bis_index]
if len(start) < 1:
raise SyntaxError("expected a start value.")
variables[var] = eval_expression(better_join(start, ' '), variables)
if "mit" in tokens:
mit_index = tokens.index("mit")
else:
mit_index = -1
stop = tokens[bis_index+1:mit_index]
if len(stop) < 1:
raise SyntaxError("expected a stop value.")
if mit_index != -1:
step = tokens[mit_index+1:-1]
else:
step = ["1"]
block_initiators[line.indent] = BlockInitiator(\
initiator="für",var=var, stop=stop, step=step, index=line_index)
#on repeats
else:
variables[block_initiators[line.indent].var] += \
eval_expression(\
better_join(block_initiators[line.indent].step, ' '), variables\
)
if variables[block_initiators[line.indent].var] <= \
eval_expression(\
better_join(block_initiators[line.indent].stop, ' '), variables\
):
max_indent = line.indent + indent_step
else:
block_initiators.pop(line.indent)
case other if len(tokens) > 1 and tokens[1].strip() == '=': # regular assignment
is_valid_var_name(tokens[0])
variables[tokens[0]]=eval_expression(better_join(tokens[2:],' '),variables)
case other if len(tokens) > 4 and tokens[1].strip() == '[' and '=' in tokens[2:]: # array assingment
equals_index = tokens.index('=')
closing_squares_index = equals_index-1
if tokens[closing_squares_index] != ']':
raise SyntaxError("Expected ']', not '" + tokens[closing_squares_index] + "'.")
assign_to_array(variables, better_join(tokens[:equals_index],' '), better_join(tokens[equals_index+1:],' '))
case other:
raise SyntaxError("Couldn't parse line.")
line_index += 1
if sum([l.initiator for l in block_initiators.values()].count(s) \
for s in ("solange", "für")) > 0:
begin_indent = max(indent_of_last_key(block_initiators, "solange"),\
indent_of_last_key(block_initiators, "für"))
line_index = block_initiators[begin_indent].index
continue
#else
break
except SyntaxError as error:
temp_out = f"Line {line.index}: {error}"
print(temp_out)
output += temp_out
return output
return output
def main(in_filename: str = "in.txt"):
"""main()"""
with open(in_filename, 'r', encoding="UTF-8") as in_file,\
open("out.txt", 'w', encoding="UTF-8") as out_file:
all_lines = []
i = 1
for line in in_file:
line = line.rstrip('\n').rstrip(' ')
indent = len(line) - len(line.lstrip(' \t'))
line = line[indent:]
if line.endswith(';'):
line = line[:-1]
if line != "":
all_lines.append(Line(line, i, indent))
i += 1
output_text = main_thread(all_lines)
out_file.write(output_text)
out_file.close()
if __name__ == "__main__":
if len(argv) > 1:
main(argv[1])
else:
main()