codex-storage / questionable

Elegant optional types for Nim
Other
114 stars 5 forks source link

Option binding in generic not working even with mixin #7

Closed TheSimpleZ closed 3 years ago

TheSimpleZ commented 3 years ago

I found a weird quirk.

This code:

import questionable

proc printVal(val: int) =
  echo val

proc doSomething*[T](unused: T) =
  if x =? some(0):
    mixin x
    x.printVal()

doSomething(1)

Gives:

Error: undeclared identifier: 'x'

However, this works:

import questionable

proc printVal(val: int) =
  echo val

proc doSomething*[T](unused: T) =
  if x =? some(0):
    mixin x
    printVal x # Use different call syntax

doSomething(1)

Although, trying to access an object property causes the same issue again

import questionable

type o = object
  a: int

proc printVal(val: int) =
  echo val

proc doSomething*[T](unused: T) =
  if x =? some(o(a: 1)):
    mixin x
    printVal x.a # undeclared identifier: 'x'

doSomething(1)

According to the readme, mixin should make x accessible in generics.

Compiler version: Nim Compiler Version 1.4.6 [Windows: amd64]

Questionable version: questionable@0.8.0

markspanbroek commented 3 years ago

Thanks for taking the time to report these issues, I really appreciate it!

There are more cases where the =? operator doesn’t work very well with generics. The problem lies in the fact that the Nim compiler will do a semantic analysis before it evaluates the =? macro. The mixin statement sometimes helps, but often doesn’t.

I’m working on a solution, but it’s not finished yet and will likely involve a change in the syntax of option binding.

TheSimpleZ commented 3 years ago

Alright! Thanks for the quick responses. I guess I'll have to wait with using this package in generics until then 😄

markspanbroek commented 3 years ago

That shouldn’t take too long, this bug is bothering me 😄

markspanbroek commented 3 years ago

Fixed in 270003831660291f7da2d10ca64e7fce7363b780. The mixin statement is also no longer necessary. Please update to version 0.9.0 to get the fix.