nim callback on property change
- User
nim callback on property change
Assistant
Implementing "callback on property change" in Nim is a great use case for macros. You want to transform a simple object definition into one that automatically includes private backing fields, public getters/setters, and a mechanism to notify listeners when a property's value changes.
This pattern is often called "observable properties" or "INotifyPropertyChanged" in other languages.
Here's how you can achieve this with a Nim macro:
import macros, sequtils # For `add` on seq # --- 1. Define the Callback Type --- type PropertyChangeCallback* = proc(propertyName: string) # --- 2. Create the `notify` Macro --- macro notify*(typename: untyped, body: untyped): untyped = ## Transforms an object definition into one with observable properties. ## Adds a `onPropertyChangeCallbacks` field and generates ## getters and setters for all fields, which trigger callbacks. ## ## Example: ## ## notify Person: ## name: string ## age: int ## ## Becomes (roughly): ## ## type Person = ref object ## _name: string ## _age: int ## onPropertyChangeCallbacks: seq[PropertyChangeCallback] ## ## proc name(self: Person): string = self._name ## proc `name=`(self: Person, val: string) = ## if self._name != val: ## self._name = val ## for cb in self.onPropertyChangeCallbacks: ## cb("name") ## # ... similar for age ## ## proc newPerson(): Person = ... ## proc addPropertyChangeListener(self: Person, cb: PropertyChangeCallback) = ... let objType = typename # e.g., `Person` var newBody = newStmtList() # Stores the new fields for the object var generatedProcs = newStmtList() # Stores the generated getter/setter procs # Add the callbacks field to the object's definition newBody.add quote do: onPropertyChangeCallbacks*: seq[PropertyChangeCallback] # Iterate over the provided object body (the fields the user defined) for field in body.children: # Check if it's a variable declaration (e.g., `fieldName: FieldType`) if field.kind == nkVarDecl: let fieldName = field[0] # e.g., `name` let fieldType = field[1] # e.g., `string` let backingField = ident("_" & $fieldName) # e.g., `_name` let setterName = ident($fieldName & "=") # e.g., `name=` let fieldNameStr = newLit($fieldName) # e.g., "name" (for callback) # 1. Add the private backing field to the object definition newBody.add quote do: `backingField`: `fieldType` # 2. Generate the public getter proc generatedProcs.add quote do: proc `fieldName`*(self: `objType`): `fieldType` = self.`backingField` # 3. Generate the public setter proc generatedProcs.add quote do: proc `setterName`*(self: `objType`, value: `fieldType`) = # Only trigger callback if the value actually changed # This prevents unnecessary notifications for idempotent assignments. if self.`backingField` != value: self.`backingField` = value # Notify all registered listeners for cb in self.onPropertyChangeCallbacks: cb(`fieldNameStr`) else: # If it's not a varDecl (e.g., a pragma, a comment, or another object member), # just pass it through to the new object body. newBody.add field # Construct the final output AST result = newStmtList() # Define the new type as a `ref object`. # `ref object` is typical for mutable state that's passed around. result.add quote do: type `objType`* = ref object `newBody` # Add a convenient constructor for the new type result.add quote do: proc new`objType`*(): `objType` = new(result) # Allocate the ref object on the heap result.onPropertyChangeCallbacks = @[] # Initialize the seq of callbacks # Add a helper proc for adding listeners result.add quote do: proc addPropertyChangeListener*(self: `objType`, cb: PropertyChangeCallback) = self.onPropertyChangeCallbacks.add(cb) # Add all the generated getter/setter procs result.add generatedProcs # --- 3. Example Usage --- notify Person: name: string age: int city: string # Let's verify the generated code (optional, for understanding) # dumpTree: # notify Person: # name: string # age: int proc myPersonCallback(propertyName: string) = echo "Property '", propertyName, "' changed!" proc main() = var p = newPerson() # Use the generated constructor p.addPropertyChangeListener(myPersonCallback) # Change properties - this should trigger callbacks p.name = "Alice" p.age = 30 p.city = "New York" echo "Person: ", p.name, ", ", p.age, ", ", p.city # Change to the same value - no callback expected echo "--- Setting name to Alice again (no callback expected) ---" p.name = "Alice" # Change again - callback expected echo "--- Setting age to 31 ---" p.age = 31 # Add another specific callback p.addPropertyChangeListener(proc(propertyName: string) = echo "Another listener heard '", propertyName, "' changed!") echo "--- Setting city to London ---" p.city = "London" # Access via getter echo "Current city (via getter): ", p.city main()Explanation:
PropertyChangeCallbackType: This defines the signature for your callback functions: they take astring(the name of the property that changed) and return nothing.notifyMacro:- It takes the
typename(e.g.,Person) and thebody(the indented block containing field declarations). objType: This variable stores theident(identifier) of your type, likePerson.newBody: ThisnewStmtList()will accumulate the fields that will form the finalref objectdefinition.generatedProcs: ThisnewStmtList()will hold all theprocdefinitions (getters and setters) that the macro generates.- Adding
onPropertyChangeCallbacks: The macro first adds aonPropertyChangeCallbacks: seq[PropertyChangeCallback]field to your object. This is where all the registered callback functions will be stored. - Iterating Fields: It loops through each
fielddefined in thebodyprovided by the user. nkVarDecl: It checks if thefieldis a variable declaration (fieldName: FieldType). This ensures it only processes actual property definitions.backingField,setterName,fieldNameStr: These areNimNodevariables created using quasiquotation (quote do:) orident()/newLit().backingField:_name(private storage)setterName:name=(the setter proc name)fieldNameStr:"name"(the string literal for the callback)
- Generated Code Structure:
- The private
_fieldNameis added to thenewBody. - A
proc fieldName*(self: objType): fieldType = self._fieldName(getter) is added togeneratedProcs. - A
procfieldName=*(self: objType, value: fieldType) = ...(setter) is added togeneratedProcs.- Crucially, the setter checks
if self.backingField != value:. This prevents callbacks from firing if the property is set to its current value, which is good practice. - If the value changes, it updates the
backingFieldand then iterates throughself.onPropertyChangeCallbacksto call each registered callback.
- Crucially, the setter checks
- The private
- Final
result: The macro constructs the finalNimNode(the AST representing the generated code).- It defines the
type objType* = ref object: ...using thenewBodyaccumulated earlier. Usingref objectis common for this pattern as it allows mutable heap-allocated instances. - It adds a
newObjType()constructor that initializes theref objectand setsonPropertyChangeCallbacksto an empty sequence. - It adds an
addPropertyChangeListener()helper proc. - Finally, it appends all the
generatedProcs(getters and setters) after the type definition.
- It defines the
- It takes the
How to Use:
- Define your object using the
notifymacro, just like a regularobjectdefinition. - Create a new instance using the generated
newYourTypeName()constructor (e.g.,newPerson()). - Register callbacks using the generated
addPropertyChangeListener()method. - Set properties using the standard assignment operator (e.g.,
p.name = "Alice"). The macro-generated setter will automatically handle change detection and callback invocation. - Get properties using the standard field access (e.g.,
p.name). The macro-generated getter will return the value from the backing field.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.