mirror of
https://github.com/nim-lang/Nim.git
synced 2026-04-21 23:05:27 +00:00
borrow checking (#15282)
* refactoring: move procs to typeallowed.nim * frontend preparations for first class openArray support * prepare the code generator for first class openArray * code generation for first class openArray; WIP * code generation for open arrays, progress * added isViewType proc * preparations for borrow checking * added borrow checking to the front end
This commit is contained in:
@@ -1836,3 +1836,55 @@ For example:
|
||||
|
||||
|
||||
The algorithm behind this analysis is currently not documented.
|
||||
|
||||
|
||||
View types
|
||||
==========
|
||||
|
||||
A view type is a type that contains one of the following types:
|
||||
|
||||
- ``var T`` (mutable view into ``T``)
|
||||
- ``lent T`` (immutable view into ``T``)
|
||||
- ``openArray[T]`` (pair of (pointer to array of ``T``, size))
|
||||
|
||||
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:
|
||||
|
||||
.. code-block:: nim
|
||||
|
||||
{.experimental: "views".}
|
||||
|
||||
proc take(a: openArray[int]) =
|
||||
echo a.len
|
||||
|
||||
proc main(s: seq[int]) =
|
||||
var x: openArray[int] = s # 'x' is a view into 's'
|
||||
# it is checked that 'x' does not outlive 's' and
|
||||
# that 's' is not mutated.
|
||||
for i in 0 .. high(x):
|
||||
echo x[i]
|
||||
take(x)
|
||||
|
||||
take(x.toOpenArray(0, 1)) # slicing remains possible
|
||||
let y = x # create a view from a view
|
||||
take y
|
||||
# it is checked that 'y' does not outlive 'x' and
|
||||
# that 'x' is not mutated as long as 'y' lives.
|
||||
|
||||
|
||||
main(@[11, 22, 33])
|
||||
|
||||
|
||||
|
||||
If a view type is used as a return type, the location must borrow from the
|
||||
first parameter that is passed to the proc.
|
||||
See https://nim-lang.org/docs/manual.html#procedures-var-return-type for
|
||||
details about how this is done for ``var T``.
|
||||
|
||||
The algorithm behind this analysis is currently not documented.
|
||||
|
||||
Reference in New Issue
Block a user