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:
Ivan Bobev 2020-11-06 20:56:09 +02:00 • committed by GitHub
commit 3c85aa9e53
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 82 additions and 9 deletions

View file

@ -611,7 +611,8 @@ proc semVarOrLet(c: PContext, n: PNode, symkind: TSymKind): PNode =
if def.kind == nkEmpty:
let actualType = v.typ.skipTypes({tyGenericInst, tyAlias,
tyUserTypeClassInst})
if actualType.kind == tyObject and actualType.requiresInit:
if actualType.kind in {tyObject, tyDistinct} and
actualType.requiresInit:
defaultConstructionError(c, v.typ, v.info)
else:
checkNilable(c, v)