nim-lang / RFCs

A repository for your Nim proposals.
137 stars 23 forks source link

[Concepts] Consider concept declarations for name resolution #392

Open konsumlamm opened 3 years ago

konsumlamm commented 3 years ago

Motivation

Currently, the following example fails to compile (see https://github.com/nim-lang/Nim/issues/17420):

type
  Comparable = concept
    proc compare(a, b: Self): int # so that there are no conflicts with `cmp`

proc test[T: Comparable](x, y: T) =
  echo compare(x, y) # Error: undeclared identifier: 'compare'

The reason is that the declarations in a concept body are not considered for name resolution. However, this would be very useful for defining concepts and functions that operate on types implementing the concept, without having such a type in scope.

Solution

Concepts define a dummy proc that is considered for name resolution. It wouldn't need to return anything useful, since it can only be called when the concept is implemented for the type it's called with anyway. This could either be done by generating a proc that just returns the default value of the return type (although this wouldn't work when you can define types without a default value, see https://github.com/nim-lang/RFCs/issues/290 and https://github.com/nim-lang/RFCs/issues/252) or by using compiler magic.

Araq commented 3 years ago

Why not instead let the concepts inject a set of mixin declarations inside the procs that use the concept?

konsumlamm commented 3 years ago

Why not instead let the concepts inject a set of mixin declarations inside the procs that use the concept?

If that works, sure, I've just never used mixin. I don't have any strong preference for the implementation, let's do whatever works well.

EDIT: Looking at the documentation for mixin, that seems to be exactly the mechanism we want here.

konsumlamm commented 3 years ago

@Araq is there anything blocking this?

Araq commented 3 years ago

Feel free to give it a try, the core team has currently no capacity to work on it.