-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgdpy.py
More file actions
1268 lines (1138 loc) · 51.2 KB
/
gdpy.py
File metadata and controls
1268 lines (1138 loc) · 51.2 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
from __future__ import annotations
import ast
import copy
import ctypes
import importlib
import json
import math
import os
import shlex
import shutil
import subprocess
import sys
import time
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any
class GdPyRuntimeError(Exception):
pass
ALIASES: dict[str, tuple[str, ...]] = {
"SAY": ("SAY", "PRINT", "ECHO", "WRITE", "OUT", "TELL", "SHOW", "DISPLAY", "SPEAK"),
"SET": ("SET", "LET", "VAR", "MAKE", "STORE", "PUT", "ASSIGN", "VALUE"),
"DEL": ("DEL", "UNSET", "DROP", "ERASE", "CLEARVAR", "REMOVEVAR"),
"COPY": ("COPY", "CLONE", "DUP", "DUPLICATE", "MIRROR"),
"SWAP": ("SWAP", "EXCHANGE", "FLIP", "ROTATEPAIR"),
"TYPEOF": ("TYPE", "TYPEOF", "KIND", "WHATIS", "VARTYPE"),
"ADD": ("ADD", "PLUS", "INCREASE", "INC", "SUMUP", "BOOST"),
"SUB": ("SUB", "MINUS", "DECREASE", "DEC", "REDUCE", "LOWERBY"),
"MUL": ("MUL", "TIMES", "MULTIPLY", "SCALE", "GROWBY"),
"DIV": ("DIV", "DIVIDE", "SPLITBY", "SHAREBY"),
"MOD": ("MOD", "REM", "REMAINDER"),
"POW": ("POW", "POWER", "EXPONENT"),
"LEN": ("LEN", "LENGTH", "SIZE", "COUNT", "COUNTAS"),
"APPEND": ("APPEND", "PUSH", "ADDITEM", "PUTLAST"),
"EXTEND": ("EXTEND", "MERGE", "CONCATLIST", "JOINLIST"),
"INSERT": ("INSERT", "PUTAT", "ADDAT"),
"REMOVE": ("REMOVE", "TAKEOUT", "DELITEM", "DISCARD"),
"POP": ("POP", "PULL", "TAKEPOP", "LASTOUT"),
"CLEAR": ("CLEAR", "EMPTY", "WIPE", "RESETLIST"),
"SORT": ("SORT", "ORDER", "ARRANGE"),
"REVERSE": ("REVERSE", "FLIPLIST", "BACKWARD"),
"UNIQUE": ("UNIQUE", "DEDUP", "DISTINCT"),
"SPLIT": ("SPLIT", "TOKENS", "CHOP", "WORDSPLIT"),
"JOIN": ("JOIN", "GLUE", "CONCAT", "STITCH"),
"REPLACE": ("REPLACE", "SWAPTEXT", "CHANGE"),
"UPPER": ("UPPER", "CAPS", "BIGTEXT"),
"LOWER": ("LOWER", "SMALL", "LOWTEXT"),
"STRIP": ("STRIP", "TRIM", "CLEAN"),
"READFILE": ("READFILE", "LOADFILE", "OPENFILE", "GETFILE"),
"WRITEFILE": ("WRITEFILE", "SAVEFILE", "CREATEFILE", "PUTFILE"),
"APPENDFILE": ("APPENDFILE", "ADDFILE", "EXTENDFILE"),
"EXISTS": ("EXISTS", "FILEEXISTS", "PATHHAS"),
"MKDIR": ("MKDIR", "CREATEDIR", "NEWDIR"),
"LISTDIR": ("LISTDIR", "DIRFILES", "SHOWDIR", "SCANDIR"),
"READJSON": ("READJSON", "LOADJSON", "OPENJSON"),
"WRITEJSON": ("WRITEJSON", "SAVEJSON", "STOREJSON"),
"IMPORT": ("IMPORT", "USE", "MODULE", "LOADLIB", "REQUIRE"),
"CALL": ("CALL", "INVOKE", "APPLY", "RUNFUNC", "EXECFUNC"),
"SAVE": ("SAVE",),
"SCREENSHOT": ("SCREENSHOT",),
"KILLPID": ("KILLPID",),
"DOGFUNNY": ("DOGFUNNY",),
"LABEL": ("LABEL", "MARK", "TAG", "SIGNPOST"),
"GOTO": ("GOTO", "JUMP", "GO", "MARKTO"),
"IF": ("IF", "WHEN"),
"ELIF": ("ELIF",),
"ELSE": ("ELSE", "OTHERWISE"),
"ENDIF": ("ENDIF", "FI", "ENDWHEN"),
"WHILE": ("WHILE", "LOOPWHILE"),
"ENDWHILE": ("ENDWHILE", "WEND", "LOOPEND"),
"FOR": ("FOR", "EACH", "FOREACH"),
"ENDFOR": ("ENDFOR", "NEXT", "ENDEACH"),
"BREAK": ("BREAK", "STOPLOOP", "LEAVELOOP"),
"CONTINUE": ("CONTINUE", "NEXTLOOP", "SKIPLOOP"),
"ASSERT": ("ASSERT", "ENSURE", "VERIFY", "CHECK"),
"WAIT": ("WAIT", "SLEEP", "PAUSE", "DELAY"),
"ASK": ("ASK", "INPUT", "READ", "PROMPT", "QUESTION"),
"HELP": ("HELP", "COMMANDS", "MANUAL", "DOCS"),
"DUMP": ("DUMP", "VARS", "STATE", "CONTEXT"),
"NOW": ("NOW", "NOWTIME", "TIMENOW"),
"TODAY": ("TODAY", "DATE", "DATEONLY"),
"ERROR": ("ERROR", "ERRORMODE", "ERRORS"),
"RIGHTS": ("RIGHTS", "ADMIN", "ELEVATE"),
"ENTER": ("ENTER", "PAUSEENTER"),
"NOP": ("NOP", "PASS", "REM", "COMMENT", "DO", "SKIP", "NOSTOP"),
"END": ("END", "STOP", "EXIT", "QUIT", "HALT", "FINISH", "CLOSE"),
}
CANONICAL = {alias: name for name, aliases in ALIASES.items() for alias in aliases}
HELP_TEXT: dict[str, str] = {
"SAY": 'SAY "text" | SAY a + b',
"SET": "SET name = expression",
"DEL": "DEL name",
"COPY": "COPY target = expression",
"SWAP": "SWAP left right",
"TYPEOF": "TYPEOF target = expression",
"ADD": "ADD name expression",
"SUB": "SUB name expression",
"MUL": "MUL name expression",
"DIV": "DIV name expression",
"MOD": "MOD name expression",
"POW": "POW name expression",
"LEN": "LEN target = expression",
"APPEND": "APPEND listVar expression",
"EXTEND": "EXTEND listVar expression",
"INSERT": "INSERT listVar index expression",
"REMOVE": "REMOVE listVar expression",
"POP": "POP listVar | POP target = listVar",
"CLEAR": "CLEAR varName",
"SORT": "SORT listVar",
"REVERSE": "REVERSE listVar",
"UNIQUE": "UNIQUE listVar",
"SPLIT": 'SPLIT target = "a,b" BY ","',
"JOIN": 'JOIN target = items BY ", "',
"REPLACE": 'REPLACE target = text OLD "a" NEW "b"',
"UPPER": "UPPER target = expression",
"LOWER": "LOWER target = expression",
"STRIP": "STRIP target = expression",
"READFILE": 'READFILE target = "file.txt"',
"WRITEFILE": 'WRITEFILE "file.txt" WITH expression',
"APPENDFILE": 'APPENDFILE "file.txt" WITH expression',
"EXISTS": 'EXISTS target = "file.txt"',
"MKDIR": 'MKDIR "folder"',
"LISTDIR": 'LISTDIR target = "folder"',
"READJSON": 'READJSON target = "file.json"',
"WRITEJSON": 'WRITEJSON "file.json" WITH expression',
"IMPORT": "IMPORT math | IMPORT random AS rnd",
"CALL": "CALL expression | CALL target = expression",
"SAVE": "SAVE | SAVE file.png",
"SCREENSHOT": "SCREENSHOT | SCREENSHOT SAVE",
"KILLPID": "KILLPID pid",
"DOGFUNNY": "DOGFUNNY",
"LABEL": "LABEL name",
"GOTO": "GOTO labelName",
"IF": "IF expression THEN command | IF expression ... ELSE ... ENDIF",
"ELIF": "ELIF expression | ELSE expression",
"ELSE": "ELSE",
"ENDIF": "ENDIF",
"WHILE": "WHILE expression",
"ENDWHILE": "ENDWHILE",
"FOR": "FOR item IN expression",
"ENDFOR": "ENDFOR",
"BREAK": "BREAK",
"CONTINUE": "CONTINUE",
"ASSERT": "ASSERT expression",
"WAIT": "WAIT expression",
"ASK": 'ASK name "Prompt"',
"HELP": "HELP | HELP SET",
"DUMP": "DUMP",
"NOW": "NOW varName",
"TODAY": "TODAY varName",
"ERROR": "ERROR(on) | ERROR(off)",
"RIGHTS": "RIGHTS(give)",
"ENTER": "ENTER",
"NOP": "NOP",
"END": "END",
}
@dataclass
class Instruction:
line_no: int
raw: str
command: str
args: list[str]
body: str
indent: int
inline_if: bool = False
class SafeEvaluator(ast.NodeVisitor):
def __init__(self, context: dict[str, Any]) -> None:
self.context = context
def evaluate(self, expression: str) -> Any:
try:
tree = ast.parse(expression, mode="eval")
except SyntaxError as error:
raise GdPyRuntimeError(f"Invalid expression '{expression}': {error.msg}.") from error
return self.visit(tree.body)
def visit_Constant(self, node: ast.Constant) -> Any:
return node.value
def visit_Name(self, node: ast.Name) -> Any:
if node.id in self.context:
return self.context[node.id]
raise GdPyRuntimeError(f"Unknown name '{node.id}'.")
def visit_List(self, node: ast.List) -> Any:
return [self.visit(item) for item in node.elts]
def visit_Tuple(self, node: ast.Tuple) -> Any:
return tuple(self.visit(item) for item in node.elts)
def visit_Set(self, node: ast.Set) -> Any:
return {self.visit(item) for item in node.elts}
def visit_Dict(self, node: ast.Dict) -> Any:
return {self.visit(k): self.visit(v) for k, v in zip(node.keys, node.values)}
def visit_Subscript(self, node: ast.Subscript) -> Any:
return self.visit(node.value)[self.visit(node.slice)]
def visit_Slice(self, node: ast.Slice) -> slice:
low = self.visit(node.lower) if node.lower else None
high = self.visit(node.upper) if node.upper else None
step = self.visit(node.step) if node.step else None
return slice(low, high, step)
def visit_Attribute(self, node: ast.Attribute) -> Any:
value = self.visit(node.value)
if node.attr.startswith("__"):
raise GdPyRuntimeError("Dunder attributes are not allowed.")
return getattr(value, node.attr)
def visit_Call(self, node: ast.Call) -> Any:
func = self.visit(node.func)
if not callable(func):
raise GdPyRuntimeError("Target in expression is not callable.")
args = [self.visit(arg) for arg in node.args]
kwargs = {kw.arg: self.visit(kw.value) for kw in node.keywords}
return func(*args, **kwargs)
def visit_BinOp(self, node: ast.BinOp) -> Any:
left = self.visit(node.left)
right = self.visit(node.right)
ops = {
ast.Add: lambda a, b: a + b,
ast.Sub: lambda a, b: a - b,
ast.Mult: lambda a, b: a * b,
ast.Div: lambda a, b: a / b,
ast.FloorDiv: lambda a, b: a // b,
ast.Mod: lambda a, b: a % b,
ast.Pow: lambda a, b: a**b,
}
op = type(node.op)
if op not in ops:
raise GdPyRuntimeError("Unsupported binary operator.")
return ops[op](left, right)
def visit_UnaryOp(self, node: ast.UnaryOp) -> Any:
value = self.visit(node.operand)
ops = {
ast.UAdd: lambda a: +a,
ast.USub: lambda a: -a,
ast.Not: lambda a: not a,
}
op = type(node.op)
if op not in ops:
raise GdPyRuntimeError("Unsupported unary operator.")
return ops[op](value)
def visit_BoolOp(self, node: ast.BoolOp) -> Any:
if isinstance(node.op, ast.And):
result = True
for value in node.values:
result = self.visit(value)
if not result:
return result
return result
if isinstance(node.op, ast.Or):
for value in node.values:
result = self.visit(value)
if result:
return result
return result
raise GdPyRuntimeError("Unsupported boolean operator.")
def visit_Compare(self, node: ast.Compare) -> Any:
left = self.visit(node.left)
for op, comp in zip(node.ops, node.comparators):
right = self.visit(comp)
if isinstance(op, ast.Eq):
ok = left == right
elif isinstance(op, ast.NotEq):
ok = left != right
elif isinstance(op, ast.Lt):
ok = left < right
elif isinstance(op, ast.LtE):
ok = left <= right
elif isinstance(op, ast.Gt):
ok = left > right
elif isinstance(op, ast.GtE):
ok = left >= right
elif isinstance(op, ast.In):
ok = left in right
elif isinstance(op, ast.NotIn):
ok = left not in right
else:
raise GdPyRuntimeError("Unsupported comparison operator.")
if not ok:
return False
left = right
return True
def visit_IfExp(self, node: ast.IfExp) -> Any:
return self.visit(node.body) if self.visit(node.test) else self.visit(node.orelse)
def generic_visit(self, node: ast.AST) -> Any:
raise GdPyRuntimeError(f"Unsupported expression part: {type(node).__name__}.")
class GdPyInterpreter:
def __init__(self, script_path: Path) -> None:
self.script_path = script_path
self.base_dir = script_path.parent
self.instructions: list[Instruction] = []
self.labels: dict[str, int] = {}
self.variables: dict[str, Any] = {}
self.modules: dict[str, Any] = {}
self.pointer = 0
self.running = True
self.branch_next: dict[int, int] = {}
self.chain_after: dict[int, int] = {}
self.if_chain_taken: dict[int, bool] = {}
self.while_to_end: dict[int, int] = {}
self.endwhile_to_while: dict[int, int] = {}
self.for_to_end: dict[int, int] = {}
self.endfor_to_for: dict[int, int] = {}
self.for_states: dict[int, dict[str, Any]] = {}
self.python_enabled = False
self.error_suppressed = False
self.error_custom = False
self.last_screenshot_path: Path | None = None
def load(self) -> None:
for line_no, raw_line in enumerate(self.script_path.read_text(encoding="utf-8").splitlines(), start=1):
indent = len(raw_line) - len(raw_line.lstrip(" \t"))
stripped_comment = self.strip_comments(raw_line)
if not stripped_comment.strip():
continue
for clean in self.split_and_chain(stripped_comment.strip()):
try:
tokens = shlex.split(clean, posix=True)
except ValueError as error:
raise GdPyRuntimeError(f"Line {line_no}: {error}.") from error
if not tokens:
continue
first_token = tokens[0]
keyword, call_arg = self.parse_call_style(first_token)
command = CANONICAL.get(keyword, keyword)
if command == "ELSE" and call_arg is None:
tail = clean[len(first_token) :].strip()
if tail and tail != ":":
command = "ELIF"
call_arg = tail
if command not in HELP_TEXT and command not in {"ELSE", "ENDIF", "ENDWHILE", "ENDFOR", "ELIF"}:
command = "PYCODE"
body = call_arg if call_arg is not None else clean[len(tokens[0]) :].lstrip()
body = self.trim_block_suffix(command, body)
if command == "ELIF" and not body:
command = "ELSE"
inline_if = command == "IF" and self.find_keyword(body, "THEN") is not None
instruction = Instruction(line_no, clean, command, tokens[1:], body, indent, inline_if)
if command == "LABEL":
label = body.strip()
if not label:
raise GdPyRuntimeError(f"Line {line_no}: LABEL expects a name.")
if label in self.labels:
raise GdPyRuntimeError(f"Line {line_no}: label '{label}' already exists.")
self.labels[label] = len(self.instructions)
self.instructions.append(instruction)
self.build_blocks()
def build_blocks(self) -> None:
while_stack: list[int] = []
for_stack: list[int] = []
for index, inst in enumerate(self.instructions):
cmd = inst.command
if cmd == "WHILE":
while_stack.append(index)
elif cmd == "ENDWHILE":
if not while_stack:
raise GdPyRuntimeError(f"Line {inst.line_no}: ENDWHILE without WHILE.")
start = while_stack.pop()
self.while_to_end[start] = index
self.endwhile_to_while[index] = start
elif cmd == "FOR":
for_stack.append(index)
elif cmd == "ENDFOR":
if not for_stack:
raise GdPyRuntimeError(f"Line {inst.line_no}: ENDFOR without FOR.")
start = for_stack.pop()
self.for_to_end[start] = index
self.endfor_to_for[index] = start
if while_stack:
raise GdPyRuntimeError(f"Line {self.instructions[while_stack[-1]].line_no}: WHILE block is not closed.")
if for_stack:
raise GdPyRuntimeError(f"Line {self.instructions[for_stack[-1]].line_no}: FOR block is not closed.")
self.build_if_chains()
def build_if_chains(self) -> None:
count = len(self.instructions)
for index, inst in enumerate(self.instructions):
if inst.command != "IF" or inst.inline_if:
continue
branches = [index]
cursor = index
chain_indent = inst.indent
explicit_end: int | None = None
search = index + 1
while search < count:
current = self.instructions[search]
if current.indent < chain_indent:
break
if current.indent == chain_indent:
if current.command == "ENDIF":
explicit_end = search
break
if current.command in {"ELIF", "ELSE"}:
self.branch_next[cursor] = search
branches.append(search)
cursor = search
search += 1
continue
break
search += 1
after = explicit_end + 1 if explicit_end is not None else search
self.branch_next[cursor] = after
for branch in branches:
self.chain_after[branch] = after
def run(self) -> None:
while self.running and self.pointer < len(self.instructions):
inst = self.instructions[self.pointer]
current = self.pointer
try:
getattr(self, f"cmd_{inst.command.lower()}")(inst)
except Exception as error:
message = (
str(error)
if isinstance(error, GdPyRuntimeError)
else f"Line {inst.line_no}: {type(error).__name__}: {error}"
)
self.variables["error"] = "yes" if self.error_custom else message
if not self.error_suppressed:
raise GdPyRuntimeError(message) from error
print(f"[GdPy suppressed] {message}")
self.pointer += 1
continue
if self.running and self.pointer == current:
self.pointer += 1
def strip_comments(self, line: str) -> str:
result: list[str] = []
in_single = False
in_double = False
escaped = False
for char in line:
if escaped:
result.append(char)
escaped = False
continue
if char == "\\":
result.append(char)
escaped = True
continue
if char == "'" and not in_double:
in_single = not in_single
result.append(char)
continue
if char == '"' and not in_single:
in_double = not in_double
result.append(char)
continue
if char == "#" and not in_single and not in_double:
break
result.append(char)
return "".join(result)
def parse_call_style(self, token: str) -> tuple[str, str | None]:
if token.endswith(":") and self.is_name(token[:-1]):
return token[:-1].upper(), ":"
if "(" in token and token.endswith(")"):
name, rest = token.split("(", 1)
if self.is_name(name):
return name.upper(), rest[:-1].strip()
return token.upper(), None
def split_and_chain(self, text: str) -> list[str]:
parts: list[str] = []
current: list[str] = []
in_single = False
in_double = False
escaped = False
depth = 0
index = 0
while index < len(text):
char = text[index]
if escaped:
current.append(char)
escaped = False
index += 1
continue
if char == "\\":
current.append(char)
escaped = True
index += 1
continue
if char == "'" and not in_double:
in_single = not in_single
current.append(char)
index += 1
continue
if char == '"' and not in_single:
in_double = not in_double
current.append(char)
index += 1
continue
if not in_single and not in_double:
if char in "([{":
depth += 1
elif char in ")]}":
depth = max(0, depth - 1)
elif depth == 0 and text[index : index + 5].lower() == " and ":
chunk = "".join(current).strip()
if chunk:
parts.append(chunk)
current = []
index += 5
continue
current.append(char)
index += 1
chunk = "".join(current).strip()
if chunk:
parts.append(chunk)
if len(parts) <= 1:
return parts or [text]
normalized: list[str] = []
for part in parts:
try:
tokens = shlex.split(part, posix=True)
except ValueError:
normalized.append(part)
continue
if not tokens:
continue
keyword, _ = self.parse_call_style(tokens[0])
command = CANONICAL.get(keyword, keyword)
if command in HELP_TEXT or command in {"ELSE", "ENDIF", "ENDWHILE", "ENDFOR", "ELIF"}:
normalized.append(part)
elif "=" in part:
normalized.append(f"SET {part}")
else:
normalized.append(part)
return normalized
def trim_block_suffix(self, command: str, body: str) -> str:
body = body.strip()
if command in {"IF", "ELIF", "ELSE", "WHILE", "FOR"} and body.endswith(":"):
return body[:-1].rstrip()
return body
def find_keyword(self, text: str, keyword: str) -> int | None:
up = text.upper()
target = keyword.upper()
in_single = False
in_double = False
escaped = False
for index, char in enumerate(text):
if escaped:
escaped = False
continue
if char == "\\":
escaped = True
continue
if char == "'" and not in_double:
in_single = not in_single
continue
if char == '"' and not in_single:
in_double = not in_double
continue
if in_single or in_double:
continue
if up[index : index + len(target)] != target:
continue
prev_char = text[index - 1] if index > 0 else " "
next_index = index + len(target)
next_char = text[next_index] if next_index < len(text) else " "
if (prev_char.isalnum() or prev_char == "_") or (next_char.isalnum() or next_char == "_"):
continue
return index
return None
def split_once(self, text: str, keyword: str) -> tuple[str, str]:
index = self.find_keyword(text, keyword)
if index is None:
raise GdPyRuntimeError(f"Expected keyword '{keyword}' in '{text}'.")
return text[:index].strip(), text[index + len(keyword) :].strip()
def split_assignment(self, text: str, line_no: int) -> tuple[str, str]:
if "=" not in text:
raise GdPyRuntimeError(f"Line {line_no}: assignment must contain '='.")
name, expr = text.split("=", 1)
name = name.strip()
if not self.is_name(name):
raise GdPyRuntimeError(f"Line {line_no}: invalid variable name '{name}'.")
return name, expr.strip()
def parse_name_and_expr(self, body: str, line_no: int) -> tuple[str, str]:
parts = body.split(maxsplit=1)
if len(parts) != 2:
raise GdPyRuntimeError(f"Line {line_no}: expected variable name and expression.")
if not self.is_name(parts[0]):
raise GdPyRuntimeError(f"Line {line_no}: invalid variable name '{parts[0]}'.")
return parts[0], parts[1]
def is_name(self, name: str) -> bool:
return bool(name) and name.replace("_", "a").isalnum() and not name[0].isdigit()
def context(self) -> dict[str, Any]:
helpers: dict[str, Any] = {
"true": True,
"false": False,
"none": None,
"yes": "yes",
"no": "no",
"Path": Path,
"math": math,
"len": len,
"list": list,
"dict": dict,
"set": set,
"tuple": tuple,
"range": range,
"min": min,
"max": max,
"sum": sum,
"abs": abs,
"round": round,
"sorted": sorted,
"str": str,
"int": int,
"float": float,
"bool": bool,
"enumerate": enumerate,
"zip": zip,
"all": all,
"any": any,
"now": lambda: datetime.now().isoformat(timespec="seconds"),
"today": lambda: datetime.now().date().isoformat(),
"read_text": lambda path: self.resolve_path(path).read_text(encoding="utf-8"),
"exists": lambda path: self.resolve_path(path).exists(),
"listdir": lambda path=".": sorted(item.name for item in self.resolve_path(path).iterdir()),
"impulse": lambda prompt="": input(str(prompt)),
}
return {**helpers, **self.modules, **self.variables}
def normalize_condition(self, expression: str) -> str:
result: list[str] = []
for index, char in enumerate(expression):
if char == "=":
prev_char = expression[index - 1] if index > 0 else ""
next_char = expression[index + 1] if index + 1 < len(expression) else ""
if prev_char not in "<>!=" and next_char != "=":
result.append("==")
continue
result.append(char)
return "".join(result)
def sync_special_aliases(self, name: str, value: Any) -> None:
if "-" in name:
self.variables[name.replace("-", "_")] = value
def eval_expr(self, expression: str) -> Any:
expression = expression.strip()
if not expression:
return ""
return SafeEvaluator(self.context()).evaluate(expression)
def render_text(self, text: str) -> str:
text = text.strip()
if len(text) >= 2 and text[0] == text[-1] and text[0] in {"'", '"'}:
text = ast.literal_eval(text)
return self.interpolate(str(text))
def eval_or_text(self, text: str) -> Any:
stripped = text.strip()
if len(stripped) >= 2 and stripped[0] == stripped[-1] and stripped[0] in {"'", '"'}:
return self.render_text(stripped)
try:
return self.eval_expr(text)
except GdPyRuntimeError:
return self.render_text(text)
def interpolate(self, text: str) -> str:
for name, value in self.variables.items():
text = text.replace(f"{{{name}}}", str(value))
text = text.replace(f"${name}", str(value))
return text
def resolve_path(self, value: Any) -> Path:
path = value if isinstance(value, Path) else Path(str(value))
return path if path.is_absolute() else self.base_dir / path
def to_number(self, value: Any, line_no: int) -> float:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise GdPyRuntimeError(f"Line {line_no}: value '{value}' is not numeric.")
return float(value)
def get_var(self, name: str, line_no: int) -> Any:
if name not in self.variables:
raise GdPyRuntimeError(f"Line {line_no}: variable '{name}' does not exist.")
return self.variables[name]
def get_container(self, name: str, line_no: int, expected: tuple[type[Any], ...]) -> Any:
value = self.get_var(name, line_no)
if not isinstance(value, expected):
expected_names = ", ".join(item.__name__ for item in expected)
raise GdPyRuntimeError(f"Line {line_no}: '{name}' must be {expected_names}.")
return value
def find_loop(self, pointer: int) -> tuple[int, int, str] | None:
loops: list[tuple[int, int, str]] = []
for start, end in self.while_to_end.items():
if start < pointer < end:
loops.append((start, end, "WHILE"))
for start, end in self.for_to_end.items():
if start < pointer < end:
loops.append((start, end, "FOR"))
return min(loops, key=lambda item: item[1] - item[0]) if loops else None
def exec_inline(self, line_no: int, code: str) -> None:
tokens = shlex.split(code, posix=True)
command = CANONICAL.get(tokens[0].upper(), tokens[0].upper())
if command in {"ELSE", "ENDIF", "ENDWHILE", "ENDFOR"}:
raise GdPyRuntimeError(f"Line {line_no}: block closing commands cannot be inline.")
inst = Instruction(line_no, code, command, tokens[1:], code[len(tokens[0]) :].lstrip(), 0, False)
getattr(self, f"cmd_{command.lower()}")(inst)
def cmd_say(self, inst: Instruction) -> None:
print(self.eval_or_text(inst.body))
def cmd_set(self, inst: Instruction) -> None:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = self.eval_or_text(expr)
def cmd_del(self, inst: Instruction) -> None:
name = inst.body.strip()
self.get_var(name, inst.line_no)
del self.variables[name]
def cmd_copy(self, inst: Instruction) -> None:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = copy.deepcopy(self.eval_expr(expr))
def cmd_swap(self, inst: Instruction) -> None:
if len(inst.args) != 2:
raise GdPyRuntimeError(f"Line {inst.line_no}: SWAP expects two names.")
left, right = inst.args
self.variables[left], self.variables[right] = self.get_var(right, inst.line_no), self.get_var(left, inst.line_no)
def cmd_typeof(self, inst: Instruction) -> None:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = type(self.eval_expr(expr)).__name__
def math_update(self, inst: Instruction, op) -> None:
name, expr = self.parse_name_and_expr(inst.body, inst.line_no)
current = self.to_number(self.get_var(name, inst.line_no), inst.line_no)
value = self.to_number(self.eval_expr(expr), inst.line_no)
result = op(current, value)
self.variables[name] = int(result) if float(result).is_integer() else result
def cmd_add(self, inst: Instruction) -> None:
self.math_update(inst, lambda a, b: a + b)
def cmd_sub(self, inst: Instruction) -> None:
self.math_update(inst, lambda a, b: a - b)
def cmd_mul(self, inst: Instruction) -> None:
self.math_update(inst, lambda a, b: a * b)
def cmd_div(self, inst: Instruction) -> None:
self.math_update(inst, lambda a, b: a / b)
def cmd_mod(self, inst: Instruction) -> None:
self.math_update(inst, lambda a, b: a % b)
def cmd_pow(self, inst: Instruction) -> None:
self.math_update(inst, lambda a, b: a**b)
def cmd_len(self, inst: Instruction) -> None:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = len(self.eval_expr(expr))
def cmd_append(self, inst: Instruction) -> None:
name, expr = self.parse_name_and_expr(inst.body, inst.line_no)
self.get_container(name, inst.line_no, (list,)).append(self.eval_expr(expr))
def cmd_extend(self, inst: Instruction) -> None:
name, expr = self.parse_name_and_expr(inst.body, inst.line_no)
self.get_container(name, inst.line_no, (list,)).extend(self.eval_expr(expr))
def cmd_insert(self, inst: Instruction) -> None:
parts = inst.body.split(maxsplit=2)
if len(parts) != 3:
raise GdPyRuntimeError(f"Line {inst.line_no}: INSERT expects list, index and value.")
self.get_container(parts[0], inst.line_no, (list,)).insert(int(self.eval_expr(parts[1])), self.eval_expr(parts[2]))
def cmd_remove(self, inst: Instruction) -> None:
name, expr = self.parse_name_and_expr(inst.body, inst.line_no)
value = self.eval_expr(expr)
container = self.get_container(name, inst.line_no, (list, set))
container.remove(value) if isinstance(container, list) else container.discard(value)
def cmd_pop(self, inst: Instruction) -> None:
if "=" in inst.body:
target, source = self.split_assignment(inst.body, inst.line_no)
self.variables[target] = self.get_container(source.strip(), inst.line_no, (list,)).pop()
else:
self.get_container(inst.body.strip(), inst.line_no, (list,)).pop()
def cmd_clear(self, inst: Instruction) -> None:
body = inst.body.strip()
if not body:
os.system("cls" if os.name == "nt" else "clear")
return
if body.startswith("="):
names = [name.strip() for name in body[1:].split(",") if name.strip()]
for name in names:
self.variables[name] = ""
if "-" in name:
self.sync_special_aliases(name, "")
return
name = body
value = self.get_var(name, inst.line_no)
if isinstance(value, str):
self.variables[name] = ""
elif isinstance(value, (list, dict, set)):
value.clear()
else:
raise GdPyRuntimeError(f"Line {inst.line_no}: CLEAR works with list, dict, set or str.")
def cmd_sort(self, inst: Instruction) -> None:
self.get_container(inst.body.strip(), inst.line_no, (list,)).sort()
def cmd_reverse(self, inst: Instruction) -> None:
self.get_container(inst.body.strip(), inst.line_no, (list,)).reverse()
def cmd_unique(self, inst: Instruction) -> None:
name = inst.body.strip()
self.variables[name] = list(dict.fromkeys(self.get_container(name, inst.line_no, (list,))))
def cmd_split(self, inst: Instruction) -> None:
name, rest = self.split_assignment(inst.body, inst.line_no)
text_expr, sep_expr = self.split_once(rest, "BY")
self.variables[name] = str(self.eval_or_text(text_expr)).split(str(self.eval_or_text(sep_expr)))
def cmd_join(self, inst: Instruction) -> None:
name, rest = self.split_assignment(inst.body, inst.line_no)
items_expr, sep_expr = self.split_once(rest, "BY")
self.variables[name] = str(self.eval_or_text(sep_expr)).join(str(item) for item in self.eval_expr(items_expr))
def cmd_replace(self, inst: Instruction) -> None:
name, rest = self.split_assignment(inst.body, inst.line_no)
text_expr, old_part = self.split_once(rest, "OLD")
old_expr, new_expr = self.split_once(old_part, "NEW")
text = str(self.eval_or_text(text_expr))
self.variables[name] = text.replace(str(self.eval_or_text(old_expr)), str(self.eval_or_text(new_expr)))
def cmd_upper(self, inst: Instruction) -> None:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = str(self.eval_or_text(expr)).upper()
def cmd_lower(self, inst: Instruction) -> None:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = str(self.eval_or_text(expr)).lower()
def cmd_strip(self, inst: Instruction) -> None:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = str(self.eval_or_text(expr)).strip()
def cmd_readfile(self, inst: Instruction) -> None:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = self.resolve_path(self.eval_or_text(expr)).read_text(encoding="utf-8")
def cmd_writefile(self, inst: Instruction) -> None:
path_expr, content_expr = self.split_once(inst.body, "WITH")
path = self.resolve_path(self.eval_or_text(path_expr))
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(str(self.eval_or_text(content_expr)), encoding="utf-8")
def cmd_appendfile(self, inst: Instruction) -> None:
path_expr, content_expr = self.split_once(inst.body, "WITH")
path = self.resolve_path(self.eval_or_text(path_expr))
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as file:
file.write(str(self.eval_or_text(content_expr)))
def cmd_exists(self, inst: Instruction) -> None:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = self.resolve_path(self.eval_or_text(expr)).exists()
def cmd_mkdir(self, inst: Instruction) -> None:
self.resolve_path(self.eval_or_text(inst.body)).mkdir(parents=True, exist_ok=True)
def cmd_listdir(self, inst: Instruction) -> None:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = sorted(item.name for item in self.resolve_path(self.eval_or_text(expr)).iterdir())
def cmd_readjson(self, inst: Instruction) -> None:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = json.loads(self.resolve_path(self.eval_or_text(expr)).read_text(encoding="utf-8"))
def cmd_writejson(self, inst: Instruction) -> None:
path_expr, data_expr = self.split_once(inst.body, "WITH")
path = self.resolve_path(self.eval_or_text(path_expr))
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(self.eval_expr(data_expr), ensure_ascii=False, indent=2), encoding="utf-8")
def cmd_import(self, inst: Instruction) -> None:
feature = inst.body.strip().lower()
if feature == "python":
self.python_enabled = True
self.modules["python"] = __import__("builtins")
return
if feature == "rights":
self.variables["rights"] = self.variables.get("rights", "no")
return
if feature == "error":
self.variables["error"] = self.variables.get("error", "none")
return
if feature == "file":
self.variables["file"] = "planned_requires_rights"
return
if feature == "desktop":
self.variables["desktop"] = "ready"
return
if feature == "desktop-time":
value = datetime.now().strftime("%H:%M")
self.variables["desktop-time"] = value
self.sync_special_aliases("desktop-time", value)
return
if feature == "desktop-data":
value = datetime.now().strftime("%d.%m.%Y")
self.variables["desktop-data"] = value
self.sync_special_aliases("desktop-data", value)
return
if feature == "killpid":
self.variables["killpid"] = "ready_requires_rights"
return
if feature == "dogfunny":
self.variables["dogfunny"] = "ready"
return
if feature == "screenshot":
self.variables["screenshot"] = "ready_requires_rights"
return
if self.find_keyword(inst.body, "AS") is not None:
module_name, alias = self.split_once(inst.body, "AS")
else:
module_name = inst.body.strip()
alias = module_name.split(".")[-1]
if not self.is_name(alias):
raise GdPyRuntimeError(f"Line {inst.line_no}: invalid alias '{alias}'.")
self.modules[alias] = importlib.import_module(module_name.strip())
def cmd_call(self, inst: Instruction) -> None:
if "=" in inst.body:
name, expr = self.split_assignment(inst.body, inst.line_no)
self.variables[name] = self.eval_expr(expr)
else:
self.eval_expr(inst.body)
def cmd_label(self, inst: Instruction) -> None:
return None
def cmd_goto(self, inst: Instruction) -> None:
label = inst.body.strip()
if label not in self.labels:
raise GdPyRuntimeError(f"Line {inst.line_no}: label '{label}' does not exist.")
self.pointer = self.labels[label]
def cmd_if(self, inst: Instruction) -> None:
if inst.inline_if:
cond, code = self.split_once(inst.body, "THEN")
if self.eval_expr(self.normalize_condition(cond)):
self.exec_inline(inst.line_no, code)
return
after = self.chain_after[self.pointer]
if self.if_chain_taken.get(after):
self.pointer = after
return
if self.eval_expr(self.normalize_condition(inst.body)):
self.if_chain_taken[after] = True
return
self.pointer = self.branch_next[self.pointer]
def cmd_elif(self, inst: Instruction) -> None:
after = self.chain_after[self.pointer]
if self.if_chain_taken.get(after):
self.pointer = after