My macro: 
    
    
    import macros
    
    macro createObj(typ: typedesc, data: untyped): untyped =
      # This macro only accepts tuples in parenthesis, but this can be changed
      assert data.kind == nnkPar
      # Object construction syntax
      result = newTree(nnkObjConstr)
      # Add type name
      result.add(typ.getTypeInst()[1])
      # Get implementation of typedesc
      let typImpl = typ.getTypeInst()[1].symbol.getImpl()[2]
      # We support both ref and usual objects
      let fields = if typImpl.kind == nnkRefTy: typImpl[0][2] else: typImpl[2]
      # Tuple should have exactly the same number of values as object
      assert fields.len == data.len
      # add fieldName: value to result for all fields/values
      for i in 0..<fields.len:
        result.add newTree(nnkExprColonExpr, fields[i][0], data[i])
      # Result would be something like MyObj(x: 5, y: 7.0)
    
    type MyObj = ref object
      x: int
      y: float
    
    let myObj = createObj(MyObj, (5, 7.0))
    echo myObj.y
    

Reply via email to