Skip to content

Borrowing for var T and lent T to improve Nim's memory safety #7373

@Araq

Description

@Araq

This proposal finally solves issue #124 by a simple borrow checking rule: A return type of var T is assumed and enforced to be a view into the location reachable by the first parameter of the proc.

Every known usage of var T in the standard library is derived from the first parameter. Other code like

var global: int
proc foo(): var int = global

will fail to compile. Furthermore the analysis needs to forbit mutating operations on the collection for as long as the var T views are "borrowed". Since let x = returnsVarT(collection) conceptually turns the pointer view into a copy, this borrow check should be rather easy to enforce. I hope.

Let us see how this outlined borrowing rule solves #124:

proc forward[T](x: var T): var T = result = x # ok, derives from the first parameter.
proc p(param: var int): var int =
  var x: int
  result = forward(x) # Error: location is derived from ``x`` which is not p's first parameter.

Future directions

Later versions can be more precise with a syntax like

proc foo(container: var X): var T from container

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions