Make {.requiresInit.} to work for distinct types (#15869)
Make `requiresInit` pragma to work for distinct types in addition to
objects. Tagging of distinct types with `requiresInit` pragma was
already supported, but its impact wasn't applied. Now its behavior when
applied on distinct types is as follows.
Given the following distinct type definitions:
```nim
type
DistinctObject {.requiresInit, borrow: `.`.} = distinct MyObject
DistinctString {.requiresInit.} = distinct string
```
The following code blocks will fail to compile:
```nim
var foo: DistinctFoo
foo.x = "test"
doAssert foo.x == "test"
```
```nim
var s: DistinctString
s = "test"
doAssert s == "test"
```
But these ones will compile successfully:
```nim
let foo = DistinctFoo(Foo(x: "test"))
doAssert foo.x == "test"
```
```nim
let s = "test"
doAssert s == "test"
```
This commit is contained in:
parent
60c364fb22
commit
3c85aa9e53
6 changed files with 82 additions and 9 deletions
|
|
@ -106,3 +106,35 @@ type FooD = distinct int
|
|||
proc `<=`(a, b: FooD): bool {.borrow.}
|
||||
|
||||
for f in [FooD(0): "Foo"]: echo f
|
||||
|
||||
block tRequiresInit:
|
||||
template accept(x) =
|
||||
static: doAssert compiles(x)
|
||||
|
||||
template reject(x) =
|
||||
static: doAssert not compiles(x)
|
||||
|
||||
type
|
||||
Foo = object
|
||||
x: string
|
||||
|
||||
DistinctFoo {.requiresInit, borrow: `.`.} = distinct Foo
|
||||
DistinctString {.requiresInit.} = distinct string
|
||||
|
||||
reject:
|
||||
var foo: DistinctFoo
|
||||
foo.x = "test"
|
||||
doAssert foo.x == "test"
|
||||
|
||||
accept:
|
||||
let foo = DistinctFoo(Foo(x: "test"))
|
||||
doAssert foo.x == "test"
|
||||
|
||||
reject:
|
||||
var s: DistinctString
|
||||
s = "test"
|
||||
doAssert s == "test"
|
||||
|
||||
accept:
|
||||
let s = "test"
|
||||
doAssert s == "test"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue