Distinct type

A distinct type is new type derived from a base type that is incompatible with its base type. In particular, it is an essential property of a distinct type that it does not imply a subtype relation between it and its base type. Explicit type conversions from a distinct type to its base type and vice versa are allowed. See also distinctBase to get the reverse operation.

A distinct type is an ordinal type if its base type is an ordinal type.

Modelling currencies

A distinct type can be used to model different physical units with a numerical base type, for example. The following example models currencies.

Different currencies should not be mixed in monetary calculations. Distinct types are a perfect tool to model different currencies:

  1. type
  2. Dollar = distinct int
  3. Euro = distinct int
  4. var
  5. d: Dollar
  6. e: Euro
  7. echo d + 12
  8. # Error: cannot add a number with no unit and a ``Dollar``

Unfortunately, d + 12.Dollar is not allowed either, because + is defined for int (among others), not for Dollar. So a + for dollars needs to be defined:

  1. proc `+` (x, y: Dollar): Dollar =
  2. result = Dollar(int(x) + int(y))

It does not make sense to multiply a dollar with a dollar, but with a number without unit; and the same holds for division:

  1. proc `*` (x: Dollar, y: int): Dollar =
  2. result = Dollar(int(x) * y)
  3. proc `*` (x: int, y: Dollar): Dollar =
  4. result = Dollar(x * int(y))
  5. proc `div` ...

This quickly gets tedious. The implementations are trivial and the compiler should not generate all this code only to optimize it away later - after all + for dollars should produce the same binary code as + for ints. The pragma borrow has been designed to solve this problem; in principle it generates the above trivial implementations:

  1. proc `*` (x: Dollar, y: int): Dollar {.borrow.}
  2. proc `*` (x: int, y: Dollar): Dollar {.borrow.}
  3. proc `div` (x: Dollar, y: int): Dollar {.borrow.}

The borrow pragma makes the compiler use the same implementation as the proc that deals with the distinct type’s base type, so no code is generated.

But it seems all this boilerplate code needs to be repeated for the Euro currency. This can be solved with templates.

  1. template additive(typ: typedesc) =
  2. proc `+` *(x, y: typ): typ {.borrow.}
  3. proc `-` *(x, y: typ): typ {.borrow.}
  4. # unary operators:
  5. proc `+` *(x: typ): typ {.borrow.}
  6. proc `-` *(x: typ): typ {.borrow.}
  7. template multiplicative(typ, base: typedesc) =
  8. proc `*` *(x: typ, y: base): typ {.borrow.}
  9. proc `*` *(x: base, y: typ): typ {.borrow.}
  10. proc `div` *(x: typ, y: base): typ {.borrow.}
  11. proc `mod` *(x: typ, y: base): typ {.borrow.}
  12. template comparable(typ: typedesc) =
  13. proc `<` * (x, y: typ): bool {.borrow.}
  14. proc `<=` * (x, y: typ): bool {.borrow.}
  15. proc `==` * (x, y: typ): bool {.borrow.}
  16. template defineCurrency(typ, base: untyped) =
  17. type
  18. typ* = distinct base
  19. additive(typ)
  20. multiplicative(typ, base)
  21. comparable(typ)
  22. defineCurrency(Dollar, int)
  23. defineCurrency(Euro, int)

The borrow pragma can also be used to annotate the distinct type to allow certain builtin operations to be lifted:

  1. type
  2. Foo = object
  3. a, b: int
  4. s: string
  5. Bar {.borrow: `.`.} = distinct Foo
  6. var bb: ref Bar
  7. new bb
  8. # field access now valid
  9. bb.a = 90
  10. bb.s = "abc"

Currently only the dot accessor can be borrowed in this way.

Avoiding SQL injection attacks

An SQL statement that is passed from Nim to an SQL database might be modelled as a string. However, using string templates and filling in the values is vulnerable to the famous SQL injection attack:

  1. import strutils
  2. proc query(db: DbHandle, statement: string) = ...
  3. var
  4. username: string
  5. db.query("SELECT FROM users WHERE name = '$1'" % username)
  6. # Horrible security hole, but the compiler does not mind!

This can be avoided by distinguishing strings that contain SQL from strings that don’t. Distinct types provide a means to introduce a new string type SQL that is incompatible with string:

  1. type
  2. SQL = distinct string
  3. proc query(db: DbHandle, statement: SQL) = ...
  4. var
  5. username: string
  6. db.query("SELECT FROM users WHERE name = '$1'" % username)
  7. # Static error: `query` expects an SQL string!

It is an essential property of abstract types that they do not imply a subtype relation between the abstract type and its base type. Explicit type conversions from string to SQL are allowed:

  1. import strutils, sequtils
  2. proc properQuote(s: string): SQL =
  3. # quotes a string properly for an SQL statement
  4. return SQL(s)
  5. proc `%` (frmt: SQL, values: openarray[string]): SQL =
  6. # quote each argument:
  7. let v = values.mapIt(SQL, properQuote(it))
  8. # we need a temporary type for the type conversion :-(
  9. type StrSeq = seq[string]
  10. # call strutils.`%`:
  11. result = SQL(string(frmt) % StrSeq(v))
  12. db.query("SELECT FROM users WHERE name = '$1'".SQL % [username])

Now we have compile-time checking against SQL injection attacks. Since “”.SQL is transformed to SQL(“”) no new syntax is needed for nice looking SQL string literals. The hypothetical SQL type actually exists in the library as the SqlQuery type of modules like db_sqlite.