-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpreterME.py
More file actions
2005 lines (1742 loc) · 95.8 KB
/
interpreterME.py
File metadata and controls
2005 lines (1742 loc) · 95.8 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
#this software is licenced under the GNU General Public License v3.0, for more information check: https://raw.githubusercontent.com/XFydro/x3/refs/heads/main/license.txt
#i will try to clean it up in future updates. -Raven
"""
Requirements:
__Python3.8+
__Pip(Latest Update for better experience)
__Internet Connection(for first run to download essentials like help files)
__Minimal Hardware resources:2GB Ram
__Patience because python is slow af :P
"""
from difflib import SequenceMatcher
import datetime, platform, uuid, getpass, socket, traceback, builtins, argparse, time, re, os, shlex, json, difflib, subprocess, importlib, random, math, struct
#import cProfile
REPL=0 #on default script mode.
VERSION=3.96 #version (For IDE and more)
def install_package(package, alias=None)->None:
import sys
try:
module = importlib.import_module(package)
if REPL==1:
print(f"{package} is already installed.")
except ImportError:
print(f"{package} not found. Installing...")
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
try:
module = importlib.import_module(package)
except ImportError:
print(f"ErrID14: Failed to import {package} after installation.")
return None
if alias:
globals()[alias] = module
print(f"Imported {package} as {alias}.")
else:
globals()[package] = module
try:
import psutil
except ImportError:
install_package("psutil")
try:
import requests
except ImportError:
install_package("requests")
try:
class Error(Exception):
pass
class Interpreter:
def __init__(self):
self.call_stack = []
self.local_variables = {}
self.REPL:int=REPL
self.current_line:int=-1
self.variables:dict = {} #variable dictionary
self.functions:dict = {} #function dictionary
self.current_function_name:str = None
self.in_function_definition:bool = False #flag to indicate if the code is currently in a function definition
self.CFE:bool = False #Current Function Execution.
self.local:bool = False #local variable flag, used to indicate if a var is being declared locally or globally
self.control_stack:list = [] #that if else and stuff, for basic control flow monitoring
self.debug:bool = False #only used as a placeholder, replaced by the new BETTER debug system
self.debuglog:list = [] #log() function list.
self.output:str = None #output for functions like fetch, i will think of improving this.
self.log_messages:list = [] #old log messages record, still works but deprecated
self.loaded_files:list = [] #list of loaded files, to prevent recursion during file loading.
self.execution_state:dict = {} #thought of removing this but it is still used in some control flow magic so ye.
self.trystate:str = "False" #for checking whether the current block is in a try state or not. (had to make it a string because of setattr and getattr)
self.return_flag:bool = False
self.return_value:str = None
self.loaderrorcount:int = 0 #load error count, used to track errors during file loading.
self._math_ns={'math':math}
self._math_cache={}
#Debug Init---
self.ctrflwdebug:bool = False
self.prtdebug:bool = False
self.mathdebug:bool = False
self.filedebug:bool = False
self.clramadebug:bool = False
self.cmdhandlingdebug:bool = False
self.reqdebug:bool=False
self.conddebug:bool=False
self.vardebug:bool=False
#---
#Rules Init--
self.semo:bool=False #Script Execution Mode Only, this is used to prevent REPL from executing commands.
self.disableprt:bool=False #Disable Print, to disable the print command, i forgot why i made this TwT #29.9.25-Raven.
#---
self.command_mapping:dict = {
'add': self.cmd_add,
'a_file': self.cmd_append_file,
'call': self.cmd_call,
'cls': self.cmd_clear,
'create_dir': self.cmd_create_dir,
'dec': self.cmd_dec,
'def': self.cmd_def,
'del': self.cmd_del,
'del_file': self.cmd_delete_file,
'delete_dir': self.cmd_delete_dir,
'dev.debug': self.dev,
'div': self.cmd_div,
'else': self.cmd_else,
'end': self.cmd_end,
'exit': self.cmd_exit,
'fastmath': self.cmd_fastmath,
'fetch': self.cmd_fetch,
'flush': self.cmd_reworkedflush,
'fncend': self.cmd_fncend,
'goto': self.cmd_goto,
'if': self.cmd_if,
'inc': self.cmd_inc,
'inp': self.cmd_inp,
'load': self.load,
'mod': self.cmd_mod,
'mul': self.cmd_mul,
'prt': self.cmd_prt,
'reg': self.cmd_reg,
'return': self.cmd_return,
'r_file': self.cmd_read_file,
'search_file': self.cmd_search_file,
'setclientrule': self.setclientrule,
'sqrt': self.cmd_sqrt,
'sub': self.cmd_sub,
'brute': self.cmd_brute,
'wait': self.cmd_wait,
'while': self.cmd_while,
'w_file': self.cmd_create_file,
'--info': self.info,
'--help': self.help,
}
self.exceptional_commands:dict={
"//",
"",
" ",
}
self.nibbits:dict = { #Renamed to nibbits because "nibbits" sounds cuter than "additional_parameters" :3 #29.9.25-Raven
#misc inline functions, that can be used in commands by using the syntax ##function_name or ##function_name(args) or ##function_name:type:(args) for functions with arguments. (arguments must be enclosed in parentheses)
"##interpreter:vars": lambda: list(self.variables.keys()),
"##interpreter:funcs": lambda: list(getattr(self, "functions", {}).keys()),
"##interpreter:memory": lambda: f"{round(psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024, 2)} MB" if 'psutil' in globals() else "[psutil module not available]",
"##interpreter:platform": lambda: platform.platform(),
"##interpreter:eval": lambda x="": eval(x) if x else None,
"##random": lambda: random.random(),
"##randint": lambda: random.randint(0, 100),
"##timeseconds": lambda: time.time(),
"##timestamp": lambda: int(time.time()),
"##date": lambda: datetime.datetime.now().strftime("%Y-%m-%d"),
"##time": lambda: datetime.datetime.now().strftime("%H:%M:%S"),
"##datetime": lambda: datetime.datetime.now(),
"##datetime:iso": lambda: datetime.datetime.now().isoformat(),
"##datetime:utc": lambda: datetime.datetime.now(datetime.timezone.utc).isoformat(),
"##REPL": lambda: self.REPL,
"##uuid": lambda: str(uuid.uuid4()),
"##uuid:hex": lambda: uuid.uuid4().hex,
"##user": lambda: getpass.getuser(),
"##hostname": lambda: socket.gethostname(),
"##platform": lambda: platform.system(),
"##osversion": lambda: platform.version(),
"##cwd": lambda: os.getcwd(),
"##randbool": lambda: random.choice([True, False]),
"##msec": lambda: int(time.time() * 1000),
"##env": lambda key="": os.environ.get(key, "") if key else dict(os.environ),
"##upper": lambda txt="": txt.upper(),
"##lower": lambda txt="": txt.lower(),
"##reverse": lambda txt="": txt[::-1],
"##length": lambda txt="": len(txt),
"##capitalize": lambda txt="": txt.capitalize(),
"##pingreport": lambda host="8.8.8.8": os.system(f"ping -n 1 {host}" if os.name == "nt" else f"ping -c 1 {host}") == 0,
"##ping": lambda host="8.8.8.8": (
lambda output: (
re.search(r'time[=<]?\s*([\d.]+)\s*ms', output).group(1)
if re.search(r'time[=<]?\s*([\d.]+)\s*ms', output) else "unreachable"
)
)(
subprocess.getoutput(
f"ping -n 1 {host}" if platform.system().lower() == "windows"
else f"ping -c 1 {host}"
)
),
"##fetch": lambda url="": requests.get(url).text if 'requests' in globals() else (_ for _ in ()).throw(Error("--ErrID102: Fetch not available")),
"##fetch:json": lambda url="": requests.get(url).json() if 'requests' in globals() else (_ for _ in ()).throw(Error("--ErrID102: Fetch not available")),
"##fetch:status": lambda url="": requests.get(url).status_code if 'requests' in globals() else (_ for _ in ()).throw(Error("--ErrID102: Fetch not available")),
"##fetch:headers": lambda url="": requests.get(url).headers if 'requests' in globals() else (_ for _ in ()).throw(Error("--ErrID102: Fetch not available")),
"##fetch:content": lambda url="": requests.get(url).content if 'requests' in globals() else (_ for _ in ()).throw(Error("--ErrID102: Fetch not available")),
"##fetch:html": lambda url="": requests.get(url).text if 'requests' in globals() else (_ for _ in ()).throw(Error("--ErrID102: Fetch not available")),
"##fetch:xml": lambda url="": requests.get(url).text if 'requests' in globals() else (_ for _ in ()).throw(Error("--ErrID102: Fetch not available")),
"##rgb:channel": lambda s="000000 0": (
lambda parts: (
lambda hex_str, ch: int(hex_str[ch*2:ch*2+2], 16)
)(
(parts[0].strip('"').lstrip("#") + "000000")[:6],
max(0, min(2, int(parts[1])))
)
if len(parts) >= 2 else 0
)(s.split()),
"##rgb": lambda s="000000": (
lambda hex_str: (
int(hex_str[0:2], 16),
int(hex_str[2:4], 16),
int(hex_str[4:6], 16)
) if len(hex_str) >= 6 else (0, 0, 0)
)(s.strip('"').lstrip("#") + "000000"),
"##readfile": lambda path="": open(path, "r").read() if os.path.exists(path) else "[File not found]",#returns entire file content as an single string
}
def raiseError(self, message):
raise Error(message)
def setclientrule(self, args):
allowed=['REPL', 'semo','disableprt']
newargs=args.split(" ")
for i in range(0,len(newargs)):
if newargs[i] in allowed:
if getattr(self, newargs[i], None) is not None:
setattr(self, newargs[i], True) if not getattr(self, newargs[i]) else setattr(self, newargs[i], False)
print(f"[DEBUG] Client rule '{newargs[i]}' set to {getattr(self, newargs[i])}.") if self.cmdhandlingdebug else None
else:
self.raiseError(f"--ErrID106: Unknown client rule '{newargs[i]}'") if getattr(self, "trystate")=="False" else print(f"[WARNING] Unknown client rule '{newargs[i]}', ignored due to try block.")
if newargs[i]=="reset":
# Reset all rules to default (i hope my lazy ahh wont forget updating this part everytime new rules are added) #12.8.25
self.semo = False
self.disableprt = False
print("[DEBUG] All client rules reset to default.") if self.cmdhandlingdebug else None
def info(self):
print(f'Running on version:{VERSION}')
print(f'Developed by Raven Corvidae 07.2024-Present, under GNU GPLv3.0 license.')
def help(self, command):
print("Syntax and other information at Https://x3documentation.neocities.org/syntax")
def comment_strip(self, s):
return s.split('\\')[0]
def load(self, filename: str) -> None:
self.loaderrorcount = 0
success_count = 0
if filename in self.loaded_files:
if self.filedebug:
print(f"[DEBUG-{self.filedebug}] File '{filename}' already loaded, skipping to prevent recursion.")
return
if self.filedebug:
print(f"[DEBUG-{self.filedebug}] Starting to load file: {filename}")
try:
if not isinstance(filename, str):
raise TypeError(f"Expected filename as str, got {type(filename).__name__}.")
if not os.path.isfile(filename):
raise FileNotFoundError(f"File '{filename}' does not exist.")
if not os.access(filename, os.R_OK):
raise PermissionError(f"No read permission for file '{filename}'.")
if self.filedebug:
print(f"[DEBUG-{self.filedebug}] Opening file: {filename}")
try:
interpreter = self
except Exception as e:
raise RuntimeError(f"Interpreter initialization failed: {e}")
with open(filename, 'r', encoding='utf-8', errors='replace') as file:
for lineno, line in enumerate(file, 1):
line = line.strip()
if not line or line.startswith("//"):
continue
try:
interpreter.handle_command(line)
success_count += 1
if self.filedebug:
print(f"[Line {lineno}] Executed: {line}")
except Exception:
self.loaderrorcount += 1
if self.filedebug:
print(f"[Line {lineno}] Failed: {line}")
continue
self.loaded_files.append(filename)
except (FileNotFoundError, PermissionError, TypeError, RuntimeError) as critical:
print(f"[LOAD-CRITICAL] {critical}")
except Exception as unknown:
print(f"[LOAD-UNKNOWN] Unexpected error:\n{unknown}")
if self.filedebug:
traceback.print_exc()
finally:
if self.filedebug:
print(f"[DEBUG-{self.filedebug}] Load complete.")
print(f" ├─ Successes: {success_count}")
print(f" └─ Failures: {self.loaderrorcount}")
def cmd_del(self, args):
"""Deletes a variable or function.
Usage: del var variable_name OR del func function_name"""
parts = args.split(" ",)
object_type = parts[0].strip().lower() if len(parts) > 0 else None
name = parts[1].strip() if len(parts) > 1 else None
if object_type == "var":
if name in self.variables:
del self.variables[name]
if self.vardebug:
print(f"[DEBUG] Variable '{name}' deleted.")
else:
self.loaderrorcount+=1;self.raiseError(f"--ErrID75: Variable '{name}' not defined.")if getattr(self, "trystate")=="False" else print(f"[WARNING] Variable '{name}' not defined, ignored due to try block.")
elif object_type == "func":
if name in self.functions:
del self.functions[name]
if self.vardebug:
print(f"[DEBUG] Function '{name}' deleted.")
else:
self.loaderrorcount+=1;self.raiseError(f"--ErrID76: Function '{name}' not defined.")if getattr(self, "trystate")=="False" else print(f"[WARNING] Function '{name}' not defined, ignored due to try block.")
else:
self.loaderrorcount+=1;self.raiseError(f"--ErrID74: Unknown object type '{object_type}' for deletion.")if getattr(self, "trystate")=="False" else print(f"[WARNING] Unknown object type '{object_type}' for deletion, ignored due to try block.")
def log(self, message):
if self.debug:
print(f"[DEBUG]: {message}")
self.debuglog.append(f"[DEBUG]: {message}")
def cmd_clear(self, args):
if args!="legacy":
os.system('cls' if os.name == 'nt' else 'clear')
else:
print("\n" * 100) #for terminals or non-tty outputs that dont support cls.
def cmd_brute(self):
"""A bruteforce control flow command, that will execute the block until it encounters an end, regardless of errors."""
self.trystate = "True"
self.control_stack.append({"type": "try"})
if self.ctrflwdebug:
print(f"[DEBUG] Try pushed to stack.")
def cmd_if(self, condition):
"""
Evaluate an IF condition and push it to the control stack.
"""
try:
condition = self.replace_nibbits(condition) # Replace any additional parameters like ##random, ##REPL, etc :3
result = self.eval_condition(condition) # Pass the full condition as a single string
except ValueError as e:
self.loaderrorcount+=1;self.raiseError(f"--ErrID77: Invalid IF condition '{condition}'. Details: {e}")if getattr(self, "trystate")=="False" else print(f"[WARNING] Invalid IF condition '{condition}'. Details: {e}, ignored due to try block.")
self.control_stack.append({"type": "if", "executed": result, "has_else": False})
if self.ctrflwdebug:
print(f"[DEBUG] IF condition '{condition}' evaluated to {result}, pushed to stack.")
if not result:
if self.ctrflwdebug:
print("[DEBUG] Skipping subsequent commands inside this IF block.")
def evaluate_math_expression(self, expression):
# Replace variables in the expression
try:
return eval(expression, {"__builtins__": {}}, {})
except Exception as e:
print(f"[MATH ERROR] {e}")
return "<MATH_ERROR>"
def cmd_else(self):
"""
Execute an ELSE block only if the preceding IF block was false.
"""
if not self.control_stack:
self.loaderrorcount+=1;self.raiseError("--ErrID78: ELSE without a matching IF.")if getattr(self, "trystate")=="False" else print(f"[WARNING] ELSE without a matching IF, ignored due to try block.")
last_if = self.control_stack[-1]
if last_if["type"] != "if":
self.loaderrorcount+=1;self.raiseError("--ErrID78: ELSE without a matching IF.")if getattr(self, "trystate")=="False" else print(f"[WARNING] ELSE without a matching IF, ignored due to try block.")
if last_if.get("has_else", False):
self.loaderrorcount+=1;self.raiseError("--ErrID79: Multiple ELSE statements for the same IF.")if getattr(self, "trystate")=="False" else print(f"[WARNING] Multiple ELSE statements for the same IF, ignored due to try block.")
last_if["has_else"] = True
last_if["executed"] = not last_if["executed"]
if self.ctrflwdebug:
if last_if["executed"]:
print("[DEBUG] ELSE block will execute.")
else:
print("[DEBUG] Skipping ELSE block because IF condition was true.")
def cmd_while(self, condition):
"""
Implements a while-loop functionality with proper nested execution.
Skips pushing a new while-loop if the last one is on the same line.
"""
if (self.control_stack and
self.control_stack[-1]["type"] == "while" and
self.control_stack[-1]["start_line"] == self.current_line):
if self.ctrflwdebug:
print(f"[DEBUG] Skipping duplicate WHILE on line {self.current_line}")
return
if not self.should_execute():
executed = False
else:
try:
executed = self.eval_condition(condition)
except ValueError as e:
self.loaderrorcount+=1;self.raiseError(f"--ErrID90: Invalid WHILE condition '{condition}'. Details: {e}")if getattr(self, "trystate")=="False" else print(f"[WARNING] Invalid WHILE condition '{condition}'. Details: {e}, ignored due to try block.")
self.control_stack.append({
"type": "while",
"condition": condition,
"executed": executed,
"start_line": self.current_line
})
if self.ctrflwdebug:
print(f"[DEBUG] WHILE condition '{condition}' evaluated to {executed}, pushed to stack.")
def cmd_end(self):
"""
Handles 'end' for 'if', 'else', and 'while' blocks.
For 'while', it only loops if it was executed and the condition is still true.
"""
if not self.control_stack:
self.loaderrorcount+=1;self.raiseError("--ErrID91: 'end' without matching control block.")if getattr(self, "trystate")=="False" else print(f"[WARNING] 'end' without matching control block, ignored due to try block.")
block = self.control_stack.pop()
debug = self.ctrflwdebug
block_type = block.get("type")
if debug:
print(f"[DEBUG] END:")
print(f" popped -> {block}")
print(f" type -> {block.get('type') if isinstance(block, dict) else type(block)}")
print(f" full stack -> {self.control_stack if hasattr(self, 'control_stack') else 'NO STACK FOUND'}")
if block_type == "while":
if block["executed"]:
try:
condition_still_true = self.eval_condition(self.replace_variables(block["condition"]))
except Exception as e:
self.loaderrorcount+=1;self.raiseError(f"--ErrID92: WHILE condition failed at END. Details: {e}")if getattr(self, "trystate")=="False" else print(f"[WARNING] WHILE condition failed at END. Details: {e}, ignored due to try block.")
if condition_still_true:
if debug:
print(f"[DEBUG] Repeating WHILE: jumping to line {block['start_line']}")
self.control_stack.append(block)
self.current_line = block["start_line"] - 1
return
else:
if debug:
print(f"[DEBUG] Exiting WHILE loop")
else:
if debug:
print(f"[DEBUG] Skipping WHILE block recheck (never executed)")
elif block_type in ("if", "else"):
if debug:
print(f"[DEBUG] Closing {block_type.upper()} block")
elif block_type =="try":
self.trystate="False"
if debug:
print(f"[DEBUG] Closing TRY block")
else:
self.loaderrorcount+=1;self.raiseError(f"--ErrID93: Unknown control block type '{block_type}' during END.") if getattr(self, "trystate")=="False" else print(f"[WARNING] Unknown control block type '{block_type}' during END.") #just realised this will never be triggered TwT #29.8.25
def should_execute(self):
"""
Determine if the current block should execute based on active IF conditions.
"""
if not self.control_stack:
return True
for block in reversed(self.control_stack):
if ((block["type"] == "if" and not block["executed"]) or
(block["type"] == "else" and not block["executed"])):
return False
return True
def list_replacer(self, expr):
"""
Replaces $list[index] patterns in an expression with the actual element.
Keeps strings quoted so eval won't break.
"""
pattern = re.compile(r"\$(\w+)\[(\d+)\]")
def replacer(match):
var_name, index = match.group(1), int(match.group(2))
if var_name not in self.variables:
self.raiseError(f"--ErrID99: Variable '{var_name}' not defined")
return "None"
value, vtype = self.variables[var_name]
if vtype != "list":
self.raiseError(f"--ErrID100: Variable '{var_name}' is not a list")
return "None"
try:
element = value[index]
return f'"{element}"'
except IndexError:
self.raiseError(f"--ErrID101: Index {index} out of range for list '{var_name}'")
return "None"
return pattern.sub(replacer, expr)
def replace_variables(self, text, quoted=None):
if not self.should_execute():
return text
text = self.list_replacer(text)
if self.vardebug:
print(f"[DEBUG] Replacing variables in: {text}")
def func_replacer(match):
raw = match.group(1)
if ":" in raw:
func_name, arg_str = raw.split(":", 1)
arg_str = arg_str.strip("()")
resolved_args = self.replace_variables(arg_str)
result = self.cmd_call(f"{func_name} {resolved_args}")
return str(result) if result is not None else ""
return f"<INVALID:{raw}>"
def var_replacer(match):
var_name = match.group(1)
if var_name in self.local_variables:
val = self.local_variables[var_name][0]
elif var_name in self.variables:
val = self.variables[var_name][0]
else:
self.raiseError(f"--ErrID94: Variable '{var_name}' not defined.")
return ""
return str(val)
if self.vardebug:
print(f"[DEBUG] Final variable replacement in: {text}")
text = re.sub(r"\$([a-zA-Z_][a-zA-Z0-9_]*)", var_replacer, text)
text = re.sub(r"##([\w]+:\([^\)]*\))", func_replacer, text)
return self.replace_nibbits(text)
def eval_condition(self, condition_str):
condition_str = self.replace_variables(condition_str, quoted=True) # Replace variables in the condition
condition_str = self.replace_nibbits(condition_str) # Replace nibbits in the condition
if self.conddebug:
print(f"[DEBUG] Evaluating condition: {condition_str}")
def debug(msg):
if self.conddebug:
print(f"[DEBUG] {msg}")
import ast
import operator
_ALLOWED_OPS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod,
ast.Pow: operator.pow,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
}
def safe_eval_math(expr):
def _eval(node):
if isinstance(node, ast.Constant):
if isinstance(node.value, (int, float)):
return node.value
raise ValueError
if isinstance(node, ast.BinOp):
return _ALLOWED_OPS[type(node.op)](
_eval(node.left),
_eval(node.right)
)
if isinstance(node, ast.UnaryOp):
return _ALLOWED_OPS[type(node.op)](_eval(node.operand))
raise ValueError
tree = ast.parse(expr, mode="eval")
return _eval(tree.body)
def get_value(token):
token = token.strip()
token_lower = token.lower()
if token_lower in ("true", "false"):
val = token_lower == "true"
debug(f"Resolved boolean literal {token} -> {val}")
return val
if (token.startswith('"') and token.endswith('"')) or \
(token.startswith("'") and token.endswith("'")):
val = token[1:-1]
debug(f"Resolved literal string {token} -> {val!r}")
return val
try:
val = safe_eval_math(token)
debug(f"Evaluated math expression {token} -> {val}")
return val
except Exception:
pass
try:
val = float(token) if "." in token else int(token)
debug(f"Parsed numeric literal {token} -> {val!r}")
return val
except ValueError:
pass
debug(f"Interpreting token {token} as string {token!r}")
return token
def compare_values(left, op, right):
debug(f"Comparing {left!r} {op} {right!r}")
if left is None or right is None:
return False
try:
if isinstance(left, (int, float)) and isinstance(right, str):
right = float(right) if '.' in right else int(right)
elif isinstance(right, (int, float)) and isinstance(left, str):
left = float(left) if '.' in left else int(left)
except:
return False
if op == "==ic":
return str(left).lower() == str(right).lower()
if op == "startswith":
return str(left).startswith(str(right))
if op == "contains":
return str(right) in str(left)
if op == "|+|":
return SequenceMatcher(None, str(left), str(right)).ratio() * 100
return {
"==": left == right,
"!=": left != right,
">": left > right,
"<": left < right,
">=": left >= right,
"<=": left <= right
}.get(op, False)
def eval_simple(expr):
expr = expr.strip()
if expr.startswith("(") and expr.endswith(")"):
return self.eval_condition(expr[1:-1])
ops = ["==ic", "|+|", ">=", "<=", "!=", "==", ">", "<", "startswith", "contains"]
for op in ops:
parts = expr.split(op)
if len(parts) == 2:
left_raw = parts[0].strip()
right_raw = parts[1].strip()
left_val = get_value(left_raw)
right_val = get_value(right_raw)
result = compare_values(left_val, op, right_val)
debug(f"Result of {parts[0]} {op} {parts[1]} -> {result}")
return result
val = get_value(expr)
result = bool(val)
debug(f"Truth value of {expr!r} -> {result}")
return result
def eval_and(term):
factors = []
buf = ""
level = 0
in_quotes = None
i = 0
while i < len(term):
ch = term[i]
if ch in "\"'":
if in_quotes is None:
in_quotes = ch
elif in_quotes == ch:
in_quotes = None
if ch == "(" and in_quotes is None:
level += 1
elif ch == ")" and in_quotes is None:
level -= 1
if term[i:i+3] == "and" and level == 0 and in_quotes is None:
factors.append(buf.strip())
buf = ""
i += 3
continue
buf += ch
i += 1
factors.append(buf.strip())
result = True
for factor in factors:
if factor.startswith("!"):
res = not eval_simple(factor[1:])
else:
res = eval_simple(factor)
result = result and bool(res)
debug(f"AND so far -> {result}")
if not result:
break
return result
def split_or_blocks(condition_str):
terms = []
buf = ""
level = 0
in_quotes = None
i = 0
while i < len(condition_str):
ch = condition_str[i]
if ch in "\"'":
if in_quotes is None:
in_quotes = ch
elif in_quotes == ch:
in_quotes = None
if ch == "(" and not in_quotes:
level += 1
elif ch == ")" and not in_quotes:
level -= 1
if condition_str[i:i+2] == "or" and level == 0 and in_quotes is None:
terms.append(buf.strip())
buf = ""
i += 2
continue
buf += ch
i += 1
terms.append(buf.strip())
return terms
final_result = False
for term in split_or_blocks(condition_str):
res = eval_and(term)
debug(f"OR-term '{term}' -> {res}")
final_result = final_result or res
if final_result:
break
debug(f"Final result of '{condition_str}' -> {final_result}")
return final_result
def cmd_prt(self, raw_args):
"""
Enhanced print command with styled, formatted, and interactive output.
"""
if not(self.disableprt):
if not raw_args:
self.loaderrorcount+=1;self.raiseError("--ErrID37: No arguments provided for prt command.")if getattr(self, "trystate")=="False" else print(f"[WARNING] No arguments provided for prt command, ignored due to try block.")
return
# Default settings
settings = {
"color_code": "",
"alignment": None,
"delay": None,
"log_message": False,
"title": None,
"save_to_file": None,
"format_type": None,
"case": None,
"border": None,
"text_effect": None,
}
try:
# Preserve spaces inside quotes
args = raw_args[1:-1] if raw_args.startswith('"') and raw_args.endswith('"') else raw_args
# Parse settings using regex
settings_pattern = re.compile(r"(align|delay|title|tofile|format|case|border|effect|log)(?:=(\S+))?")
matches = settings_pattern.findall(args)
for key, value in matches:
settings[key] = float(value) if key == "delay" else value.lower()
# Remove settings from args
args = settings_pattern.sub("", args).strip().replace(" ", " ")
# Handle log flag
if "log" in args.split():
args = args.replace("log", "").strip()
settings["log_message"] = True
# Variable interpolation
# Apply case transformations
if settings["case"] == "upper":
args = args.upper()
elif settings["case"] == "lower":
args = args.lower()
# Apply text alignment
if settings["alignment"] == "center":
args = args.center(80)
elif settings["alignment"] == "right":
args = args.rjust(80)
elif settings["alignment"] == "left":
args = args.ljust(80)
# Add borders if specified
if settings["border"]:
border_char = settings["border"]
padding = 1 # space between text and border
content_line = f"{border_char}{' ' * padding}{args}{' ' * padding}{border_char}"
border_length = len(content_line)
border_line = border_char * (border_length // len(border_char))
if len(border_line) < border_length:
border_line += border_char[:border_length - len(border_line)] # fill the gap
args = f"{border_line}\n{content_line}\n{border_line}"
# Apply text effects
effect_map = {"bold": "\033[1m", "italic": "\033[3m"}
if settings["text_effect"] in effect_map:
args = f"{effect_map[settings['text_effect']]}{args}\033[0m"
# Update terminal title
if settings["title"]:
print(f"\033]0;{settings['title']}\a", end="")
# Format output
if settings["format_type"] == "json":
args = json.dumps({"message": args}, indent=4)
elif settings["format_type"] == "html":
args = f"<p>{args}</p>"
# Save output to file
if settings["save_to_file"]:
with open(settings["save_to_file"], "w") as file:
file.write(args + "\n")
# Log message if needed
if settings["log_message"]:
self.log_messages.append(args)
args = self.replace_nibbits(args)
args=self._decode_escapes(args)
# Handle output & animated printing with delay
if settings["delay"]:
import sys
for char in args:
sys.stdout.write(settings["color_code"] + char)
sys.stdout.flush()
time.sleep(settings["delay"])
print("\033[0m") # Reset color
elif args.strip() == "output":
#print output in ut-8 encoding
print(self.output.encode('utf-8', errors='replace').decode('utf-8'))
else:
print(args.encode('utf-8', errors='replace').decode('utf-8'))
if self.prtdebug:
print("[DEBUG] Print Settings: ", settings)
except ValueError as e:
self.loaderrorcount+=1;self.raiseError(f"--ErrID38: Value error in prt command. Details: {e}")if getattr(self, "trystate")=="False" else print(f"[WARNING] Value error in prt command. Details: {e}, ignored due to try block.")
except Exception as e:
self.raiseError(f"[Uncategorized Error] : {e}")if getattr(self, "trystate")=="False" else print(f"[WARNING] Uncategorized Error : {e}, ignored due to try block.")
def _int_replacer(self, args):
for i in range(len(args)):
try:
expr = str(args[i]).strip()
if any(op in expr for op in ['+', '-', '*', '/']):
args[i] = int(eval(expr))
else:
args[i] = int(expr)
except:
pass
return args
def _decode_escapes(self, text):
"""Turn escape sequences like \\n into actual newlines."""
text = text.replace("\\r\\n", "\r\n")
text = text.replace("\\n", "\n")
text = text.replace("\\t", "\t")
text = text.replace("\\r", "\r")
return text
def _split_list_literal(self, text):
"""
Split a list literal safely, respecting quotes and nested brackets.
Example:
[1, 2, "Hello, world", [3,4]]
-> ['1', '2', '"Hello, world"', '[3,4]']
"""
items, buf = [], ""
depth = 0
in_quotes = None
for ch in text:
if ch in "\"'":
if in_quotes is None:
in_quotes = ch
elif in_quotes == ch:
in_quotes = None
buf += ch
elif ch == "[" and not in_quotes:
depth += 1
buf += ch
elif ch == "]" and not in_quotes:
depth -= 1
buf += ch
elif ch == "," and depth == 0 and not in_quotes:
if buf.strip():
items.append(buf.strip())
buf = ""
else:
buf += ch
if buf.strip():
items.append(buf.strip())
return items
def cmd_create_file(self, args):
parts = shlex.split(args)
if len(parts) < 2:
self.loaderrorcount += 1
self.raiseError("--ErrID50: Missing filename or content for create_file command.")if getattr(self, "trystate")=="False" else print(f"[WARNING] Missing filename or content for create_file command, ignored due to try block.")
return
filename, content = parts[0], parts[1]
content = self._decode_escapes(content)
with open(filename, 'w', encoding='utf-8', errors='replace') as f:
f.write(content)
print(f"File '{filename}' created successfully.")
def cmd_append_file(self, args):
parts = shlex.split(args)
if len(parts) < 2:
self.loaderrorcount += 1
self.raiseError("--ErrID55: Missing filename or content for append_file command.")if getattr(self, "trystate")=="False" else print(f"[WARNING] Missing filename or content for append_file command, ignored due to try block.")
return
filename, content = parts[0], parts[1]
content = self._decode_escapes(content)
with open(filename, 'a', encoding='utf-8', errors='replace') as f:
f.write(content)
print(f"Content appended to file '{filename}' successfully.")
def cmd_read_file(self, args):
"""
Reads the content of a file and prints or stores it.
Syntax: read_file filename [var_name]
"""
parts = args.split()
# Ensure the command has at least the required arguments
if len(parts) < 2:
self.loaderrorcount+=1;self.raiseError("--ErrID52: Missing filename or variable name for read_file command.")if getattr(self, "trystate")=="False" else print(f"[WARNING] Missing filename or variable name for read_file command, ignored due to try block.")
return
filename = parts[0]
# Check if the filename is a variable reference and not a quoted literal
if filename in self.variables and not (filename.startswith('"') and filename.endswith('"')):
filename = self.variables[filename][0]
try:
with open(filename, 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
var_name = parts[1] # Store the content in the specified variable
self.store_variable(var_name, content, "str")
print(f"File content stored in variable '{var_name}'.")
except FileNotFoundError:
self.loaderrorcount+=1;self.raiseError(f"--ErrID53: File '{filename}' not found.")if getattr(self, "trystate")=="False" else print(f"[WARNING] File '{filename}' not found, ignored due to try block.")
except Exception as e:
self.raiseError(f"[Unrecognised Error] Failed to read file. Error: {e}")if getattr(self, "trystate")=="False" else print(f"[WARNING] Unrecognised Error: Failed to read file. Error: {e}, ignored due to try block.")
def fetch_data_from_URL(self, url=None, timeout=20):
install_package("requests")
"""Fetch data from a given URL or from a variable in Var_Reg."""
if not url:
self.loaderrorcount+=1;self.raiseError("--ErrID11: No URL or variable provided.")if getattr(self, "trystate")=="False" else print(f"[WARNING] No URL or variable provided, ignored due to try block.")
self.output = None
return
if url in self.variables:
url = self.variables[url]
if not isinstance(url, str) or not url.strip():
self.loaderrorcount+=1;self.raiseError("--ErrID12: Invalid URL or variable key provided.")if getattr(self, "trystate")=="False" else print(f"[WARNING] Invalid URL or variable key provided, ignored due to try block.")
self.output = None
return
try:
response = requests.get(url, timeout=timeout)
response.raise_for_status()
self.output = response.text.strip() # Store the fetched data, removing any trailing whitespace
if self.reqdebug:
print(f"[DEBUG] Data fetched and stored in output: {self.output}")
except requests.exceptions.RequestException as e:
self.raiseError(f"[Unrecognised Error] Failed to fetch data from URL. Error: {e}")if getattr(self, "trystate")=="False" else print(f"[WARNING] Unrecognised Error: Failed to fetch data from URL. Error: {e}, ignored due to try block.")
def store_variable(self, var_name, value, data_type, local=False):