Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

nim callback on property change

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o3-mini’s answer.
  1. User

    nim callback on property change

  2. Gemini 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:

    1. PropertyChangeCallback Type: This defines the signature for your callback functions: they take a string (the name of the property that changed) and return nothing.
    2. notify Macro:
      • It takes the typename (e.g., Person) and the body (the indented block containing field declarations).
      • objType: This variable stores the ident (identifier) of your type, like Person.
      • newBody: This newStmtList() will accumulate the fields that will form the final ref object definition.
      • generatedProcs: This newStmtList() will hold all the proc definitions (getters and setters) that the macro generates.
      • Adding onPropertyChangeCallbacks: The macro first adds a onPropertyChangeCallbacks: seq[PropertyChangeCallback] field to your object. This is where all the registered callback functions will be stored.
      • Iterating Fields: It loops through each field defined in the body provided by the user.
      • nkVarDecl: It checks if the field is a variable declaration (fieldName: FieldType). This ensures it only processes actual property definitions.
      • backingField, setterName, fieldNameStr: These are NimNode variables created using quasiquotation (quote do:) or ident()/newLit().
        • backingField: _name (private storage)
        • setterName: name= (the setter proc name)
        • fieldNameStr: "name" (the string literal for the callback)
      • Generated Code Structure:
        • The private _fieldName is added to the newBody.
        • A proc fieldName*(self: objType): fieldType = self._fieldName (getter) is added to generatedProcs.
        • A proc fieldName=*(self: objType, value: fieldType) = ... (setter) is added to generatedProcs.
          • 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 backingField and then iterates through self.onPropertyChangeCallbacks to call each registered callback.
      • Final result: The macro constructs the final NimNode (the AST representing the generated code).
        • It defines the type objType* = ref object: ... using the newBody accumulated earlier. Using ref object is common for this pattern as it allows mutable heap-allocated instances.
        • It adds a newObjType() constructor that initializes the ref object and sets onPropertyChangeCallbacks to an empty sequence.
        • It adds an addPropertyChangeListener() helper proc.
        • Finally, it appends all the generatedProcs (getters and setters) after the type definition.

    How to Use:

    1. Define your object using the notify macro, just like a regular object definition.
    2. Create a new instance using the generated newYourTypeName() constructor (e.g., newPerson()).
    3. Register callbacks using the generated addPropertyChangeListener() method.
    4. Set properties using the standard assignment operator (e.g., p.name = "Alice"). The macro-generated setter will automatically handle change detection and callback invocation.
    5. Get properties using the standard field access (e.g., p.name). The macro-generated getter will return the value from the backing field.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.

Identical first prompt