IncludeCPP 3.8.0__py3-none-any.whl → 3.8.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -715,17 +715,60 @@ class CSSLRuntime:
715
715
 
716
716
  Parses class members and methods, creating a CSSLClass object
717
717
  that can be instantiated with 'new'.
718
+ Supports inheritance via 'extends' keyword and method overwriting via 'overwrites'.
718
719
  """
719
720
  class_info = node.value
720
721
  class_name = class_info.get('name')
722
+ extends_class_name = class_info.get('extends')
723
+ extends_is_python = class_info.get('extends_is_python', False)
724
+ overwrites_class_name = class_info.get('overwrites')
725
+ overwrites_is_python = class_info.get('overwrites_is_python', False)
726
+
727
+ # Resolve parent class if extends is specified
728
+ parent_class = None
729
+ if extends_class_name:
730
+ if extends_is_python:
731
+ # extends $PythonObject - look up in shared objects
732
+ from ..cssl_bridge import _live_objects, SharedObjectProxy
733
+ if extends_class_name in _live_objects:
734
+ parent_class = _live_objects[extends_class_name]
735
+ # Unwrap SharedObjectProxy if needed
736
+ if isinstance(parent_class, SharedObjectProxy):
737
+ parent_class = parent_class._obj
738
+ else:
739
+ # Also check scope with $ prefix
740
+ parent_class = self.global_scope.get(f'${extends_class_name}')
741
+ else:
742
+ # Try to resolve from scope (could be CSSL class or variable holding Python object)
743
+ parent_class = self.scope.get(extends_class_name)
744
+ if parent_class is None:
745
+ parent_class = self.global_scope.get(extends_class_name)
746
+
747
+ if parent_class is None:
748
+ raise ValueError(f"Cannot extend unknown class '{extends_class_name}'")
749
+
750
+ # Auto-wrap Python objects for inheritance
751
+ from .cssl_builtins import CSSLizedPythonObject
752
+ if not isinstance(parent_class, (CSSLClass, CSSLizedPythonObject)):
753
+ # Wrap raw Python object
754
+ parent_class = CSSLizedPythonObject(parent_class, self)
721
755
 
722
756
  members = {} # Member variable defaults/types
723
757
  methods = {} # Method AST nodes
724
- constructor = None
758
+ constructors = [] # List of constructors (multiple allowed with constr keyword)
759
+ constructor = None # Primary constructor (backward compatibility)
760
+
761
+ # Get class parameters and extends args
762
+ class_params = class_info.get('class_params', [])
763
+ extends_args = class_info.get('extends_args', [])
725
764
 
726
765
  for child in node.children:
727
- if child.type == 'function':
728
- # This is a method
766
+ if child.type == 'constructor':
767
+ # New-style constructor from 'constr' keyword
768
+ constructors.append(child)
769
+
770
+ elif child.type == 'function':
771
+ # This is a method or old-style constructor
729
772
  func_info = child.value
730
773
  method_name = func_info.get('name')
731
774
 
@@ -752,32 +795,170 @@ class CSSLRuntime:
752
795
  name=class_name,
753
796
  members=members,
754
797
  methods=methods,
755
- constructor=constructor
798
+ constructor=constructor,
799
+ parent=parent_class
756
800
  )
801
+ # Store additional constructor info
802
+ class_def.constructors = constructors # Multiple constructors from 'constr' keyword
803
+ class_def.class_params = class_params # Class-level constructor parameters
804
+ class_def.extends_args = extends_args # Arguments to pass to parent constructor
757
805
 
758
806
  # Register class in scope
759
807
  self.scope.set(class_name, class_def)
760
808
  self.global_scope.set(class_name, class_def)
761
809
 
810
+ # Handle class overwrites - replace methods in target class
811
+ if overwrites_class_name:
812
+ self._apply_class_overwrites(
813
+ class_def, overwrites_class_name, overwrites_is_python
814
+ )
815
+
762
816
  return class_def
763
817
 
818
+ def _apply_class_overwrites(self, new_class: CSSLClass, target_name: str, is_python: bool):
819
+ """Apply method overwrites from new_class to target class/object.
820
+
821
+ When a class has 'overwrites' specified, all methods defined in new_class
822
+ will replace the corresponding methods in the target.
823
+ """
824
+ from .cssl_builtins import CSSLizedPythonObject
825
+
826
+ # Resolve target
827
+ target = None
828
+ if is_python:
829
+ from ..cssl_bridge import _live_objects
830
+ if target_name in _live_objects:
831
+ target = _live_objects[target_name]
832
+ else:
833
+ target = self.scope.get(target_name)
834
+ if target is None:
835
+ target = self.global_scope.get(target_name)
836
+
837
+ if target is None:
838
+ return # Target not found, silently skip
839
+
840
+ # Get methods to overwrite
841
+ methods_to_overwrite = new_class.methods
842
+
843
+ if is_python and hasattr(target, '__class__'):
844
+ # Python object - overwrite methods on the object/class
845
+ for method_name, method_node in methods_to_overwrite.items():
846
+ # Create a Python-callable wrapper for the CSSL method
847
+ wrapper = self._create_method_wrapper(method_node, target)
848
+ # Set on the object
849
+ try:
850
+ setattr(target, method_name, wrapper)
851
+ except AttributeError:
852
+ # Try setting on class instead
853
+ try:
854
+ setattr(target.__class__, method_name, wrapper)
855
+ except:
856
+ pass
857
+ elif isinstance(target, CSSLClass):
858
+ # CSSL class - directly replace methods
859
+ for method_name, method_node in methods_to_overwrite.items():
860
+ target.methods[method_name] = method_node
861
+ elif isinstance(target, CSSLizedPythonObject):
862
+ # CSSLized Python object - get underlying object and overwrite
863
+ py_obj = target.get_python_obj()
864
+ for method_name, method_node in methods_to_overwrite.items():
865
+ wrapper = self._create_method_wrapper(method_node, py_obj)
866
+ try:
867
+ setattr(py_obj, method_name, wrapper)
868
+ except AttributeError:
869
+ try:
870
+ setattr(py_obj.__class__, method_name, wrapper)
871
+ except:
872
+ pass
873
+
874
+ def _create_method_wrapper(self, method_node: ASTNode, instance: Any):
875
+ """Create a Python-callable wrapper for a CSSL method that works with an instance."""
876
+ def wrapper(*args, **kwargs):
877
+ # Set up instance context for this->
878
+ old_instance = self._current_instance
879
+ # Create a fake CSSLInstance-like wrapper if needed
880
+ self._current_instance = instance
881
+ try:
882
+ return self._call_function(method_node, list(args), kwargs)
883
+ finally:
884
+ self._current_instance = old_instance
885
+ return wrapper
886
+
764
887
  def _exec_function(self, node: ASTNode) -> Any:
765
- """Execute function definition - just registers it"""
888
+ """Execute function definition - registers it and handles extends/overwrites.
889
+
890
+ Syntax:
891
+ define func() { ... }
892
+ define func : extends otherFunc() { ... } - Inherit local vars
893
+ define func : overwrites otherFunc() { ... } - Replace otherFunc
894
+ """
766
895
  func_info = node.value
767
896
  func_name = func_info.get('name')
897
+ extends_func = func_info.get('extends')
898
+ extends_is_python = func_info.get('extends_is_python', False)
899
+ overwrites_func = func_info.get('overwrites')
900
+ overwrites_is_python = func_info.get('overwrites_is_python', False)
901
+
902
+ # Store function extends info for runtime use
903
+ if extends_func:
904
+ node.value['_extends_resolved'] = self._resolve_function_target(
905
+ extends_func, extends_is_python
906
+ )
907
+
908
+ # Handle overwrites - replace the target function
909
+ if overwrites_func:
910
+ target = self._resolve_function_target(overwrites_func, overwrites_is_python)
911
+ if target is not None:
912
+ # Store original for reference
913
+ node.value['_overwrites_original'] = target
914
+ # Replace the target function with this one
915
+ if overwrites_is_python:
916
+ from ..cssl_bridge import _live_objects
917
+ if overwrites_func in _live_objects:
918
+ # Create a wrapper that calls the CSSL function
919
+ _live_objects[overwrites_func] = self._create_python_wrapper(node)
920
+ else:
921
+ # Replace in CSSL scope
922
+ self.scope.set(overwrites_func, node)
923
+ self.global_scope.set(overwrites_func, node)
924
+
925
+ # Register the function
768
926
  self.scope.set(func_name, node)
769
927
  return None
770
928
 
929
+ def _resolve_function_target(self, name: str, is_python: bool) -> Any:
930
+ """Resolve a function target for extends/overwrites."""
931
+ if is_python:
932
+ from ..cssl_bridge import _live_objects
933
+ if name in _live_objects:
934
+ return _live_objects[name]
935
+ return self.global_scope.get(f'${name}')
936
+ else:
937
+ target = self.scope.get(name)
938
+ if target is None:
939
+ target = self.global_scope.get(name)
940
+ return target
941
+
942
+ def _create_python_wrapper(self, func_node: ASTNode):
943
+ """Create a Python-callable wrapper for a CSSL function."""
944
+ def wrapper(*args, **kwargs):
945
+ return self._call_function(func_node, list(args), kwargs)
946
+ return wrapper
947
+
771
948
  def _exec_typed_declaration(self, node: ASTNode) -> Any:
772
949
  """Execute typed variable declaration: type<T> varName = value;
773
950
 
774
951
  Creates appropriate type instances for stack, vector, datastruct, etc.
952
+
953
+ The * prefix indicates a non-nullable variable (can never be None/null).
954
+ Example: vector<dynamic> *MyVector - can never contain None values.
775
955
  """
776
956
  decl = node.value
777
957
  type_name = decl.get('type')
778
958
  element_type = decl.get('element_type', 'dynamic')
779
959
  var_name = decl.get('name')
780
960
  value_node = decl.get('value')
961
+ non_null = decl.get('non_null', False)
781
962
 
782
963
  # Create the appropriate type instance
783
964
  if type_name == 'stack':
@@ -825,11 +1006,32 @@ class CSSLRuntime:
825
1006
  # For container types, the value might be initialization data
826
1007
  init_value = self._evaluate(value_node)
827
1008
  if isinstance(init_value, (list, tuple)):
1009
+ # For non-null containers, filter out None values
1010
+ if non_null:
1011
+ init_value = [v for v in init_value if v is not None]
828
1012
  instance.extend(init_value)
829
1013
  elif init_value is not None:
830
1014
  if hasattr(instance, 'append'):
831
1015
  instance.append(init_value)
832
1016
 
1017
+ # Non-null enforcement: container types get wrapped to filter None on operations
1018
+ if non_null:
1019
+ # Mark the instance as non-null for runtime checks
1020
+ if hasattr(instance, '_non_null'):
1021
+ instance._non_null = True
1022
+ # Track non-null variables for assignment enforcement
1023
+ if not hasattr(self, '_non_null_vars'):
1024
+ self._non_null_vars = set()
1025
+ self._non_null_vars.add(var_name)
1026
+
1027
+ # Ensure initial value is not None for non-null variables
1028
+ if instance is None:
1029
+ raise CSSLRuntimeError(
1030
+ f"Non-null variable '*{var_name}' cannot be initialized to None",
1031
+ node.line,
1032
+ hint="Use a default value or remove the * prefix"
1033
+ )
1034
+
833
1035
  # Check for global modifier
834
1036
  modifiers = decl.get('modifiers', [])
835
1037
  is_global = 'global' in modifiers
@@ -1006,6 +1208,9 @@ class CSSLRuntime:
1006
1208
  func_node: The function AST node
1007
1209
  args: List of positional arguments
1008
1210
  kwargs: Dict of named arguments (param_name -> value)
1211
+
1212
+ Supports:
1213
+ define func : extends otherFunc() { ... } - Inherit local vars from otherFunc
1009
1214
  """
1010
1215
  func_info = func_node.value
1011
1216
  params = func_info.get('params', [])
@@ -1018,6 +1223,34 @@ class CSSLRuntime:
1018
1223
  # Create new scope
1019
1224
  new_scope = Scope(parent=self.scope)
1020
1225
 
1226
+ # Handle function extends - inherit local vars from extended function
1227
+ extends_resolved = func_info.get('_extends_resolved')
1228
+ if extends_resolved:
1229
+ if callable(extends_resolved):
1230
+ # Python function - call it first to populate any state
1231
+ try:
1232
+ extends_resolved(*args, **kwargs)
1233
+ except:
1234
+ pass
1235
+ elif hasattr(extends_resolved, 'value'):
1236
+ # CSSL function - execute it in a temporary scope to get local vars
1237
+ old_scope = self.scope
1238
+ temp_scope = Scope(parent=self.scope)
1239
+ self.scope = temp_scope
1240
+ try:
1241
+ # Execute extended function body to populate local vars
1242
+ for child in extends_resolved.children:
1243
+ if not self._running:
1244
+ break
1245
+ self._execute_node(child)
1246
+ # Copy all local vars to new scope
1247
+ for name, value in temp_scope._vars.items():
1248
+ new_scope.set(name, value)
1249
+ except:
1250
+ pass
1251
+ finally:
1252
+ self.scope = old_scope
1253
+
1021
1254
  # Bind parameters - handle both positional and named arguments
1022
1255
  for i, param in enumerate(params):
1023
1256
  # Extract param name and type from dict format: {'name': 'a', 'type': 'int'}
@@ -1029,10 +1262,20 @@ class CSSLRuntime:
1029
1262
  param_type = ''
1030
1263
 
1031
1264
  # Check if this is an 'open' parameter - receives all args as a list
1032
- if param_type == 'open' or param_name == 'Params':
1265
+ # The parser sets param['open'] = True for 'open' keyword
1266
+ is_open_param = (isinstance(param, dict) and param.get('open', False)) or param_name == 'Params'
1267
+ if is_open_param:
1033
1268
  # 'open Params' receives all arguments as a list
1034
- new_scope.set(param_name, list(args))
1035
- new_scope.set('Params', list(args)) # Also set 'Params' for OpenFind
1269
+ # Check for non_null flag: open *Params filters out None values
1270
+ is_non_null = isinstance(param, dict) and param.get('non_null', False)
1271
+ args_list = list(args)
1272
+ if is_non_null:
1273
+ args_list = [a for a in args_list if a is not None]
1274
+ # Also filter kwargs
1275
+ kwargs = {k: v for k, v in kwargs.items() if v is not None}
1276
+ new_scope.set(param_name, args_list)
1277
+ new_scope.set('Params', args_list) # Also set 'Params' for OpenFind
1278
+ new_scope.set('_OpenKwargs', kwargs) # Store kwargs for OpenFind<type, "name">
1036
1279
  elif param_name in kwargs:
1037
1280
  # Named argument takes priority
1038
1281
  new_scope.set(param_name, kwargs[param_name])
@@ -1267,6 +1510,82 @@ class CSSLRuntime:
1267
1510
  """Execute continue statement"""
1268
1511
  raise CSSLContinue()
1269
1512
 
1513
+ def _exec_constructor(self, node: ASTNode) -> Any:
1514
+ """Execute constructor node - only called when encountered directly.
1515
+
1516
+ Normally constructors are executed through _call_constructor in _eval_new.
1517
+ This handles cases where a constructor node is executed in other contexts.
1518
+ """
1519
+ # Constructor nodes should be handled during class instantiation
1520
+ # If we reach here, it's in a context where the constructor is stored but not executed
1521
+ return None
1522
+
1523
+ def _exec_super_call(self, node: ASTNode) -> Any:
1524
+ """Execute super() call to invoke parent constructor or method.
1525
+
1526
+ Syntax:
1527
+ super() - Call parent constructor with no args
1528
+ super(arg1, arg2) - Call parent constructor with args
1529
+ super::method() - Call specific parent method
1530
+ super::method(args) - Call specific parent method with args
1531
+ """
1532
+ if self._current_instance is None:
1533
+ raise CSSLRuntimeError(
1534
+ "super() called outside of class context",
1535
+ node.line if hasattr(node, 'line') else 0,
1536
+ hint="super() can only be used inside class constructors and methods"
1537
+ )
1538
+
1539
+ instance = self._current_instance
1540
+
1541
+ # Try to get parent from instance first, then from class definition
1542
+ parent = getattr(instance, '_parent_class', None)
1543
+ if parent is None and hasattr(instance, '_class') and instance._class:
1544
+ parent = getattr(instance._class, 'parent', None)
1545
+
1546
+ if parent is None:
1547
+ raise CSSLRuntimeError(
1548
+ "super() called but class has no parent",
1549
+ node.line if hasattr(node, 'line') else 0,
1550
+ hint="super() requires the class to extend another class"
1551
+ )
1552
+
1553
+ method_name = node.value.get('method')
1554
+ args = [self._evaluate(arg) for arg in node.value.get('args', [])]
1555
+
1556
+ from .cssl_builtins import CSSLizedPythonObject
1557
+
1558
+ if method_name:
1559
+ # super::method() - call specific parent method
1560
+ if isinstance(parent, CSSLClass):
1561
+ method = parent.methods.get(method_name)
1562
+ if method:
1563
+ return self._call_method(instance, method, args, {})
1564
+ else:
1565
+ raise CSSLRuntimeError(
1566
+ f"Parent class has no method '{method_name}'",
1567
+ node.line if hasattr(node, 'line') else 0
1568
+ )
1569
+ elif isinstance(parent, CSSLizedPythonObject):
1570
+ py_obj = parent.get_python_obj()
1571
+ if hasattr(py_obj, method_name):
1572
+ method = getattr(py_obj, method_name)
1573
+ return method(*args)
1574
+ else:
1575
+ raise CSSLRuntimeError(
1576
+ f"Parent Python object has no method '{method_name}'",
1577
+ node.line if hasattr(node, 'line') else 0
1578
+ )
1579
+ elif hasattr(parent, method_name):
1580
+ method = getattr(parent, method_name)
1581
+ return method(*args)
1582
+ else:
1583
+ # super() - call parent constructor
1584
+ self._call_parent_constructor(instance, args)
1585
+ instance._parent_constructor_called = True
1586
+
1587
+ return None
1588
+
1270
1589
  def _exec_try(self, node: ASTNode) -> Any:
1271
1590
  """Execute try/catch block"""
1272
1591
  try:
@@ -2308,6 +2627,9 @@ class CSSLRuntime:
2308
2627
 
2309
2628
  if node.type == 'literal':
2310
2629
  value = node.value
2630
+ # Handle dict-format literals from parser: {'type': 'int', 'value': 0}
2631
+ if isinstance(value, dict) and 'value' in value:
2632
+ value = value['value']
2311
2633
  # String interpolation - replace {var} or <var> with scope values
2312
2634
  if isinstance(value, str):
2313
2635
  has_fstring = '{' in value and '}' in value
@@ -2783,19 +3105,20 @@ class CSSLRuntime:
2783
3105
  )
2784
3106
 
2785
3107
  def _eval_typed_call(self, node: ASTNode) -> Any:
2786
- """Evaluate typed function call like OpenFind<string>(0)"""
3108
+ """Evaluate typed function call like OpenFind<string>(0) or OpenFind<dynamic, "name">"""
2787
3109
  name = node.value.get('name')
2788
3110
  type_param = node.value.get('type_param', 'dynamic')
3111
+ param_name = node.value.get('param_name') # For OpenFind<type, "name">
2789
3112
  args = [self._evaluate(a) for a in node.value.get('args', [])]
2790
3113
 
2791
- # Handle OpenFind<type>(index)
3114
+ # Handle OpenFind<type>(index) or OpenFind<type, "name">
2792
3115
  if name == 'OpenFind':
2793
3116
  # OpenFind searches for a value of the specified type
2794
3117
  # from the open parameters in scope
2795
3118
  open_params = self.scope.get('Params') or []
2796
- index = args[0] if args else 0
3119
+ open_kwargs = self.scope.get('_OpenKwargs') or {}
2797
3120
 
2798
- # Search for value of matching type at or near the index
3121
+ # Type mapping for type checking
2799
3122
  type_map = {
2800
3123
  'string': str, 'str': str,
2801
3124
  'int': int, 'integer': int,
@@ -2803,10 +3126,23 @@ class CSSLRuntime:
2803
3126
  'bool': bool, 'boolean': bool,
2804
3127
  'list': list, 'array': list,
2805
3128
  'dict': dict, 'json': dict,
3129
+ 'dynamic': None, # Accept any type
2806
3130
  }
2807
-
2808
3131
  target_type = type_map.get(type_param.lower())
2809
3132
 
3133
+ # If param_name is specified, search by name in kwargs
3134
+ # OpenFind<dynamic, "tasks"> -> searches for MyFunc(tasks="value")
3135
+ if param_name:
3136
+ if param_name in open_kwargs:
3137
+ value = open_kwargs[param_name]
3138
+ # Type check if not dynamic
3139
+ if target_type is None or isinstance(value, target_type):
3140
+ return value
3141
+ return None
3142
+
3143
+ # Otherwise, search by index in positional args
3144
+ index = args[0] if args else 0
3145
+
2810
3146
  if isinstance(open_params, (list, tuple)):
2811
3147
  # Find first matching type starting from index
2812
3148
  for i in range(index, len(open_params)):
@@ -2827,14 +3163,16 @@ class CSSLRuntime:
2827
3163
  raise CSSLRuntimeError(
2828
3164
  f"Unknown typed function: {name}<{type_param}>",
2829
3165
  node.line,
2830
- context=f"Available typed functions: OpenFind<type>",
2831
- hint="Typed functions use format: FunctionName<Type>(args)"
3166
+ context=f"Available typed functions: OpenFind<type>, OpenFind<type, \"name\">",
3167
+ hint="Use OpenFind<type>(index) for positional or OpenFind<type, \"name\"> for named params"
2832
3168
  )
2833
3169
 
2834
3170
  def _eval_new(self, node: ASTNode) -> CSSLInstance:
2835
3171
  """Evaluate 'new ClassName(args)' expression.
2836
3172
 
2837
3173
  Creates a new instance of a CSSL class and calls its constructor.
3174
+ Supports multiple constructors (constr keyword), class parameters,
3175
+ and automatic parent constructor calling.
2838
3176
  """
2839
3177
  class_name = node.value.get('class')
2840
3178
  args = [self._evaluate(arg) for arg in node.value.get('args', [])]
@@ -2862,12 +3200,130 @@ class CSSLRuntime:
2862
3200
  # Create new instance
2863
3201
  instance = CSSLInstance(class_def)
2864
3202
 
2865
- # Call constructor if defined
3203
+ # Store parent class reference for super() calls
3204
+ instance._parent_class = class_def.parent
3205
+ instance._parent_constructor_called = False
3206
+
3207
+ # Get class params and extends args
3208
+ class_params = getattr(class_def, 'class_params', [])
3209
+ extends_args = getattr(class_def, 'extends_args', [])
3210
+ constructors = getattr(class_def, 'constructors', [])
3211
+
3212
+ # Bind class_params to instance scope (they receive values from constructor args)
3213
+ # These are the implicit constructor parameters defined in class declaration
3214
+ param_values = {}
3215
+ for i, param in enumerate(class_params):
3216
+ param_name = param.get('name') if isinstance(param, dict) else param
3217
+ if i < len(args):
3218
+ param_values[param_name] = args[i]
3219
+ else:
3220
+ param_values[param_name] = None
3221
+
3222
+ # Call parent constructor with extends_args if parent exists and args specified
3223
+ if class_def.parent and extends_args:
3224
+ evaluated_extends_args = [self._evaluate(arg) for arg in extends_args]
3225
+ self._call_parent_constructor(instance, evaluated_extends_args)
3226
+ instance._parent_constructor_called = True
3227
+
3228
+ # Execute all constructors defined with 'constr' keyword (in order)
3229
+ for constr in constructors:
3230
+ self._call_constructor(instance, constr, args, kwargs, param_values)
3231
+
3232
+ # Call primary constructor (old-style) if defined
2866
3233
  if class_def.constructor:
2867
3234
  self._call_method(instance, class_def.constructor, args, kwargs)
2868
3235
 
2869
3236
  return instance
2870
3237
 
3238
+ def _call_parent_constructor(self, instance: CSSLInstance, args: list, kwargs: dict = None):
3239
+ """Call the parent class constructor on an instance.
3240
+
3241
+ Used for automatic parent constructor calling and super() calls.
3242
+ """
3243
+ kwargs = kwargs or {}
3244
+ parent = instance._parent_class
3245
+
3246
+ if parent is None:
3247
+ return
3248
+
3249
+ from .cssl_builtins import CSSLizedPythonObject
3250
+
3251
+ if isinstance(parent, CSSLClass):
3252
+ # CSSL parent class
3253
+ if parent.constructor:
3254
+ self._call_method(instance, parent.constructor, args, kwargs)
3255
+ # Also call parent's constr constructors
3256
+ for constr in getattr(parent, 'constructors', []):
3257
+ self._call_constructor(instance, constr, args, kwargs, {})
3258
+ elif isinstance(parent, CSSLizedPythonObject):
3259
+ # Python parent - call __init__ if it's a class
3260
+ py_obj = parent.get_python_obj()
3261
+ if isinstance(py_obj, type):
3262
+ # It's a class - we need to initialize it
3263
+ try:
3264
+ py_obj.__init__(instance, *args, **kwargs)
3265
+ except TypeError:
3266
+ pass # Initialization might not be needed
3267
+ elif isinstance(parent, type):
3268
+ # Raw Python class
3269
+ try:
3270
+ parent.__init__(instance, *args, **kwargs)
3271
+ except TypeError:
3272
+ pass
3273
+
3274
+ def _call_constructor(self, instance: CSSLInstance, constr_node: ASTNode,
3275
+ args: list, kwargs: dict, param_values: dict):
3276
+ """Call a constructor defined with 'constr' keyword.
3277
+
3278
+ Handles constructor extends/overwrites and sets up the instance scope.
3279
+ """
3280
+ constr_info = constr_node.value
3281
+ constr_params = constr_info.get('params', [])
3282
+ extends_class = constr_info.get('extends_class')
3283
+ extends_method = constr_info.get('extends_method')
3284
+
3285
+ # Save previous instance context
3286
+ prev_instance = self._current_instance
3287
+ self._current_instance = instance
3288
+
3289
+ # Create new scope for constructor
3290
+ new_scope = Scope(parent=self.scope)
3291
+
3292
+ # Bind param_values (from class params) to constructor scope
3293
+ for name, value in param_values.items():
3294
+ new_scope.set(name, value)
3295
+
3296
+ # Bind constructor parameters
3297
+ for i, param in enumerate(constr_params):
3298
+ param_name = param.get('name') if isinstance(param, dict) else param
3299
+ if i < len(args):
3300
+ new_scope.set(param_name, args[i])
3301
+ elif param_name in kwargs:
3302
+ new_scope.set(param_name, kwargs[param_name])
3303
+ else:
3304
+ new_scope.set(param_name, None)
3305
+
3306
+ # If constructor extends another constructor, inherit its local vars
3307
+ if extends_class and extends_method:
3308
+ parent_class = self.scope.get(extends_class) or self.global_scope.get(extends_class)
3309
+ if parent_class and isinstance(parent_class, CSSLClass):
3310
+ for constr in getattr(parent_class, 'constructors', []):
3311
+ if constr.value.get('name') == extends_method:
3312
+ # Execute parent constructor first to get local vars
3313
+ self._call_constructor(instance, constr, args, kwargs, param_values)
3314
+ break
3315
+
3316
+ # Execute constructor body
3317
+ prev_scope = self.scope
3318
+ self.scope = new_scope
3319
+
3320
+ try:
3321
+ for stmt in constr_node.children:
3322
+ self._execute_node(stmt)
3323
+ finally:
3324
+ self.scope = prev_scope
3325
+ self._current_instance = prev_instance
3326
+
2871
3327
  def _eval_this_access(self, node: ASTNode) -> Any:
2872
3328
  """Evaluate 'this->member' access.
2873
3329
 
@@ -2905,6 +3361,10 @@ class CSSLRuntime:
2905
3361
  if instance.has_method(member):
2906
3362
  # Return a callable that will invoke the method with instance context
2907
3363
  method_node = instance.get_method(member)
3364
+ # Check if this is an inherited Python method
3365
+ if isinstance(method_node, tuple) and method_node[0] == 'python_method':
3366
+ python_method = method_node[1]
3367
+ return lambda *args, **kwargs: python_method(*args, **kwargs)
2908
3368
  return lambda *args, **kwargs: self._call_method(instance, method_node, list(args), kwargs)
2909
3369
 
2910
3370
  raise CSSLRuntimeError(
@@ -2986,6 +3446,10 @@ class CSSLRuntime:
2986
3446
  # Check for method
2987
3447
  if obj.has_method(member):
2988
3448
  method_node = obj.get_method(member)
3449
+ # Check if this is an inherited Python method
3450
+ if isinstance(method_node, tuple) and method_node[0] == 'python_method':
3451
+ python_method = method_node[1]
3452
+ return lambda *args, **kwargs: python_method(*args, **kwargs)
2989
3453
  return lambda *args, **kwargs: self._call_method(obj, method_node, list(args), kwargs)
2990
3454
  raise CSSLRuntimeError(f"'{obj._class.name}' has no member or method '{member}'")
2991
3455