Source Edit

Authors:Andreas Rumpf
Version:2.0.8

About this document

This document describes features of Nim that are to be considered experimental. Some of these are not covered by the .experimental pragma or --experimental switch because they are already behind a special syntax and one may want to use Nim libraries using these features without using them oneself.

Note: Unless otherwise indicated, these features are not to be removed, but refined and overhauled.

Void type

The void type denotes the absence of any type. Parameters of type void are treated as non-existent, void as a return type means that the procedure does not return a value:

  1. proc nothing(x, y: void): void =
  2. echo "ha"
  3. nothing() # writes "ha" to stdout

The void type is particularly useful for generic code:

  1. proc callProc[T](p: proc (x: T), x: T) =
  2. when T is void:
  3. p()
  4. else:
  5. p(x)
  6. proc intProc(x: int) = discard
  7. proc emptyProc() = discard
  8. callProc[int](intProc, 12)
  9. callProc[void](emptyProc)

However, a void type cannot be inferred in generic code:

  1. callProc(emptyProc)
  2. # Error: type mismatch: got (proc ())
  3. # but expected one of:
  4. # callProc(p: proc (T), x: T)

The void type is only valid for parameters and return types; other symbols cannot have the type void.

Generic define pragma

Aside the typed define pragmas for constants, there is a generic {.define.} pragma that interprets the value of the define based on the type of the constant value.

  1. const foo {.define: "package.foo".} = 123
  2. const bar {.define: "package.bar".} = false
  1. nim c -d:package.foo=456 -d:package.bar foobar.nim

The following types are supported:

  • string and cstring
  • Signed and unsigned integer types
  • bool
  • Enums

Top-down type inference

In expressions such as:

  1. let a: T = ex

Normally, the compiler type checks the expression ex by itself, then attempts to statically convert the type-checked expression to the given type T as much as it can, while making sure it matches the type. The extent of this process is limited however due to the expression usually having an assumed type that might clash with the given type.

With top-down type inference, the expression is type checked with the extra knowledge that it is supposed to be of type T. For example, the following code is does not compile with the former method, but compiles with top-down type inference:

  1. let foo: (float, uint8, cstring) = (1, 2, "abc")

The tuple expression has an expected type of (float, uint8, cstring). Since it is a tuple literal, we can use this information to assume the types of its elements. The expected types for the expressions 1, 2 and “abc” are respectively float, uint8, and cstring; and these expressions can be statically converted to these types.

Without this information, the type of the tuple expression would have been assumed to be (int, int, string). Thus the type of the tuple expression would not match the type of the variable, and an error would be given.

The extent of this varies, but there are some notable special cases.

Sequence literals

Top-down type inference applies to sequence literals.

  1. let x: seq[seq[float]] = @[@[1, 2, 3], @[4, 5, 6]]

This behavior is tied to the @ overloads in the system module, so overloading @ can disable this behavior. This can be circumvented by specifying the `` system.@ `` overload.

  1. proc `@`(x: string): string = "@" & x
  2. # does not compile:
  3. let x: seq[float] = @[1, 2, 3]
  4. # compiles:
  5. let x: seq[float] = system.`@`([1, 2, 3])

Package level objects

Every Nim module resides in a (nimble) package. An object type can be attached to the package it resides in. If that is done, the type can be referenced from other modules as an incomplete object type. This feature allows to break up recursive type dependencies across module boundaries. Incomplete object types are always passed byref and can only be used in pointer like contexts (var/ref/ptr IncompleteObject) in general, since the compiler does not yet know the size of the object. To complete an incomplete object, the package pragma has to be used. package implies byref.

As long as a type T is incomplete, no runtime type information for T is available.

Example:

  1. # module A (in an arbitrary package)
  2. type
  3. Pack.SomeObject = object # declare as incomplete object of package 'Pack'
  4. Triple = object
  5. a, b, c: ref SomeObject # pointers to incomplete objects are allowed
  6. # Incomplete objects can be used as parameters:
  7. proc myproc(x: SomeObject) = discard
  1. # module B (in package "Pack")
  2. type
  3. SomeObject* {.package.} = object # Use 'package' to complete the object
  4. s, t: string
  5. x, y: int

This feature will likely be superseded in the future by support for recursive module dependencies.

Importing private symbols

In some situations, it may be useful to import all symbols (public or private) from a module. The syntax import foo {.all.} can be used to import all symbols from the module foo. Note that importing private symbols is generally not recommended.

See also the experimental importutils module.

Code reordering

The code reordering feature can implicitly rearrange procedure, template, and macro definitions along with variable declarations and initializations at the top level scope so that, to a large extent, a programmer should not have to worry about ordering definitions correctly or be forced to use forward declarations to preface definitions inside a module.

Example:

  1. {.experimental: "codeReordering".}
  2. proc foo(x: int) =
  3. bar(x)
  4. proc bar(x: int) =
  5. echo(x)
  6. foo(10)

Variables can also be reordered as well. Variables that are initialized (i.e. variables that have their declaration and assignment combined in a single statement) can have their entire initialization statement reordered. Be wary of what code is executed at the top level:

  1. {.experimental: "codeReordering".}
  2. proc a() =
  3. echo(foo)
  4. var foo = 5
  5. a() # outputs: "5"

It is important to note that reordering only works for symbols at top level scope. Therefore, the following will fail to compile:

  1. {.experimental: "codeReordering".}
  2. proc a() =
  3. b()
  4. proc b() =
  5. echo("Hello!")
  6. a()

This feature will likely be replaced with a better solution to remove the need for forward declarations.

Special Operators

dot operators

Note: Dot operators are still experimental and so need to be enabled via {.experimental: “dotOperators”.}.

Nim offers a special family of dot operators that can be used to intercept and rewrite proc call and field access attempts, referring to previously undeclared symbol names. They can be used to provide a fluent interface to objects lying outside the static confines of the type system such as values from dynamic scripting languages or dynamic file formats such as JSON or XML.

When Nim encounters an expression that cannot be resolved by the standard overload resolution rules, the current scope will be searched for a dot operator that can be matched against a re-written form of the expression, where the unknown field or proc name is passed to an untyped parameter:

  1. a.b # becomes `.`(a, b)
  2. a.b(c, d) # becomes `.`(a, b, c, d)

The matched dot operators can be symbols of any callable kind (procs, templates and macros), depending on the desired effect:

  1. template `.`(js: PJsonNode, field: untyped): JSON = js[astToStr(field)]
  2. var js = parseJson("{ x: 1, y: 2}")
  3. echo js.x # outputs 1
  4. echo js.y # outputs 2

The following dot operators are available:

operator .

This operator will be matched against both field accesses and method calls.

operator .()

This operator will be matched exclusively against method calls. It has higher precedence than the . operator and this allows one to handle expressions like x.y and x.y() differently if one is interfacing with a scripting language for example.

operator .=

This operator will be matched against assignments to missing fields.

  1. a.b = c # becomes `.=`(a, b, c)

Call operator

The call operator, (), matches all kinds of unresolved calls and takes precedence over dot operators, however it does not match missing overloads for existing routines. The experimental callOperator switch must be enabled to use this operator.

  1. {.experimental: "callOperator".}
  2. template `()`(a: int, b: float): untyped = $(a, b)
  3. block:
  4. let a = 1.0
  5. let b = 2
  6. doAssert b(a) == `()`(b, a)
  7. doAssert a.b == `()`(b, a)
  8. block:
  9. let a = 1.0
  10. proc b(): int = 2
  11. doAssert not compiles(b(a))
  12. doAssert not compiles(a.b) # `()` not called
  13. block:
  14. let a = 1.0
  15. proc b(x: float): int = int(x + 1)
  16. let c = 3.0
  17. doAssert not compiles(a.b(c)) # gives a type mismatch error same as b(a, c)
  18. doAssert (a.b)(c) == `()`(a.b, c)

Extended macro pragmas

Macro pragmas as described in the manual can also be applied to type, variable and constant declarations.

For types:

  1. type
  2. MyObject {.schema: "schema.protobuf".} = object

This is translated to a call to the schema macro with a nnkTypeDef AST node capturing the left-hand side, remaining pragmas and the right-hand side of the definition. The macro can return either a type section or another nnkTypeDef node, both of which will replace the original row in the type section.

In the future, this nnkTypeDef argument may be replaced with a unary type section node containing the type definition, or some other node that may be more convenient to work with. The ability to return nodes other than type definitions may also be supported, however currently this is not convenient when dealing with mutual type recursion. For now, macros can return an unused type definition where the right-hand node is of kind nnkStmtListType. Declarations in this node will be attached to the same scope as the parent scope of the type section.


For variables and constants, it is largely the same, except a unary node with the same kind as the section containing a single definition is passed to macros, and macros can return any expression.

  1. var
  2. a = ...
  3. b {.importc, foo, nodecl.} = ...
  4. c = ...

Assuming foo is a macro or a template, this is roughly equivalent to:

  1. var a = ...
  2. foo:
  3. var b {.importc, nodecl.} = ...
  4. var c = ...

Symbols as template/macro calls (alias syntax)

Templates and macros that have no generic parameters and no required arguments can be called as lone symbols, i.e. without parentheses. This is useful for repeated uses of complex expressions that cannot conveniently be represented as runtime values.

  1. type Foo = object
  2. bar: int
  3. var foo = Foo(bar: 10)
  4. template bar: int = foo.bar
  5. assert bar == 10
  6. bar = 15
  7. assert bar == 15

Not nil annotation

Note: This is an experimental feature. It can be enabled with {.experimental: “notnil”.}.

All types for which nil is a valid value can be annotated with the not nil annotation to exclude nil as a valid value:

  1. {.experimental: "notnil".}
  2. type
  3. PObject = ref TObj not nil
  4. TProc = (proc (x, y: int)) not nil
  5. proc p(x: PObject) =
  6. echo "not nil"
  7. # compiler catches this:
  8. p(nil)
  9. # and also this:
  10. var x: PObject
  11. p(x)

The compiler ensures that every code path initializes variables which contain non-nilable pointers. The details of this analysis are still to be specified here.

Strict not nil checking

Note: This feature is experimental, you need to enable it with

  1. {.experimental: "strictNotNil".}

or

  1. nim c --experimental:strictNotNil <program>

In the second case it would check builtin and imported modules as well.

It checks the nilability of ref-like types and makes dereferencing safer based on flow typing and not nil annotations.

Its implementation is different than the notnil one: defined under strictNotNil. Keep in mind the difference in option names, be careful with distinguishing them.

We check several kinds of types for nilability:

  • ref types
  • pointer types
  • proc types
  • cstrings

nil

The default kind of nilability types is the nilable kind: they can have the value nil. If you have a non-nilable type T, you can use T nil to get a nilable type for it.

not nil

You can annotate a type where nil isn’t a valid value with not nil.

  1. type
  2. NilableObject = ref object
  3. a: int
  4. Object = NilableObject not nil
  5. Proc = (proc (x, y: int))
  6. proc p(x: Object) =
  7. echo x.a # ensured to dereference without an error
  8. # compiler catches this:
  9. p(nil)
  10. # and also this:
  11. var x: NilableObject
  12. if x.isNil:
  13. p(x)
  14. else:
  15. p(x) # ok

If a type can include nil as a valid value, dereferencing values of the type is checked by the compiler: if a value which might be nil is dereferenced, this produces a warning by default, you can turn this into an error using the compiler options --warningAsError:strictNotNil.

If a type is nilable, you should dereference its values only after a isNil or equivalent check.

local turn on/off

You can still turn off nil checking on function/module level by using a {.strictNotNil: off.} pragma.

nilability state

Currently, a nilable value can be Safe, MaybeNil or Nil : we use internally Parent and Unreachable but this is an implementation detail(a parent layer has the actual nilability).

  • Safe means it shouldn’t be nil at that point: e.g. after assignment to a non-nil value or not a.isNil check
  • MaybeNil means it might be nil, but it might not be nil: e.g. an argument, a call argument or a value after an if and else.
  • Nil means it should be nil at that point; e.g. after an assignment to nil or a .isNil check.
  • Unreachable means it shouldn’t be possible to access this in this branch: so we do generate a warning as well.

We show an error for each dereference ([], .field, [index] () etc.) which is of a tracked expression which is in MaybeNil or Nil state.

type nilability

Types are either nilable or non-nilable. When you pass a param or a default value, we use the type : for nilable types we return MaybeNil and for non-nilable Safe.

params rules

Param’s nilability is detected based on type nilability. We use the type of the argument to detect the nilability.

assignment rules

Let’s say we have left = right.

When we assign, we pass the right’s nilability to the left’s expression. There should be special handling of aliasing and compound expressions which we specify in their sections. (Assignment is a possible alias move or move out).

call args rules

When we call with arguments, we have two cases when we might change the nilability.

  1. callByVar(a)

Here callByVar can re-assign a, so this might change a’s nilability, so we change it to MaybeNil. This is also a possible aliasing move out (moving out of a current alias set).

  1. call(a)

Here call can change a field or element of a, so if we have a dependant expression of a : e.g. a.field. Dependants become MaybeNil.

branches rules

Branches are the reason we do nil checking like this: with flow checking. Sources of branching are if, while, for, and, or, case, try and combinations with return, break, continue and raise

We create a new layer/“scope” for each branch where we map expressions to nilability. This happens when we “fork”: usually on the beginning of a construct. When branches “join” we usually unify their expression maps or/and nilabilities.

Merging usually merges maps and alias sets: nilabilities are merged like this:

  1. template union(l: Nilability, r: Nilability): Nilability =
  2. ## unify two states
  3. if l == r:
  4. l
  5. else:
  6. MaybeNil

Special handling is for .isNil and \== nil, also for not, and and or.

not reverses the nilability, and is similar to “forking” : the right expression is checked in the layer resulting from the left one and or is similar to “merging”: the right and left expression should be both checked in the original layer.

isNil, \== nil make expressions Nil. If there is a not or != nil, they make them Safe. We also reverse the nilability in the opposite branch: e.g. else.

compound expressions: field, index expressions

We want to track also field(dot) and index(bracket) expressions.

We track some of those compound expressions which might be nilable as dependants of their bases: a.field is changed if a is moved (re-assigned), similarly a[index] is dependent on a and a.field.field on a.field.

When we move the base, we update dependants to MaybeNil. Otherwise, we usually start with type nilability.

When we call args, we update the nilability of their dependants to MaybeNil as the calls usually can change them. We might need to check for strictFuncs pure funcs and not do that then.

For field expressions a.field, we calculate an integer value based on a hash of the tree and just accept equivalent trees as equivalent expressions.

For item expression a[index], we also calculate an integer value based on a hash of the tree and accept equivalent trees as equivalent expressions: for static values only. For now, we support only constant indices: we don’t track expression with no-const indices. For those we just report a warning even if they are safe for now: one can use a local variable to workaround. For loops this might be annoying: so one should be able to turn off locally the warning using the {.warning[StrictNotNil]:off.}.

For bracket expressions, in the future we might count a[<any>] as the same general expression. This means we should the index but otherwise handle it the same for assign (maybe “aliasing” all the non-static elements) and differentiate only for static: e.g. a[0] and a[1].

element tracking

When we assign an object construction, we should track the fields as well:

  1. var a = Nilable(field: Nilable()) # a : Safe, a.field: Safe

Usually we just track the result of an expression: probably this should apply for elements in other cases as well. Also related to tracking initialization of expressions/fields.

unstructured control flow rules

Unstructured control flow keywords as return, break, continue, raise mean that we jump from a branch out. This means that if there is code after the finishing of the branch, it would be run if one hasn’t hit the direct parent branch of those: so it is similar to an else. In those cases we should use the reverse nilabilities for the local to the condition expressions. E.g.

  1. for a in c:
  2. if not a.isNil:
  3. b()
  4. break
  5. code # here a: Nil , because if not, we would have breaked

aliasing

We support alias detection for local expressions.

We track sets of aliased expressions. We start with all nilable local expressions in separate sets. Assignments and other changes to nilability can move / move out expressions of sets.

move: Moving left to right means we remove left from its current set and unify it with the right’s set. This means it stops being aliased with its previous aliases.

  1. var left = b
  2. left = right # moving left to right

move out: Moving out left might remove it from the current set and ensure that it’s in its own set as a single element. e.g.

  1. var left = b
  2. left = nil # moving out

warnings and errors

We show an error for each dereference ([], .field, [index] () etc.) which is of a tracked expression which is in MaybeNil or Nil state.

We might also show a history of the transitions and the reasons for them that might change the nilability of the expression.

Aliasing restrictions in parameter passing

Note: The aliasing restrictions are currently not enforced by the implementation and need to be fleshed out further.

“Aliasing” here means that the underlying storage locations overlap in memory at runtime. An “output parameter” is a parameter of type var T, an input parameter is any parameter that is not of type var.

  1. Two output parameters should never be aliased.
  2. An input and an output parameter should not be aliased.
  3. An output parameter should never be aliased with a global or thread local variable referenced by the called proc.
  4. An input parameter should not be aliased with a global or thread local variable updated by the called proc.

One problem with rules 3 and 4 is that they affect specific global or thread local variables, but Nim’s effect tracking only tracks “uses no global variable” via .noSideEffect. The rules 3 and 4 can also be approximated by a different rule:

  1. A global or thread local variable (or a location derived from such a location) can only passed to a parameter of a .noSideEffect proc.

Strict funcs

Since version 1.4, a stricter definition of “side effect” is available. In addition to the existing rule that a side effect is calling a function with side effects, the following rule is also enforced:

A store to the heap via a ref or ptr indirection is not allowed.

For example:

  1. {.experimental: "strictFuncs".}
  2. type
  3. Node = ref object
  4. le, ri: Node
  5. data: string
  6. func len(n: Node): int =
  7. # valid: len does not have side effects
  8. var it = n
  9. while it != nil:
  10. inc result
  11. it = it.ri
  12. func mut(n: Node) =
  13. var it = n
  14. while it != nil:
  15. it.data = "yeah" # forbidden mutation
  16. it = it.ri

View types

Tip: --experimental:views is more effective with --experimental:strictFuncs.

A view type is a type that is or contains one of the following types:

  • lent T (view into T)
  • openArray[T] (pair of (pointer to array of T, size))

For example:

  1. type
  2. View1 = openArray[byte]
  3. View2 = lent string
  4. View3 = Table[openArray[char], int]

Exceptions to this rule are types constructed via ptr or proc. For example, the following types are not view types:

  1. type
  2. NotView1 = proc (x: openArray[int])
  3. NotView2 = ptr openArray[char]
  4. NotView3 = ptr array[4, lent int]

The mutability aspect of a view type is not part of the type but part of the locations it’s derived from. More on this later.

A view is a symbol (a let, var, const, etc.) that has a view type.

Since version 1.4, Nim allows view types to be used as local variables. This feature needs to be enabled via {.experimental: “views”.}.

A local variable of a view type borrows from the locations and it is statically enforced that the view does not outlive the location it was borrowed from.

For example:

  1. {.experimental: "views".}
  2. proc take(a: openArray[int]) =
  3. echo a.len
  4. proc main(s: seq[int]) =
  5. var x: openArray[int] = s # 'x' is a view into 's'
  6. # it is checked that 'x' does not outlive 's' and
  7. # that 's' is not mutated.
  8. for i in 0 .. high(x):
  9. echo x[i]
  10. take(x)
  11. take(x.toOpenArray(0, 1)) # slicing remains possible
  12. let y = x # create a view from a view
  13. take y
  14. # it is checked that 'y' does not outlive 'x' and
  15. # that 'x' is not mutated as long as 'y' lives.
  16. main(@[11, 22, 33])

A local variable of a view type can borrow from a location derived from a parameter, another local variable, a global const or let symbol or a thread-local var or let.

Let p the proc that is analysed for the correctness of the borrow operation.

Let source be one of:

  • A formal parameter of p. Note that this does not cover parameters of inner procs.
  • The result symbol of p.
  • A local var or let or const of p. Note that this does not cover locals of inner procs.
  • A thread-local var or let.
  • A global let or const.
  • A constant array/seq/object/tuple constructor.

Path expressions

A location derived from source is then defined as a path expression that has source as the owner. A path expression e is defined recursively:

  • source itself is a path expression.
  • Container access like e[i] is a path expression.
  • Tuple access e[0] is a path expression.
  • Object field access e.field is a path expression.
  • system.toOpenArray(e, …) is a path expression.
  • Pointer dereference e[] is a path expression.
  • An address addr e is a path expression.
  • A type conversion T(e) is a path expression.
  • A cast expression cast[T](e) is a path expression.
  • f(e, …) is a path expression if f’s return type is a view type. Because the view can only have been borrowed from e, we then know that the owner of f(e, …) is e.

If a view type is used as a return type, the location must borrow from a location that is derived from the first parameter that is passed to the proc. See the manual for details about how this is done for var T.

A mutable view can borrow from a mutable location, an immutable view can borrow from both a mutable or an immutable location.

If a view borrows from a mutable location, the view can be used to update the location. Otherwise it cannot be used for mutations.

The duration of a borrow is the span of commands beginning from the assignment to the view and ending with the last usage of the view.

For the duration of the borrow operation, no mutations to the borrowed locations may be performed except via the view that borrowed from the location. The borrowed location is said to be sealed during the borrow.

  1. {.experimental: "views".}
  2. type
  3. Obj = object
  4. field: string
  5. proc dangerous(s: var seq[Obj]) =
  6. let v: lent Obj = s[0] # seal 's'
  7. s.setLen 0 # prevented at compile-time because 's' is sealed.
  8. echo v.field

The scope of the view does not matter:

  1. proc valid(s: var seq[Obj]) =
  2. let v: lent Obj = s[0] # begin of borrow
  3. echo v.field # end of borrow
  4. s.setLen 0 # valid because 'v' isn't used afterwards

The analysis requires as much precision about mutations as is reasonably obtainable, so it is more effective with the experimental strict funcs feature. In other words --experimental:views works better with --experimental:strictFuncs.

The analysis is currently control flow insensitive:

  1. proc invalid(s: var seq[Obj]) =
  2. let v: lent Obj = s[0]
  3. if false:
  4. s.setLen 0
  5. echo v.field

In this example, the compiler assumes that s.setLen 0 invalidates the borrow operation of v even though a human being can easily see that it will never do that at runtime.

Start of a borrow

A borrow starts with one of the following:

  • The assignment of a non-view-type to a view-type.
  • The assignment of a location that is derived from a local parameter to a view-type.

End of a borrow

A borrow operation ends with the last usage of the view variable.

Reborrows

A view v can borrow from multiple different locations. However, the borrow is always the full span of v’s lifetime and every location that is borrowed from is sealed during v’s lifetime.

Algorithm

The following section is an outline of the algorithm that the current implementation uses. The algorithm performs two traversals over the AST of the procedure or global section of code that uses a view variable. No fixpoint iterations are performed, the complexity of the analysis is O(N) where N is the number of nodes of the AST.

The first pass over the AST computes the lifetime of each local variable based on a notion of an “abstract time”, in the implementation it’s a simple integer that is incremented for every visited node.

In the second pass, information about the underlying object “graphs” is computed. Let v be a parameter or a local variable. Let G(v) be the graph that v belongs to. A graph is defined by the set of variables that belong to the graph. Initially for all v: G(v) = {v}. Every variable can only be part of a single graph.

Assignments like a = b “connect” two variables, both variables end up in the same graph {a, b} = G(a) = G(b). Unfortunately, the pattern to look for is much more complex than that and can involve multiple assignment targets and sources:

  1. f(x, y) = g(a, b)

connects x and y to a and b: G(x) = G(y) = G(a) = G(b) = {x, y, a, b}. A type based alias analysis rules out some of these combinations, for example a string value cannot possibly be connected to a seq[int].

A pattern like v[] = value or v.field = value marks G(v) as mutated. After the second pass a set of disjoint graphs was computed.

For strict functions it is then enforced that there is no graph that is both mutated and has an element that is an immutable parameter (that is a parameter that is not of type var T).

For borrow checking, a different set of checks is performed. Let v be the view and b the location that is borrowed from.

  • The lifetime of v must not exceed b’s lifetime. Note: The lifetime of a parameter is the complete proc body.
  • If v is used for a mutation, b must be a mutable location too.
  • During v’s lifetime, G(b) can only be modified by v (and only if v is a mutable view).
  • If v is result then b has to be a location derived from the first formal parameter or from a constant location.
  • A view cannot be used for a read or a write access before it was assigned to.

Concepts

Concepts, also known as “user-defined type classes”, are used to specify an arbitrary set of requirements that the matched type must satisfy.

Concepts are written in the following form:

  1. type
  2. Comparable = concept x, y
  3. (x < y) is bool
  4. Stack[T] = concept s, var v
  5. s.pop() is T
  6. v.push(T)
  7. s.len is Ordinal
  8. for value in s:
  9. value is T

The concept matches if:

  1. all expressions within the body can be compiled for the tested type
  2. all statically evaluable boolean expressions in the body are true
  3. all type modifiers specified match their respective definitions

The identifiers following the concept keyword represent instances of the currently matched type. You can apply any of the standard type modifiers such as var, ref, ptr and static to denote a more specific type of instance. You can also apply the type modifier to create a named instance of the type itself:

  1. type
  2. MyConcept = concept x, var v, ref r, ptr p, static s, type T
  3. ...

Within the concept body, types can appear in positions where ordinary values and parameters are expected. This provides a more convenient way to check for the presence of callable symbols with specific signatures:

  1. type
  2. OutputStream = concept var s
  3. s.write(string)

In order to check for symbols accepting type params, you must prefix the type with the explicit type modifier. The named instance of the type, following the concept keyword is also considered to have the explicit modifier and will be matched only as a type.

  1. type
  2. # Let's imagine a user-defined casting framework with operators
  3. # such as `val.to(string)` and `val.to(JSonValue)`. We can test
  4. # for these with the following concept:
  5. MyCastables = concept x
  6. x.to(type string)
  7. x.to(type JSonValue)
  8. # Let's define a couple of concepts, known from Algebra:
  9. AdditiveMonoid* = concept x, y, type T
  10. x + y is T
  11. T.zero is T # require a proc such as `int.zero` or 'Position.zero'
  12. AdditiveGroup* = concept x, y, type T
  13. x is AdditiveMonoid
  14. -x is T
  15. x - y is T

Please note that the is operator allows one to easily verify the precise type signatures of the required operations, but since type inference and default parameters are still applied in the concept body, it’s also possible to describe usage protocols that do not reveal implementation details.

Much like generics, concepts are instantiated exactly once for each tested type and any static code included within the body is executed only once.

Concept diagnostics

By default, the compiler will report the matching errors in concepts only when no other overload can be selected and a normal compilation error is produced. When you need to understand why the compiler is not matching a particular concept and, as a result, a wrong overload is selected, you can apply the explain pragma to either the concept body or a particular call-site.

  1. type
  2. MyConcept {.explain.} = concept ...
  3. overloadedProc(x, y, z) {.explain.}

This will provide Hints in the compiler output either every time the concept is not matched or only on the particular call-site.

Generic concepts and type binding rules

The concept types can be parametric just like the regular generic types:

  1. ### matrixalgo.nim
  2. import std/typetraits
  3. type
  4. AnyMatrix*[R, C: static int; T] = concept m, var mvar, type M
  5. M.ValueType is T
  6. M.Rows == R
  7. M.Cols == C
  8. m[int, int] is T
  9. mvar[int, int] = T
  10. type TransposedType = stripGenericParams(M)[C, R, T]
  11. AnySquareMatrix*[N: static int, T] = AnyMatrix[N, N, T]
  12. AnyTransform3D* = AnyMatrix[4, 4, float]
  13. proc transposed*(m: AnyMatrix): m.TransposedType =
  14. for r in 0 ..< m.R:
  15. for c in 0 ..< m.C:
  16. result[r, c] = m[c, r]
  17. proc determinant*(m: AnySquareMatrix): int =
  18. ...
  19. proc setPerspectiveProjection*(m: AnyTransform3D) =
  20. ...
  21. --------------
  22. ### matrix.nim
  23. type
  24. Matrix*[M, N: static int; T] = object
  25. data: array[M*N, T]
  26. proc `[]`*(M: Matrix; m, n: int): M.T =
  27. M.data[m * M.N + n]
  28. proc `[]=`*(M: var Matrix; m, n: int; v: M.T) =
  29. M.data[m * M.N + n] = v
  30. # Adapt the Matrix type to the concept's requirements
  31. template Rows*(M: typedesc[Matrix]): int = M.M
  32. template Cols*(M: typedesc[Matrix]): int = M.N
  33. template ValueType*(M: typedesc[Matrix]): typedesc = M.T
  34. -------------
  35. ### usage.nim
  36. import matrix, matrixalgo
  37. var
  38. m: Matrix[3, 3, int]
  39. projectionMatrix: Matrix[4, 4, float]
  40. echo m.transposed.determinant
  41. setPerspectiveProjection projectionMatrix

When the concept type is matched against a concrete type, the unbound type parameters are inferred from the body of the concept in a way that closely resembles the way generic parameters of callable symbols are inferred on call sites.

Unbound types can appear both as params to calls such as s.push(T) and on the right-hand side of the is operator in cases such as x.pop is T and x.data is seq[T].

Unbound static params will be inferred from expressions involving the \== operator and also when types dependent on them are being matched:

  1. type
  2. MatrixReducer[M, N: static int; T] = concept x
  3. x.reduce(SquareMatrix[N, T]) is array[M, int]

The Nim compiler includes a simple linear equation solver, allowing it to infer static params in some situations where integer arithmetic is involved.

Just like in regular type classes, Nim discriminates between bind once and bind many types when matching the concept. You can add the distinct modifier to any of the otherwise inferable types to get a type that will be matched without permanently inferring it. This may be useful when you need to match several procs accepting the same wide class of types:

  1. type
  2. Enumerable[T] = concept e
  3. for v in e:
  4. v is T
  5. type
  6. MyConcept = concept o
  7. # this could be inferred to a type such as Enumerable[int]
  8. o.foo is distinct Enumerable
  9. # this could be inferred to a different type such as Enumerable[float]
  10. o.bar is distinct Enumerable
  11. # it's also possible to give an alias name to a `bind many` type class
  12. type Enum = distinct Enumerable
  13. o.baz is Enum

On the other hand, using bind once types allows you to test for equivalent types used in multiple signatures, without actually requiring any concrete types, thus allowing you to encode implementation-defined types:

  1. type
  2. MyConcept = concept x
  3. type T1 = auto
  4. x.foo(T1)
  5. x.bar(T1) # both procs must accept the same type
  6. type T2 = seq[SomeNumber]
  7. x.alpha(T2)
  8. x.omega(T2) # both procs must accept the same type
  9. # and it must be a numeric sequence

As seen in the previous examples, you can refer to generic concepts such as Enumerable[T] just by their short name. Much like the regular generic types, the concept will be automatically instantiated with the bind once auto type in the place of each missing generic param.

Please note that generic concepts such as Enumerable[T] can be matched against concrete types such as string. Nim doesn’t require the concept type to have the same number of parameters as the type being matched. If you wish to express a requirement towards the generic parameters of the matched type, you can use a type mapping operator such as genericHead or stripGenericParams within the body of the concept to obtain the uninstantiated version of the type, which you can then try to instantiate in any required way. For example, here is how one might define the classic Functor concept from Haskell and then demonstrate that Nim’s Option[T] type is an instance of it:

  1. import std/[sugar, typetraits]
  2. type
  3. Functor[A] = concept f
  4. type MatchedGenericType = genericHead(typeof(f))
  5. # `f` will be a value of a type such as `Option[T]`
  6. # `MatchedGenericType` will become the `Option` type
  7. f.val is A
  8. # The Functor should provide a way to obtain
  9. # a value stored inside it
  10. type T = auto
  11. map(f, A -> T) is MatchedGenericType[T]
  12. # And it should provide a way to map one instance of
  13. # the Functor to a instance of a different type, given
  14. # a suitable `map` operation for the enclosed values
  15. import std/options
  16. echo Option[int] is Functor # prints true

Concept derived values

All top level constants or types appearing within the concept body are accessible through the dot operator in procs where the concept was successfully matched to a concrete type:

  1. type
  2. DateTime = concept t1, t2, type T
  3. const Min = T.MinDate
  4. T.Now is T
  5. t1 < t2 is bool
  6. type TimeSpan = typeof(t1 - t2)
  7. TimeSpan * int is TimeSpan
  8. TimeSpan + TimeSpan is TimeSpan
  9. t1 + TimeSpan is T
  10. proc eventsJitter(events: Enumerable[DateTime]): float =
  11. var
  12. # this variable will have the inferred TimeSpan type for
  13. # the concrete Date-like value the proc was called with:
  14. averageInterval: DateTime.TimeSpan
  15. deviation: float
  16. ...

Concept refinement

When the matched type within a concept is directly tested against a different concept, we say that the outer concept is a refinement of the inner concept and thus it is more-specific. When both concepts are matched in a call during overload resolution, Nim will assign a higher precedence to the most specific one. As an alternative way of defining concept refinements, you can use the object inheritance syntax involving the of keyword:

  1. type
  2. Graph = concept g, type G of EquallyComparable, Copyable
  3. type
  4. VertexType = G.VertexType
  5. EdgeType = G.EdgeType
  6. VertexType is Copyable
  7. EdgeType is Copyable
  8. var
  9. v: VertexType
  10. e: EdgeType
  11. IncidendeGraph = concept of Graph
  12. # symbols such as variables and types from the refined
  13. # concept are automatically in scope:
  14. g.source(e) is VertexType
  15. g.target(e) is VertexType
  16. g.outgoingEdges(v) is Enumerable[EdgeType]
  17. BidirectionalGraph = concept g, type G
  18. # The following will also turn the concept into a refinement when it
  19. # comes to overload resolution, but it doesn't provide the convenient
  20. # symbol inheritance
  21. g is IncidendeGraph
  22. g.incomingEdges(G.VertexType) is Enumerable[G.EdgeType]
  23. proc f(g: IncidendeGraph)
  24. proc f(g: BidirectionalGraph) # this one will be preferred if we pass a type
  25. # matching the BidirectionalGraph concept

Dynamic arguments for bindSym

This experimental feature allows the symbol name argument of macros.bindSym to be computed dynamically.

  1. {.experimental: "dynamicBindSym".}
  2. import macros
  3. macro callOp(opName, arg1, arg2): untyped =
  4. result = newCall(bindSym($opName), arg1, arg2)
  5. echo callOp("+", 1, 2)
  6. echo callOp("-", 5, 4)

Term rewriting macros

Term rewriting macros are macros or templates that have not only a name but also a pattern that is searched for after the semantic checking phase of the compiler: This means they provide an easy way to enhance the compilation pipeline with user defined optimizations:

  1. template optMul{`*`(a, 2)}(a: int): int = a + a
  2. let x = 3
  3. echo x * 2

The compiler now rewrites x * 2 as x + x. The code inside the curly brackets is the pattern to match against. The operators *, **, |, ~ have a special meaning in patterns if they are written in infix notation, so to match verbatim against * the ordinary function call syntax needs to be used.

Term rewriting macros are applied recursively, up to a limit. This means that if the result of a term rewriting macro is eligible for another rewriting, the compiler will try to perform it, and so on, until no more optimizations are applicable. To avoid putting the compiler into an infinite loop, there is a hard limit on how many times a single term rewriting macro can be applied. Once this limit has been passed, the term rewriting macro will be ignored.

Unfortunately optimizations are hard to get right and even this tiny example is wrong:

  1. template optMul{`*`(a, 2)}(a: int): int = a + a
  2. proc f(): int =
  3. echo "side effect!"
  4. result = 55
  5. echo f() * 2

We cannot duplicate ‘a’ if it denotes an expression that has a side effect! Fortunately Nim supports side effect analysis:

  1. template optMul{`*`(a, 2)}(a: int{noSideEffect}): int = a + a
  2. proc f(): int =
  3. echo "side effect!"
  4. result = 55
  5. echo f() * 2 # not optimized ;-)

You can make one overload matching with a constraint and one without, and the one with a constraint will have precedence, and so you can handle both cases differently.

So what about 2 * a? We should tell the compiler * is commutative. We cannot really do that however as the following code only swaps arguments blindly:

  1. template mulIsCommutative{`*`(a, b)}(a, b: int): int = b * a

What optimizers really need to do is a canonicalization:

  1. template canonMul{`*`(a, b)}(a: int{lit}, b: int): int = b * a

The int{lit} parameter pattern matches against an expression of type int, but only if it’s a literal.

Parameter constraints

The parameter constraint expression can use the operators | (or), & (and) and ~ (not) and the following predicates:

PredicateMeaning
atomThe matching node has no children.
litThe matching node is a literal like “abc”, 12.
symThe matching node must be a symbol (a bound identifier).
identThe matching node must be an identifier (an unbound identifier).
callThe matching AST must be a call/apply expression.
lvalueThe matching AST must be an lvalue.
sideeffectThe matching AST must have a side effect.
nosideeffectThe matching AST must have no side effect.
paramA symbol which is a parameter.
genericparamA symbol which is a generic parameter.
moduleA symbol which is a module.
typeA symbol which is a type.
varA symbol which is a variable.
letA symbol which is a let variable.
constA symbol which is a constant.
resultThe special result variable.
procA symbol which is a proc.
methodA symbol which is a method.
iteratorA symbol which is an iterator.
converterA symbol which is a converter.
macroA symbol which is a macro.
templateA symbol which is a template.
fieldA symbol which is a field in a tuple or an object.
enumfieldA symbol which is a field in an enumeration.
forvarA for loop variable.
labelA label (used in block statements).
nk*The matching AST must have the specified kind. (Example: nkIfStmt denotes an if statement.)
aliasStates that the marked parameter needs to alias with some other parameter.
noaliasStates that every other parameter must not alias with the marked parameter.

Predicates that share their name with a keyword have to be escaped with backticks. The alias and noalias predicates refer not only to the matching AST, but also to every other bound parameter; syntactically they need to occur after the ordinary AST predicates:

  1. template ex{a = b + c}(a: int{noalias}, b, c: int) =
  2. # this transformation is only valid if 'b' and 'c' do not alias 'a':
  3. a = b
  4. inc a, c

Another example:

  1. proc somefunc(s: string) = assert s == "variable"
  2. proc somefunc(s: string{nkStrLit}) = assert s == "literal"
  3. proc somefunc(s: string{nkRStrLit}) = assert s == r"raw"
  4. proc somefunc(s: string{nkTripleStrLit}) = assert s == """triple"""
  5. proc somefunc(s: static[string]) = assert s == "constant"
  6. # Use parameter constraints to provide overloads based on both the input parameter type and form.
  7. var variable = "variable"
  8. somefunc(variable)
  9. const constant = "constant"
  10. somefunc(constant)
  11. somefunc("literal")
  12. somefunc(r"raw")
  13. somefunc("""triple""")

Pattern operators

The operators *, **, |, ~ have a special meaning in patterns if they are written in infix notation.

The | operator

The | operator if used as infix operator creates an ordered choice:

  1. template t{0|1}(): untyped = 3
  2. let a = 1
  3. # outputs 3:
  4. echo a

The matching is performed after the compiler performed some optimizations like constant folding, so the following does not work:

  1. template t{0|1}(): untyped = 3
  2. # outputs 1:
  3. echo 1

The reason is that the compiler already transformed the 1 into “1” for the echo statement. However, a term rewriting macro should not change the semantics anyway. In fact, they can be deactivated with the --patterns:off command line option or temporarily with the patterns pragma.

The {} operator

A pattern expression can be bound to a pattern parameter via the expr{param} notation:

  1. template t{(0|1|2){x}}(x: untyped): untyped = x + 1
  2. let a = 1
  3. # outputs 2:
  4. echo a

The ~ operator

The ~ operator is the ‘not’ operator in patterns:

  1. template t{x = (~x){y} and (~x){z}}(x, y, z: bool) =
  2. x = y
  3. if x: x = z
  4. var
  5. a = false
  6. b = true
  7. c = false
  8. a = b and c
  9. echo a

The * operator

The * operator can flatten a nested binary expression like a & b & c to &(a, b, c):

  1. var
  2. calls = 0
  3. proc `&&`(s: varargs[string]): string =
  4. result = s[0]
  5. for i in 1..len(s)-1: result.add s[i]
  6. inc calls
  7. template optConc{ `&&` * a }(a: string): untyped = &&a
  8. let space = " "
  9. echo "my" && (space & "awe" && "some " ) && "concat"
  10. # check that it's been optimized properly:
  11. doAssert calls == 1

The second operator of * must be a parameter; it is used to gather all the arguments. The expression “my” && (space & “awe” && “some “ ) && “concat” is passed to optConc in a as a special list (of kind nkArgList) which is flattened into a call expression; thus the invocation of optConc produces:

  1. `&&`("my", space & "awe", "some ", "concat")

The ** operator

The ** is much like the * operator, except that it gathers not only all the arguments, but also the matched operators in reverse polish notation:

  1. import std/macros
  2. type
  3. Matrix = object
  4. dummy: int
  5. proc `*`(a, b: Matrix): Matrix = discard
  6. proc `+`(a, b: Matrix): Matrix = discard
  7. proc `-`(a, b: Matrix): Matrix = discard
  8. proc `$`(a: Matrix): string = result = $a.dummy
  9. proc mat21(): Matrix =
  10. result.dummy = 21
  11. macro optM{ (`+`|`-`|`*`) ** a }(a: Matrix): untyped =
  12. echo treeRepr(a)
  13. result = newCall(bindSym"mat21")
  14. var x, y, z: Matrix
  15. echo x + y * z - x

This passes the expression x + y * z - x to the optM macro as an nnkArgList node containing:

  1. Arglist
  2. Sym "x"
  3. Sym "y"
  4. Sym "z"
  5. Sym "*"
  6. Sym "+"
  7. Sym "x"
  8. Sym "-"

(This is the reverse polish notation of x + y * z - x.)

Parameters

Parameters in a pattern are type checked in the matching process. If a parameter is of the type varargs, it is treated specially and can match 0 or more arguments in the AST to be matched against:

  1. template optWrite{
  2. write(f, x)
  3. ((write|writeLine){w})(f, y)
  4. }(x, y: varargs[untyped], f: File, w: untyped) =
  5. w(f, x, y)

noRewrite pragma

Term rewriting macros and templates are currently greedy and they will rewrite as long as there is a match. There was no way to ensure some rewrite happens only once, e.g. when rewriting term to same term plus extra content.

noRewrite pragma can actually prevent further rewriting on marked code, e.g. with given example echo(“ab”) will be rewritten just once:

  1. template pwnEcho{echo(x)}(x: untyped) =
  2. {.noRewrite.}: echo("pwned!")
  3. echo "ab"

noRewrite pragma can be useful to control term-rewriting macros recursion.

Example: Partial evaluation

The following example shows how some simple partial evaluation can be implemented with term rewriting:

  1. proc p(x, y: int; cond: bool): int =
  2. result = if cond: x + y else: x - y
  3. template optP1{p(x, y, true)}(x, y: untyped): untyped = x + y
  4. template optP2{p(x, y, false)}(x, y: untyped): untyped = x - y

Example: Hoisting

The following example shows how some form of hoisting can be implemented:

  1. import std/pegs
  2. template optPeg{peg(pattern)}(pattern: string{lit}): Peg =
  3. var gl {.global, gensym.} = peg(pattern)
  4. gl
  5. for i in 0 .. 3:
  6. echo match("(a b c)", peg"'(' @ ')'")
  7. echo match("W_HI_Le", peg"\y 'while'")

The optPeg template optimizes the case of a peg constructor with a string literal, so that the pattern will only be parsed once at program startup and stored in a global gl which is then re-used. This optimization is called hoisting because it is comparable to classical loop hoisting.

AST based overloading

Parameter constraints can also be used for ordinary routine parameters; these constraints then affect ordinary overloading resolution:

  1. proc optLit(a: string{lit|`const`}) =
  2. echo "string literal"
  3. proc optLit(a: string) =
  4. echo "no string literal"
  5. const
  6. constant = "abc"
  7. var
  8. variable = "xyz"
  9. optLit("literal")
  10. optLit(constant)
  11. optLit(variable)

However, the constraints alias and noalias are not available in ordinary routines.

Parallel & Spawn

Nim has two flavors of parallelism:

  1. Structured parallelism via the parallel statement.
  2. Unstructured parallelism via the standalone spawn statement.

Nim has a builtin thread pool that can be used for CPU intensive tasks. For IO intensive tasks the async and await features should be used instead. Both parallel and spawn need the threadpool module to work.

Somewhat confusingly, spawn is also used in the parallel statement with slightly different semantics. spawn always takes a call expression of the form f(a, …). Let T be f’s return type. If T is void, then spawn’s return type is also void, otherwise it is FlowVar[T].

Within a parallel section, the FlowVar[T] is sometimes eliminated to T. This happens when T does not contain any GC’ed memory. The compiler can ensure the location in location = spawn f(…) is not read prematurely within a parallel section and so there is no need for the overhead of an indirection via FlowVar[T] to ensure correctness.

Note: Currently exceptions are not propagated between spawn’ed tasks!

This feature is likely to be removed in the future as external packages can have better solutions.

Spawn statement

The spawn statement can be used to pass a task to the thread pool:

  1. import std/threadpool
  2. proc processLine(line: string) =
  3. discard "do some heavy lifting here"
  4. for x in lines("myinput.txt"):
  5. spawn processLine(x)
  6. sync()

For reasons of type safety and implementation simplicity the expression that spawn takes is restricted:

  • It must be a call expression f(a, …).
  • f must be gcsafe.
  • f must not have the calling convention closure.
  • f’s parameters may not be of type var. This means one has to use raw ptr’s for data passing reminding the programmer to be careful.
  • ref parameters are deeply copied, which is a subtle semantic change and can cause performance problems, but ensures memory safety. This deep copy is performed via system.deepCopy, so it can be overridden.
  • For safe data exchange between f and the caller, a global Channel needs to be used. However, since spawn can return a result, often no further communication is required.

spawn executes the passed expression on the thread pool and returns a data flow variable FlowVar[T] that can be read from. The reading with the ^ operator is blocking. However, one can use blockUntilAny to wait on multiple flow variables at the same time:

  1. import std/threadpool, ...
  2. # wait until 2 out of 3 servers received the update:
  3. proc main =
  4. var responses = newSeq[FlowVarBase](3)
  5. for i in 0..2:
  6. responses[i] = spawn tellServer(Update, "key", "value")
  7. var index = blockUntilAny(responses)
  8. assert index >= 0
  9. responses.del(index)
  10. discard blockUntilAny(responses)

Data flow variables ensure that no data races are possible. Due to technical limitations, not every type T can be used in a data flow variable: T has to be a ref, string, seq or of a type that doesn’t contain any GC’d type. This restriction is not hard to work-around in practice.

Parallel statement

Example:

  1. # Compute pi in an inefficient way
  2. import std/[strutils, math, threadpool]
  3. {.experimental: "parallel".}
  4. proc term(k: float): float = 4 * math.pow(-1, k) / (2*k + 1)
  5. proc pi(n: int): float =
  6. var ch = newSeq[float](n + 1)
  7. parallel:
  8. for k in 0..ch.high:
  9. ch[k] = spawn term(float(k))
  10. for k in 0..ch.high:
  11. result += ch[k]
  12. echo formatFloat(pi(5000))

The parallel statement is the preferred mechanism to introduce parallelism in a Nim program. Only a subset of the Nim language is valid within a parallel section. This subset is checked during semantic analysis to be free of data races. A sophisticated disjoint checker ensures that no data races are possible, even though shared memory is extensively supported!

The subset is in fact the full language with the following restrictions / changes:

  • spawn within a parallel section has special semantics.
  • Every location of the form a[i], a[i..j] and dest where dest is part of the pattern dest = spawn f(…) has to be provably disjoint. This is called the disjoint check.
  • Every other complex location loc that is used in a spawned proc (spawn f(loc)) has to be immutable for the duration of the parallel section. This is called the immutability check. Currently it is not specified what exactly “complex location” means. We need to make this an optimization!
  • Every array access has to be provably within bounds. This is called the bounds check.
  • Slices are optimized so that no copy is performed. This optimization is not yet performed for ordinary slices outside of a parallel section.

Strict definitions and out parameters

With experimental: “strictDefs” every local variable must be initialized explicitly before it can be used:

  1. {.experimental: "strictDefs".}
  2. proc test =
  3. var s: seq[string]
  4. s.add "abc" # invalid!

Needs to be written as:

  1. {.experimental: "strictDefs".}
  2. proc test =
  3. var s: seq[string] = @[]
  4. s.add "abc" # valid!

A control flow analysis is performed in order to prove that a variable has been written to before it is used. Thus the following is valid:

  1. {.experimental: "strictDefs".}
  2. proc test(cond: bool) =
  3. var s: seq[string]
  4. if cond:
  5. s = @["y"]
  6. else:
  7. s = @[]
  8. s.add "abc" # valid!

In this example every path does set s to a value before it is used.

  1. {.experimental: "strictDefs".}
  2. proc test(cond: bool) =
  3. let s: seq[string]
  4. if cond:
  5. s = @["y"]
  6. else:
  7. s = @[]

With experimental: “strictDefs”, let statements are allowed to not have an initial value, but every path should set s to a value before it is used.

out parameters

An out parameter is like a var parameter but it must be written to before it can be used:

  1. proc myopen(f: out File; name: string): bool =
  2. f = default(File)
  3. result = open(f, name)

While it is usually the better style to use the return type in order to return results API and ABI considerations might make this infeasible. Like for var T Nim maps out T to a hidden pointer. For example POSIX’s stat routine can be wrapped as:

  1. proc stat*(a1: cstring, a2: out Stat): cint {.importc, header: "<sys/stat.h>".}

When the implementation of a routine with output parameters is analysed, the compiler checks that every path before the (implicit or explicit) return does set every output parameter:

  1. proc p(x: out int; y: out string; cond: bool) =
  2. x = 4
  3. if cond:
  4. y = "abc"
  5. # error: not every path initializes 'y'

Out parameters and exception handling

The analysis should take exceptions into account (but currently does not):

  1. proc p(x: out int; y: out string; cond: bool) =
  2. x = canRaise(45)
  3. y = "abc" # <-- error: not every path initializes 'y'

Once the implementation takes exceptions into account it is easy enough to use outParam = default(typeof(outParam)) in the beginning of the proc body.

Out parameters and inheritance

It is not valid to pass an lvalue of a supertype to an out T parameter:

  1. type
  2. Superclass = object of RootObj
  3. a: int
  4. Subclass = object of Superclass
  5. s: string
  6. proc init(x: out Superclass) =
  7. x = Superclass(a: 8)
  8. var v: Subclass
  9. init v
  10. use v.s # the 's' field was never initialized!

However, in the future this could be allowed and provide a better way to write object constructors that take inheritance into account.

Note: The implementation of “strict definitions” and “out parameters” is experimental but the concept is solid and it is expected that eventually this mode becomes the default in later versions.

Strict case objects

With experimental: “strictCaseObjects” every field access is checked to be valid at compile-time. The field is within a case section of an object.

  1. {.experimental: "strictCaseObjects".}
  2. type
  3. Foo = object
  4. case b: bool
  5. of false:
  6. s: string
  7. of true:
  8. x: int
  9. var x = Foo(b: true, x: 4)
  10. case x.b
  11. of true:
  12. echo x.x # valid
  13. of false:
  14. echo "no"
  15. case x.b
  16. of false:
  17. echo x.x # error: field access outside of valid case branch: x.x
  18. of true:
  19. echo "no"

Note: The implementation of “strict case objects” is experimental but the concept is solid and it is expected that eventually this mode becomes the default in later versions.

Quirky routines

The default code generation strategy of exceptions under the ARC/ORC model is the so called --exceptions:goto implementation. This implementation inserts a check after every call that can potentially raise an exception. A typical instruction sequence for this on for a x86 64 bit machine looks like:

  1. cmp DWORD PTR [rbx], 0
  2. je .L1

This is a memory fetch followed by jump. (An ideal implementation would use the carry flag and a single instruction like jc .L1.)

This overhead might not be desired and depending on the sematics of the routine may not be required either. So it can be disabled via a .quirky annotation:

  1. proc wontRaise(x: int) {.quirky.} =
  2. if x != 0:
  3. # because of `quirky` this will continue even if `write` raised an IO exception:
  4. write x
  5. wontRaise(x-1)
  6. wontRaise 10

If the used exception model is not --exceptions:goto then the quirky pragma has no effect and is ignored.

The quirky pragma can also be be pushed in order to affect a group of routines and whether the compiler supports the pragma can be checked with defined(nimHasQuirky):

  1. when defined(nimHasQuirky):
  2. {.push quirky: on.}
  3. proc doRaise() = raise newException(ValueError, "")
  4. proc f(): string = "abc"
  5. proc q(cond: bool) =
  6. if cond:
  7. doRaise()
  8. echo f()
  9. q(true)
  10. when defined(nimHasQuirky):
  11. {.pop.}

Warning: The quirky pragma only affects code generation, no check for validity is performed!

Threading under ARC/ORC

ARC/ORC supports a shared heap out of the box. This means that messages can be sent between threads without copies. However, without copying the data there is an inherent danger of data races. Data races are prevented at compile-time if it is enforced that only isolated subgraphs can be sent around.

Isolation

The standard library module isolation.nim provides a generic type Isolated[T] that captures the important notion that nothing else can reference the graph that is wrapped inside Isolated[T]. It is what a channel implementation should use in order to enforce the freedom of data races:

  1. proc send*[T](c: var Channel[T]; msg: sink Isolated[T])
  2. proc recv*[T](c: var Channel[T]): T
  3. ## Note: Returns T, not Isolated[T] for convenience.
  4. proc recvIso*[T](c: var Channel[T]): Isolated[T]
  5. ## remembers the data is Isolated[T].

In order to create an Isolated graph one has to use either isolate or unsafeIsolate. unsafeIsolate is as its name says unsafe and no checking is performed. It should be considered to be as dangerous as a cast operation.

Construction must ensure that the invariant holds, namely that the wrapped T is free of external aliases into it. isolate ensures this invariant. It is inspired by Pony’s recover construct:

  1. func isolate(x: sink T): Isolated[T] {.magic: "Isolate".}

As you can see, this is a new builtin because the check it performs on x is non-trivial:

If T does not contain a ref or closure type, it is isolated. Else the syntactic structure of x is analyzed:

  • Literals like nil, 4, “abc” are isolated.
  • A local variable or a routine parameter is isolated if either of these conditions is true:
    1. Its type is annotated with the .sendable pragma. Note Isolated[T] is annotated as .sendable.
    2. Its type contains the potentially dangerous ref and proc {.closure} types only in places that are protected via a .sendable container.
  • An array constructor [x…] is isolated if every element x is isolated.
  • An object constructor Obj(x…) is isolated if every element x is isolated.
  • An if or case expression is isolated if all possible values the expression may return are isolated.
  • A type conversion C(x) is isolated if x is isolated. Analogous for cast expressions.
  • A function call f(x…) is isolated if f is .noSideEffect and for every argument x:
    • x is isolated or
    • f’s return type cannot alias x’s type. This is checked via a form of alias analysis as explained in the next paragraph.

Alias analysis

We start with an important, simple case that must be valid: Sending the result of parseJson to a channel. Since the signature is func parseJson(input: string): JsonNode it is easy to see that JsonNode can never simply be a view into input which is a string.

A different case is the identity function id, send id(myJsonGraph) must be invalid because we do not know how many aliases into myJsonGraph exist elsewhere.

In general type A can alias type T if:

  • A and T are the same types.
  • A is a distinct type derived from T.
  • A is a field inside T if T is a final object type.
  • T is an inheritable object type. (An inherited type could always contain a field: A).
  • T is a closure type. Reason: T’s environment can contain a field of type A.
  • A is the element type of T if T is an array, sequence or pointer type.

Sendable pragma

A container type can be marked as .sendable. .sendable declares that the type encapsulates a ref type effectively so that a variable of this container type can be used in an isolate context:

  1. type
  2. Isolated*[T] {.sendable.} = object ## Isolated data can only be moved, not copied.
  3. value: T
  4. proc `=copy`*[T](dest: var Isolated[T]; src: Isolated[T]) {.error.}
  5. proc `=sink`*[T](dest: var Isolated[T]; src: Isolated[T]) {.inline.} =
  6. # delegate to value's sink operation
  7. `=sink`(dest.value, src.value)
  8. proc `=destroy`*[T](dest: var Isolated[T]) {.inline.} =
  9. # delegate to value's destroy operation
  10. `=destroy`(dest.value)

The .sendable pragma itself is an experimenal, unchecked, unsafe annotation. It is currently only used by Isolated[T].

Virtual pragma

virtual is designed to extend or create virtual functions when targeting the cpp backend. When a proc is marked with virtual, it forward declares the proc header within the type’s body.

Here’s an example of how to use the virtual pragma:

  1. proc newCpp*[T](): ptr T {.importcpp: "new '*0()".}
  2. type
  3. Foo = object of RootObj
  4. FooPtr = ptr Foo
  5. Boo = object of Foo
  6. BooPtr = ptr Boo
  7. proc salute(self: FooPtr) {.virtual.} =
  8. echo "hello foo"
  9. proc salute(self: BooPtr) {.virtual.} =
  10. echo "hello boo"
  11. let foo = newCpp[Foo]()
  12. let boo = newCpp[Boo]()
  13. let booAsFoo = cast[FooPtr](newCpp[Boo]())
  14. foo.salute() # prints hello foo
  15. boo.salute() # prints hello boo
  16. booAsFoo.salute() # prints hello boo

In this example, the salute function is virtual in both Foo and Boo types. This allows for polymorphism.

The virtual pragma also supports a special syntax to express Cpp constraints. Here’s how it works:

$1 refers to the function name ‘idx refers to the type of the argument at the position idx. Where idx = 1 is the this argument. #idx refers to the argument name.

The return type can be referred to as -> ‘0, but this is optional and often not needed.

  1. {.emit:"""/*TYPESECTION*/
  2. #include <iostream>
  3. class CppPrinter {
  4. public:
  5. virtual void printConst(char* message) const {
  6. std::cout << "Const Message: " << message << std::endl;
  7. }
  8. virtual void printConstRef(char* message, const int& flag) const {
  9. std::cout << "Const Ref Message: " << message << std::endl;
  10. }
  11. };
  12. """.}
  13. type
  14. CppPrinter {.importcpp, inheritable.} = object
  15. NimPrinter {.exportc.} = object of CppPrinter
  16. proc printConst(self: CppPrinter; message:cstring) {.importcpp.}
  17. CppPrinter().printConst(message)
  18. # override is optional.
  19. proc printConst(self: NimPrinter; message: cstring) {.virtual: "$1('2 #2) const override".} =
  20. echo "NimPrinter: " & $message
  21. proc printConstRef(self: NimPrinter; message: cstring; flag:int32) {.virtual: "$1('2 #2, const '3& #3 ) const override".} =
  22. echo "NimPrinterConstRef: " & $message
  23. NimPrinter().printConst(message)
  24. var val: int32 = 10
  25. NimPrinter().printConstRef(message, val)

Constructor pragma

The constructor pragma can be used in two ways: in conjunction with importcpp to import a C++ constructor, and to declare constructors that operate similarly to virtual.

Consider:

  1. type Foo* = object
  2. x: int32
  3. proc makeFoo(x: int32): Foo {.constructor.} =
  4. this.x = x

It forward declares the constructor in the type definition. When the constructor has parameters, it also generates a default constructor. Notice, inside the body of the constructor one has access to this which is of the type ptr Foo. No result variable is available.

Like virtual, constructor also supports a syntax that allows to express C++ constraints.

For example:

  1. {.emit:"""/*TYPESECTION*/
  2. struct CppClass {
  3. int x;
  4. int y;
  5. CppClass(int inX, int inY) {
  6. this->x = inX;
  7. this->y = inY;
  8. }
  9. //CppClass() = default;
  10. };
  11. """.}
  12. type
  13. CppClass* {.importcpp, inheritable.} = object
  14. x: int32
  15. y: int32
  16. NimClass* = object of CppClass
  17. proc makeNimClass(x: int32): NimClass {.constructor:"NimClass('1 #1) : CppClass(0, #1)".} =
  18. this.x = x
  19. # Optional: define the default constructor explicitly
  20. proc makeCppClass(): NimClass {.constructor: "NimClass() : CppClass(0, 0)".} =
  21. this.x = 1

In the example above CppClass has a deleted default constructor. Notice how by using the constructor syntax, one can call the appropiate constructor.

Notice when calling a constructor in the section of a global variable initialization, it will be called before NimMain meaning Nim is not fully initialized.