Skip to content

Cannot for-loop with a distinct type in a generic proc #12086

Open
@mratsim

Description

@mratsim

This is an advanced version of #12074 and probably a case of #8677 or #11225.

This makes distinct types very hard to use.

Take #12074 (whi was fixed)

# distinct_for_loop.nim

type
  Slot = distinct uint64

proc inc(x: var Slot, y = 1){.borrow.}
proc `..`(a, b: Slot): Slice[Slot]{.borrow.}
proc `<`(a, b: Slot): bool{.borrow.}

# This works, inc is visible
var x: Slot
inc x
echo "x: ", x.uint64

# This work after https://github.com/nim-lang/Nim/pull/12080
for y in Slot(0) ..< Slot(10):
  echo "y: ", y.uint64

Spread it on 3 files and hide it in a generic proc

# dforloop1.nim
type
  Slot* = distinct uint64

proc inc*(x: var Slot, y = 1){.borrow.}
proc `..`*(a, b: Slot): Slice[Slot]{.borrow.}
proc `<`*(a, b: Slot): bool{.borrow.}

var x: Slot
inc x
echo "x: ", x.uint64
# dforloop2.nim
import dforloop1

proc foo*[T](a: T) =
  mixin inc, `..`, `<`
  for y in Slot(0) ..< Slot(10):
    echo "y: ", y.uint64
# dforloop3.nim
import dforloop2

foo(10)

Compile dforloop3

Error: type mismatch: got <Slot, Slot>
but expected one of: 
proc `<`(x, y: pointer): bool
  first type mismatch at position: 1
  required type for x: pointer
  but expression 'i' is of type: Slot
proc `<`[Enum: enum](x, y: Enum): bool
  first type mismatch at position: 1
  required type for x: Enum: enum
  but expression 'i' is of type: Slot
...
...
...

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions