Module typeutils

Search:
Group by:

Provides miscellaneous utilities working with types: types declaration, constructor generation, etc.

The data keyword

Keyword data allows to create new value and reference object types. Also, it generates constructors that is more safe to use then standard one, because they allows optional fields only when explicit default value is set.

Let's define some object:

data TypeA:
  a = 1
  var b = "a"

The object type TypeA has immutable field a of type int with default value 1 and mutable field b of type string with default value "a", and the constructor called initTypeA. Let's create na exemplar of it:

var x = initTypeA(b = "b")
assert x.a == 1
assert x.b == "b"
# You can assign values to the field b:
x.b = "a"
# But the next assignment produces compile time error, because field a is immutable.
# Let's check this:
assert compiles((block:
  x.a = 2
))

Now let's create the generic type TypeB, derived from TypeA:

data TypeB[C,D] of TypeA:
  c: C
  var d: D
var y = initTypeB(100, "aaa", 'a', 1.0)

Derived types knows aboud default vaules, so you can create object like this:

var y = initTypeB(c = 'a', d = 1.0)

You can also create reference object types with this syntax

data TypeC ref object of TypeA:
  c: char

Reference objects constructors names created by adding prefix new to type name:

var z = newTypeC(c = 'a')

More documentation is coming, for now please see the tests in tests/boost/test_typeutils.nim

Macros

macro genConstructor*(`type`: typed; args: varargs[untyped]): untyped

Generates constructor for the type. The second optional parameter is the name of the constructor. By default it's newType for the ref objects and initType for the objects. The third optional parameter is the word exported and means that the constructor must be exported.

Example:

type Obj* = ref object
  x: int
  y: string
genConstructor Obj, exported

let x = newObj(1, "a")
  Source Edit
macro data*(args: varargs[untyped]): untyped
  Source Edit