timotheecour / Nim

Nim is a compiled, garbage-collected systems programming language with a design that focuses on efficiency, expressiveness, and elegance (in that order of priority).
http://nim-lang.org/
Other
2 stars 0 forks source link

`Option[T]` should not special case ptr-like types, so that some(nil).isSome is true #758

Open timotheecour opened 3 years ago

timotheecour commented 3 years ago

(placeholder to track this; but this should be explained more properly)

this prevents use cases where you'd use: proc get(t: Table[K,V], key: K): Option[V] if V is a ptr-like type (ref, ptr, pointer, etc) as it creates ambiguities as you can't distinguish between absence of value and a value that's nil, eg:

var t: Table[string, ref int]
echo t.get("foo").isSome # false
t["foo"] = nil
echo t.get("foo").isSome # false

refs https://github.com/nim-lang/Nim/pull/18253#issuecomment-860184519

try it: f.isSome is actually false. That's the whole point I've been making regarding this "optimization" mis-feature.

Seems like a bug with options to me

refs https://github.com/nim-lang/Nim/pull/18253#issue-668989097

note 1

this affects other APIs too, eg wrapnils, where you can't distinguish whether an intermediate nil was found vs when no intermediate nil was found but the final value is nil

note 2

instead we should remove this special case and add these APIs: (TODO: this was explained in https://github.com/nim-lang/Nim/pull/18253#issue-668989097; need to explain it here)

# in std/options:
proc toOption[T](a: ptr T): Options[T] 
template MaybeOption*(T): untyped =
  when T is ptr|pointer|ref: T
  else: Option[T]
juancarlospaco commented 3 years ago

Not much API of stdlib returns Option[ptr T] nor Option[ref T] anyways... 🤷