-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinterpreter.py
More file actions
1862 lines (1628 loc) · 80.2 KB
/
interpreter.py
File metadata and controls
1862 lines (1628 loc) · 80.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
import time
import sys
import os
import threading
import queue
from typing import Dict, Any, Optional, List, Union
from ast_nodes import *
from enum import Enum, auto
class ControlFlow(Exception):
pass
class BreakException(ControlFlow):
pass
class ContinueException(ControlFlow):
pass
class ExitException(ControlFlow):
pass
class ReturnException(ControlFlow):
def __init__(self, value=None):
self.value = value
class BlockStatus(Enum):
STOPPED = auto()
RUNNING = auto()
COMPLETED = auto()
class Block:
def __init__(self, name: str, body: List[Statement], iterations: Union[int, tuple, None] = None, block_type: str = "fo", is_parallel: bool = False):
self.name = name
self.body = body
self.iterations = iterations # Can be int, ('var', varname), or None
self.current_iteration = 0
self.status = BlockStatus.STOPPED
self.block_type = block_type # "os", "de", "fo"
self.is_parallel = is_parallel
self.thread = None
self.should_stop = threading.Event()
# Save/restore functionality
self.saved_iteration = None
self.saved_status = None
self.has_saved_state = False
def reset(self):
self.current_iteration = 0
self.status = BlockStatus.STOPPED
self.should_stop.clear()
if self.thread and self.thread.is_alive():
self.should_stop.set()
self.thread.join(timeout=1.0)
def save_state(self):
"""Save current execution state"""
self.saved_iteration = self.current_iteration
self.saved_status = self.status
self.has_saved_state = True
def restore_state(self):
"""Restore execution state from saved checkpoint"""
if self.has_saved_state:
self.current_iteration = self.saved_iteration
self.status = self.saved_status
return True
return False
def clear_saved_state(self):
"""Clear saved state"""
self.saved_iteration = None
self.saved_status = None
self.has_saved_state = False
def discard_saved_state(self):
"""Discard saved state and return whether there was state to discard"""
if self.has_saved_state:
self.clear_saved_state()
return True
return False
class Interpreter:
def __init__(self, enable_hot_reload=False, source_file=None):
self.global_vars: Dict[str, Any] = {}
self.functions: Dict[str, FuncDeclaration] = {}
self.classes: Dict[str, ClassDeclaration] = {}
self.blocks: Dict[str, Block] = {}
self.running_blocks: List[str] = []
self.exit_requested = False
self.modules: Dict[str, Any] = {}
self.module_namespaces: Dict[str, Dict[str, Any]] = {} # Store module namespaces
self.function_modules: Dict[str, str] = {} # Track which module a function belongs to
self.current_module: Optional[str] = None # Track current executing module
self.global_vars_lock = threading.Lock()
self.parallel_threads: List[threading.Thread] = []
self.hot_reloader = None
self.enable_hot_reload = enable_hot_reload
self.source_file = source_file
# Add built-in functions for error handling
self.setup_builtins()
def setup_builtins(self):
"""Set up built-in functions for error handling and utilities."""
# safe_call: Safely call a function and return (success, result/error)
def safe_call(func, *args, **kwargs):
try:
result = func(*args, **kwargs)
return {"success": True, "result": result, "error": None}
except Exception as e:
return {"success": False, "result": None, "error": str(e), "error_type": type(e).__name__}
# get_error: Extract error from safe_call result
def get_error(result):
if isinstance(result, dict) and "error" in result:
return result.get("error", None)
return None
# is_success: Check if safe_call succeeded
def is_success(result):
if isinstance(result, dict) and "success" in result:
return result["success"]
return False
# get_result: Extract result from safe_call
def get_result(result):
if isinstance(result, dict) and "result" in result:
return result["result"]
return None
# has_attr: Check if object has attribute (safe hasattr)
def has_attr(obj, attr_name):
try:
return hasattr(obj, attr_name)
except:
return False
# safe_getattr: Safely get attribute from object
def safe_getattr(obj, attr_name, default=None):
try:
return getattr(obj, attr_name, default)
except:
return default
# type_of: Get type name of object
def type_of(obj):
return type(obj).__name__
# is_type: Check if object is of certain type
def is_type(obj, type_name):
return type(obj).__name__ == type_name
# chr: Convert integer to character
def chr_func(i):
return chr(i)
# ord: Convert character to integer
def ord_func(c):
return ord(c)
# repr: Get string representation
def repr_func(obj):
return repr(obj)
# exit: Exit the program
def exit_func():
raise ExitException()
# open: Python's built-in open function
open_func = open
# ==== TUPLE AND COLLECTION BUILT-INS ====
# tuple: Convert to tuple
tuple_func = tuple
# list: Convert to list
list_func = list
# dict: Create dictionary
dict_func = dict
# set: Create set
set_func = set
# frozenset: Create immutable set
frozenset_func = frozenset
# len: Get length
len_func = len
# min: Get minimum value
min_func = min
# max: Get maximum value
max_func = max
# sum: Sum of elements
sum_func = sum
# sorted: Return sorted list
sorted_func = sorted
# reversed: Return reversed iterator
reversed_func = reversed
# enumerate: Return enumerated pairs
enumerate_func = enumerate
# zip: Zip iterables together
zip_func = zip
# all: Check if all elements are true
all_func = all
# any: Check if any element is true
any_func = any
# filter: Filter elements
filter_func = filter
# map: Map function over iterable
map_func = map
# range: Generate range of numbers
range_func = range
# slice: Create slice object
slice_func = slice
# iter: Get iterator
iter_func = iter
# next: Get next item from iterator
next_func = next
# abs: Absolute value
abs_func = abs
# round: Round number
round_func = round
# int: Convert to integer
int_func = int
# float: Convert to float
float_func = float
# str: Convert to string
str_func = str
# bool: Convert to boolean
bool_func = bool
# bytes: Create bytes object
bytes_func = bytes
# bytearray: Create mutable bytes
bytearray_func = bytearray
# hex: Convert to hexadecimal
hex_func = hex
# bin: Convert to binary
bin_func = bin
# oct: Convert to octal
oct_func = oct
# hash: Get hash value
hash_func = hash
# id: Get object identity
id_func = id
# divmod: Division and modulo
divmod_func = divmod
# pow: Power function
pow_func = pow
# callable: Check if object is callable
callable_func = callable
# getattr/setattr/delattr/hasattr
getattr_func = getattr
setattr_func = setattr
delattr_func = delattr
hasattr_func = hasattr
# dir: Get attributes
dir_func = dir
# help: Get help (limited in WHEN)
def help_func(obj=None):
if obj is None:
return "WHEN Language Help - Use help(object) for object help"
return f"Help for {type(obj).__name__}: {dir(obj)[:10]}..."
# input: Get user input
input_func = input
# print: Already available, but let's be explicit
print_func = print
# format: Format strings
format_func = format
# eval: Evaluate expression (be careful!)
# We'll make a safer version
def eval_func(expr_str):
# Parse and evaluate WHEN expression
from lexer import Lexer
from parser import Parser
try:
lexer = Lexer(expr_str)
tokens = lexer.tokenize()
parser = Parser(tokens)
# Try to parse as expression
parser.pos = 0 # Reset position
expr = parser.parse_expression()
return self.eval_expression(expr)
except:
raise ValueError(f"Cannot evaluate expression: {expr_str}")
# exec: Execute statements (disabled for safety)
def exec_func(code):
raise NotImplementedError("exec() is not supported in WHEN for security reasons")
# Add all built-ins to global vars
self.global_vars["safe_call"] = safe_call
self.global_vars["get_error"] = get_error
self.global_vars["is_success"] = is_success
self.global_vars["get_result"] = get_result
self.global_vars["has_attr"] = has_attr
self.global_vars["safe_getattr"] = safe_getattr
self.global_vars["type_of"] = type_of
self.global_vars["is_type"] = is_type
self.global_vars["isinstance"] = isinstance # Add Python's isinstance too
self.global_vars["type"] = type # Add Python's type too
self.global_vars["chr"] = chr_func # Character conversion
self.global_vars["ord"] = ord_func # Inverse of chr
self.global_vars["repr"] = repr_func # String representation
self.global_vars["exit"] = exit_func # Exit program
self.global_vars["open"] = open_func # File operations
# Collection and sequence functions
self.global_vars["tuple"] = tuple_func
self.global_vars["list"] = list_func
self.global_vars["dict"] = dict_func
self.global_vars["set"] = set_func
self.global_vars["frozenset"] = frozenset_func
self.global_vars["len"] = len_func
self.global_vars["min"] = min_func
self.global_vars["max"] = max_func
self.global_vars["sum"] = sum_func
self.global_vars["sorted"] = sorted_func
self.global_vars["reversed"] = reversed_func
self.global_vars["enumerate"] = enumerate_func
self.global_vars["zip"] = zip_func
self.global_vars["all"] = all_func
self.global_vars["any"] = any_func
self.global_vars["filter"] = filter_func
self.global_vars["map"] = map_func
self.global_vars["range"] = range_func
self.global_vars["slice"] = slice_func
self.global_vars["iter"] = iter_func
self.global_vars["next"] = next_func
# Numeric functions
self.global_vars["abs"] = abs_func
self.global_vars["round"] = round_func
self.global_vars["divmod"] = divmod_func
self.global_vars["pow"] = pow_func
# Type conversion
self.global_vars["int"] = int_func
self.global_vars["float"] = float_func
self.global_vars["str"] = str_func
self.global_vars["bool"] = bool_func
self.global_vars["bytes"] = bytes_func
self.global_vars["bytearray"] = bytearray_func
# String formatting
self.global_vars["hex"] = hex_func
self.global_vars["bin"] = bin_func
self.global_vars["oct"] = oct_func
self.global_vars["format"] = format_func
# Object introspection
self.global_vars["hash"] = hash_func
self.global_vars["id"] = id_func
self.global_vars["callable"] = callable_func
self.global_vars["getattr"] = getattr_func
self.global_vars["setattr"] = setattr_func
self.global_vars["delattr"] = delattr_func
self.global_vars["hasattr"] = hasattr_func
self.global_vars["dir"] = dir_func
# I/O and help
self.global_vars["help"] = help_func
self.global_vars["input"] = input_func
self.global_vars["print"] = print_func
# Eval/exec (with limitations)
self.global_vars["eval"] = eval_func
self.global_vars["exec"] = exec_func
def interpret(self, program: Program):
# Process declarations
for decl in program.declarations:
if isinstance(decl, TupleUnpackingAssignment):
# Handle tuple unpacking at global level
value = self.eval_expression(decl.value)
if hasattr(value, '__iter__') and not isinstance(value, str):
values = list(value)
else:
raise ValueError(f"Cannot unpack non-iterable {type(value).__name__} value")
if len(values) != len(decl.targets):
raise ValueError(f"Too many values to unpack (expected {len(decl.targets)}, got {len(values)})")
for target, val in zip(decl.targets, values):
self.global_vars[target] = val
elif isinstance(decl, VarDeclaration):
self.global_vars[decl.name] = self.eval_expression(decl.value)
elif isinstance(decl, FuncDeclaration):
self.functions[decl.name] = decl
elif isinstance(decl, ClassDeclaration):
self.classes[decl.name] = decl
# Create a class constructor function with proper closure
def make_constructor(class_decl):
return lambda *args, **kwargs: self.instantiate_class(class_decl, args, kwargs)
self.global_vars[decl.name] = make_constructor(decl)
elif isinstance(decl, ImportDeclaration):
self.handle_import(decl)
elif isinstance(decl, FromImportDeclaration):
self.handle_from_import(decl)
# Register blocks (check specific types first!)
for block in program.blocks:
if isinstance(block, OSBlock):
self.blocks[block.name] = Block(block.name, block.body, None, "os", False)
elif isinstance(block, ParallelDEBlock):
# Check if iterations is a variable name (stored as string from parser)
if isinstance(block.iterations, str):
iterations = ('var', block.iterations)
else:
iterations = block.iterations
self.blocks[block.name] = Block(block.name, block.body, iterations, "de", True)
elif isinstance(block, ParallelFOBlock):
self.blocks[block.name] = Block(block.name, block.body, None, "fo", True)
elif isinstance(block, DEBlock):
# Check if iterations is a variable name (stored as string from parser)
if isinstance(block.iterations, str):
iterations = ('var', block.iterations)
else:
iterations = block.iterations
self.blocks[block.name] = Block(block.name, block.body, iterations, "de", False)
else: # Regular FOBlock
self.blocks[block.name] = Block(block.name, block.body, None, "fo", False)
# Setup hot reload if enabled
if self.enable_hot_reload and self.source_file:
from hot_reload import HotReloader
self.hot_reloader = HotReloader(self, self.source_file)
self.hot_reloader.start_watching()
# Execute main block
try:
self.execute_main(program.main)
except ExitException:
print("Program exited")
finally:
# Stop hot reload if active
if self.hot_reloader:
self.hot_reloader.stop_watching()
# Clean up parallel threads
self.cleanup_parallel_threads()
def execute_main(self, main_block: MainBlock):
while not self.exit_requested:
try:
# Execute main block body
self.execute_statements(main_block.body)
# Execute one iteration of each running block (cooperative scheduling)
for block_name in list(self.running_blocks):
block = self.blocks[block_name]
if block.status == BlockStatus.RUNNING:
self.execute_block_iteration(block)
except ContinueException:
continue
except BreakException:
break
except ExitException:
raise
def resolve_block_iterations(self, block: Block) -> int:
"""Resolve the iteration count for a DE block"""
if block.iterations is None:
return None
if isinstance(block.iterations, int):
return block.iterations
if isinstance(block.iterations, tuple) and block.iterations[0] == 'var':
var_name = block.iterations[1]
if var_name in self.global_vars:
value = self.global_vars[var_name]
try:
return int(value)
except (TypeError, ValueError):
raise ValueError(f"Variable '{var_name}' cannot be converted to iteration count: {value}")
else:
raise NameError(f"Iteration variable '{var_name}' not defined")
return block.iterations
def execute_block_iteration(self, block: Block):
if block.status != BlockStatus.RUNNING:
return
# Resolve iterations if needed
iterations = self.resolve_block_iterations(block)
# For DE blocks, check if we've already completed all iterations
if iterations is not None and block.current_iteration >= iterations:
block.status = BlockStatus.COMPLETED
if block.name in self.running_blocks:
self.running_blocks.remove(block.name)
return
try:
# Set module context if this block is from a module
saved_module = self.current_module
if '.' in block.name:
# Block name includes module prefix (e.g., "whGame.game_loop")
module_name = block.name.split('.')[0]
if module_name in self.module_namespaces:
self.current_module = module_name
# Execute one iteration
self.execute_statements(block.body)
# Increment iteration counter AFTER successful execution
if iterations is not None:
block.current_iteration += 1
# Check if we've now completed all iterations
if block.current_iteration >= iterations:
block.status = BlockStatus.COMPLETED
if block.name in self.running_blocks:
self.running_blocks.remove(block.name)
except ContinueException:
# Continue still counts as an iteration
if iterations is not None:
block.current_iteration += 1
if block.current_iteration >= iterations:
block.status = BlockStatus.COMPLETED
if block.name in self.running_blocks:
self.running_blocks.remove(block.name)
except BreakException:
# Break stops the block regardless of remaining iterations
block.status = BlockStatus.STOPPED
if block.name in self.running_blocks:
self.running_blocks.remove(block.name)
finally:
# Restore module context
if '.' in block.name:
self.current_module = saved_module
def execute_statements(self, statements: List[Statement]):
for stmt in statements:
self.execute_statement(stmt)
def execute_statement(self, stmt: Statement):
if isinstance(stmt, ExpressionStatement):
self.eval_expression(stmt.expr)
elif isinstance(stmt, TupleUnpackingAssignment):
# Handle tuple unpacking: a, b, c = expr
value = self.eval_expression(stmt.value)
# Convert value to list/tuple if it's iterable
if hasattr(value, '__iter__') and not isinstance(value, str):
values = list(value)
else:
raise ValueError(f"Cannot unpack non-iterable {type(value).__name__} value")
# Check length match
if len(values) != len(stmt.targets):
raise ValueError(f"Too many values to unpack (expected {len(stmt.targets)}, got {len(values)})")
# Assign each value to corresponding target
with self.global_vars_lock:
for target, val in zip(stmt.targets, values):
if self.current_module and self.current_module in self.module_namespaces:
self.module_namespaces[self.current_module][target] = val
if self.current_module in self.modules:
setattr(self.modules[self.current_module], target, val)
else:
self.global_vars[target] = val
elif isinstance(stmt, Assignment):
value = self.eval_expression(stmt.value)
with self.global_vars_lock:
# In module context, ALL assignments go to module namespace
# (including those marked global - they're global TO THE MODULE)
if self.current_module and self.current_module in self.module_namespaces:
# print(f"[DEBUG] Updating module '{self.current_module}' var '{stmt.name}' = {value}")
self.module_namespaces[self.current_module][stmt.name] = value
# Also update the module object if it exists
if self.current_module in self.modules:
setattr(self.modules[self.current_module], stmt.name, value)
else:
# Otherwise use interpreter global scope
# print(f"[DEBUG] Updating global var '{stmt.name}' = {value} (module: {self.current_module})")
self.global_vars[stmt.name] = value
elif isinstance(stmt, IndexAssignment):
obj = self.eval_expression(stmt.object)
index = self.eval_expression(stmt.index)
value = self.eval_expression(stmt.value)
obj[index] = value
elif isinstance(stmt, AttributeAssignment):
obj = self.eval_expression(stmt.object)
value = self.eval_expression(stmt.value)
# Set the attribute on the object
setattr(obj, stmt.attribute, value)
elif isinstance(stmt, WhenStatement):
condition_result = self.eval_expression(stmt.condition)
if condition_result:
self.execute_statements(stmt.body)
elif isinstance(stmt, WithStatement):
# Execute with statement (context manager)
context = self.eval_expression(stmt.context_expr)
# Check if it has __enter__ and __exit__ methods
if hasattr(context, '__enter__') and hasattr(context, '__exit__'):
# Use the context manager protocol
value = context.__enter__()
# Store in variable if 'as' clause is present
if stmt.var_name:
with self.global_vars_lock:
if self.current_module and self.current_module in self.module_namespaces:
self.module_namespaces[self.current_module][stmt.var_name] = value
else:
self.global_vars[stmt.var_name] = value
try:
# Execute the body
self.execute_statements(stmt.body)
except Exception as e:
# Call __exit__ with exception info
if not context.__exit__(type(e), e, None):
raise
else:
# Call __exit__ with no exception
context.__exit__(None, None, None)
else:
# Simple assignment without context manager protocol
if stmt.var_name:
with self.global_vars_lock:
if self.current_module and self.current_module in self.module_namespaces:
self.module_namespaces[self.current_module][stmt.var_name] = context
else:
self.global_vars[stmt.var_name] = context
# Execute the body
self.execute_statements(stmt.body)
elif isinstance(stmt, BreakStatement):
raise BreakException()
elif isinstance(stmt, ContinueStatement):
raise ContinueException()
elif isinstance(stmt, ExitStatement):
self.exit_requested = True
raise ExitException()
elif isinstance(stmt, PassStatement):
pass
elif isinstance(stmt, ReturnStatement):
if len(stmt.values) == 0:
value = None
elif len(stmt.values) == 1:
value = self.eval_expression(stmt.values[0])
else:
# Multiple return values - return as tuple
value = tuple(self.eval_expression(val) for val in stmt.values)
raise ReturnException(value)
elif isinstance(stmt, GlobalStatement):
# Global statements mark variables as global in local scope
# Store the global declaration for function context
for name in stmt.names:
if not hasattr(self, 'current_globals'):
self.current_globals = set()
self.current_globals.add(name)
def eval_expression(self, expr: Expression) -> Any:
if isinstance(expr, NumberLiteral):
return expr.value
elif isinstance(expr, StringLiteral):
return expr.value
elif isinstance(expr, FStringLiteral):
return self.eval_fstring(expr)
elif isinstance(expr, BooleanLiteral):
return expr.value
elif isinstance(expr, NoneLiteral):
return None
elif isinstance(expr, ListLiteral):
return [self.eval_expression(elem) for elem in expr.elements]
elif isinstance(expr, TupleLiteral):
return tuple(self.eval_expression(elem) for elem in expr.elements)
elif isinstance(expr, DictLiteral):
return {self.eval_expression(k): self.eval_expression(v)
for k, v in zip(expr.keys, expr.values)}
elif isinstance(expr, SliceExpression):
obj = self.eval_expression(expr.object)
start = self.eval_expression(expr.start) if expr.start else None
stop = self.eval_expression(expr.stop) if expr.stop else None
step = self.eval_expression(expr.step) if expr.step else None
if step is not None:
return obj[start:stop:step]
else:
return obj[start:stop]
elif isinstance(expr, IndexExpression):
obj = self.eval_expression(expr.object)
index = self.eval_expression(expr.index)
return obj[index]
elif isinstance(expr, UnaryOp):
operand = self.eval_expression(expr.operand)
if expr.operator == '-':
return -operand
elif expr.operator == 'not':
return not operand
else:
raise NotImplementedError(f"Unary operator {expr.operator} not implemented")
elif isinstance(expr, TernaryOp):
condition = self.eval_expression(expr.condition)
if condition:
return self.eval_expression(expr.true_expr)
else:
return self.eval_expression(expr.false_expr)
elif isinstance(expr, Identifier):
with self.global_vars_lock:
# If in module context, check module namespace first
if self.current_module and self.current_module in self.module_namespaces:
if expr.name in self.module_namespaces[self.current_module]:
return self.module_namespaces[self.current_module][expr.name]
# Then check global vars
if expr.name in self.global_vars:
return self.global_vars[expr.name]
# Check if it's a function name being referenced
if expr.name in self.functions:
# Return a callable wrapper for WHEN functions
func = self.functions[expr.name]
def when_function_wrapper(*args, **kwargs):
# Convert args to Expression objects if they're not already
arg_exprs = []
for arg in args:
if hasattr(arg, '__dict__') and hasattr(arg, 'type'):
# This is likely a tkinter event object - pass it through
# Create a special identifier that resolves to this object
from ast_nodes import Identifier
temp_var_name = f"_temp_arg_{id(arg)}"
self.global_vars[temp_var_name] = arg
arg_exprs.append(Identifier(temp_var_name))
else:
# Regular value - wrap in a literal expression
from ast_nodes import NumberLiteral, StringLiteral, BooleanLiteral
if isinstance(arg, (int, float)):
arg_exprs.append(NumberLiteral(arg))
elif isinstance(arg, str):
arg_exprs.append(StringLiteral(arg))
elif isinstance(arg, bool):
arg_exprs.append(BooleanLiteral(arg))
else:
# Store as temporary variable
temp_var_name = f"_temp_arg_{id(arg)}"
self.global_vars[temp_var_name] = arg
arg_exprs.append(Identifier(temp_var_name))
return self.call_function(expr.name, arg_exprs, [])
return when_function_wrapper
raise NameError(f"Variable '{expr.name}' not defined")
elif isinstance(expr, BinaryOp):
left = self.eval_expression(expr.left)
right = self.eval_expression(expr.right)
return self.apply_binary_op(left, expr.operator, right)
elif isinstance(expr, CallExpression):
return self.call_function(expr.name, expr.args, expr.kwargs)
elif isinstance(expr, StartExpression):
self.start_block(expr.block_name)
return None
elif isinstance(expr, StopExpression):
self.stop_block(expr.block_name)
return None
elif isinstance(expr, SaveExpression):
self.save_block(expr.block_name)
return None
elif isinstance(expr, SaveStopExpression):
self.save_stop_block(expr.block_name)
return None
elif isinstance(expr, StartSaveExpression):
self.start_save_block(expr.block_name)
return None
elif isinstance(expr, DiscardExpression):
self.discard_block(expr.block_name)
return None
elif isinstance(expr, MemberAccess):
# Special handling for block property access
if isinstance(expr.object, Identifier) and expr.object.name in self.blocks:
block = self.blocks[expr.object.name]
if expr.member == "current_iteration":
return block.current_iteration
elif expr.member == "status":
return block.status.name
elif expr.member == "iterations":
return self.resolve_block_iterations(block)
elif expr.member == "has_saved_state":
return block.has_saved_state
else:
raise AttributeError(f"Block '{expr.object.name}' has no attribute '{expr.member}'")
else:
obj = self.eval_expression(expr.object)
attr = getattr(obj, expr.member)
# If it's a FuncDeclaration from a module, return a callable wrapper
if isinstance(attr, FuncDeclaration):
# Store it in functions so it can be called
func_name = f"{expr.object.name if isinstance(expr.object, Identifier) else 'module'}.{expr.member}"
self.functions[func_name] = attr
# Return the function name so CallExpression can find it
return func_name
return attr
elif isinstance(expr, MethodCall):
# DEBUG
# if expr.method == "is_key_pressed":
# print(f"[DEBUG MethodCall] is_key_pressed args={expr.args}, first arg={expr.args[0] if expr.args else None}")
# Check if this is a block method from a module
if isinstance(expr.object, MemberAccess):
# It might be module.block.start()
module_obj = self.eval_expression(expr.object.object)
attr = getattr(module_obj, expr.object.member)
if isinstance(attr, Block):
# It's a block method call
if expr.method == "start":
self.start_block(attr.name)
return None
elif expr.method == "stop":
self.stop_block(attr.name)
return None
else:
raise AttributeError(f"Block has no method '{expr.method}'")
obj = self.eval_expression(expr.object)
# If obj is a Block, handle its methods
if isinstance(obj, Block):
if expr.method == "start":
self.start_block(obj.name)
return None
elif expr.method == "stop":
self.stop_block(obj.name)
return None
else:
raise AttributeError(f"Block has no method '{expr.method}'")
method = getattr(obj, expr.method)
# If the method is a FuncDeclaration from a module, call it properly
if isinstance(method, FuncDeclaration):
# Create a qualified name for the function
if isinstance(expr.object, Identifier):
func_name = f"{expr.object.name}.{expr.method}"
else:
func_name = expr.method
# Register the function if needed
if func_name not in self.functions:
self.functions[func_name] = method
# Track its module if the object is a module
if isinstance(expr.object, Identifier) and expr.object.name in self.modules:
self.function_modules[func_name] = expr.object.name
# Call it through our function call mechanism
# print(f"[DEBUG] Calling function '{func_name}' via MethodCall")
return self.call_function(func_name, expr.args, expr.kwargs)
# Regular method call
args = []
for arg in expr.args:
arg_value = self.eval_expression(arg)
# Wrap FuncDeclaration objects in Python callables for tkinter compatibility
if isinstance(arg_value, FuncDeclaration):
# Create a wrapper that tkinter can call
def make_wrapper(func_decl, interpreter):
def wrapper(event=None):
# When functions expect an event parameter
# We need to pass it as a variable, not an argument
func_name = func_decl.name
# Save current event if exists
saved_event = None
for fname, mod in interpreter.function_modules.items():
if fname.endswith(f".{func_name}") or fname == func_name:
# Function belongs to a module
if mod in interpreter.module_namespaces:
if 'event' in interpreter.module_namespaces[mod]:
saved_event = interpreter.module_namespaces[mod]['event']
# Set event in module namespace
if event:
interpreter.module_namespaces[mod]['event'] = event
old_module = interpreter.current_module
interpreter.current_module = mod
try:
# Call function - it will access event from module namespace
from ast_nodes import Identifier, MemberAccess
# Create an expression that represents the event parameter
event_expr = Identifier('event') if event else None
args = [event_expr] if event_expr and func_decl.params and len(func_decl.params) > 0 else []
result = interpreter.call_function(fname, args)
finally:
interpreter.current_module = old_module
# Restore saved event
if mod in interpreter.module_namespaces:
if saved_event is not None:
interpreter.module_namespaces[mod]['event'] = saved_event
elif 'event' in interpreter.module_namespaces[mod] and event:
del interpreter.module_namespaces[mod]['event']
return result
# If not found in modules, try global
if 'event' in interpreter.global_vars:
saved_event = interpreter.global_vars['event']
if event:
interpreter.global_vars['event'] = event
try:
from ast_nodes import Identifier
event_expr = Identifier('event') if event else None
args = [event_expr] if event_expr and func_decl.params and len(func_decl.params) > 0 else []
return interpreter.call_function(func_name, args)
finally:
if saved_event is not None:
interpreter.global_vars['event'] = saved_event
elif 'event' in interpreter.global_vars and event:
del interpreter.global_vars['event']
return wrapper
arg_value = make_wrapper(arg_value, self)
args.append(arg_value)
# Handle keyword arguments
kwargs = {}
if expr.kwargs:
for kw in expr.kwargs:
kwargs[kw.name] = self.eval_expression(kw.value)
return method(*args, **kwargs)
else:
raise NotImplementedError(f"Expression type {type(expr)} not implemented")
def eval_fstring(self, fstring: FStringLiteral) -> str:
"""Evaluate an f-string by processing its parts"""
result = ""
for part_type, part_value in fstring.parts:
if part_type == 'str':
result += part_value
elif part_type == 'expr':
# Parse and evaluate the expression
try:
from lexer import Lexer
from parser import Parser
# Tokenize the expression
lexer = Lexer(part_value)
tokens = lexer.tokenize()
# Parse as expression
parser = Parser(tokens)
expr = parser.parse_expression()
# Evaluate and convert to string
value = self.eval_expression(expr)
result += str(value)
except Exception as e:
# If evaluation fails, include the error in the string
result += f"{{ERROR: {e}}}"
return result
def apply_binary_op(self, left: Any, op: str, right: Any) -> Any:
if op == '+':
return left + right # Works for numbers AND strings!
elif op == '-':
return left - right
elif op == '*':
return left * right
elif op == '/':
return left / right
elif op == '//':