src/skinsuit/sum

Search:
Group by:
Source   Edit  

macro for sum type sugar

Generates kind enum and objects for each case branch allowing multiple fields with the same name across branches. These objects can also be made ref objects with kind: ref _.

Also generates constructors for branches with only one field _: sometype.

Example:

import src/skinsuit/sum
type Foo {.sum.} = object
  case kind: _
  of A:
    x, y: int

let a = Foo(kind: A)
assert a.kind is FooKind
var b = Foo(kind: A)
b.x = 1
assert b.x == 1
let c = Foo(kind: A, a: FooA(x: 1, y: 2))
b.y = 2
assert b.a == c.a

type Value {.sum.} = object
  case kind: _
  of None: discard
  of Integer, Boolean:
    _: int
  of Unsigned:
    _: uint
  of Float:
    _: float

assert $Value(kind: None) == "(kind: None, none: ())"
assert $Value(kind: Integer, integer: 1) == $Integer(1)
assert $Value(kind: Boolean, integer: 1) == $Boolean(1)
assert $Value(kind: Unsigned, unsigned: 1) == $Unsigned(1)
assert $Value(kind: Float, float: 1) == $Float(1)

Macros

macro sum(body)
Source   Edit