nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.39k stars 1.47k forks source link

Disallow inheritance from breaking generic constraints #22064

Open Graveflo opened 1 year ago

Graveflo commented 1 year ago

Summary

Inheriting from an object that has a constraint allows the constraint of the base class to be broken without warning.

type
  SomeThing = distinct object
  BaseClass[T: SomeThing] = object of RootObj
    encap: T
  IEraseConstraint[T] = object of BaseClass[T]

discard IEraseConstraint[int]()

Description

In the following example, either IEraseConstraint[T] = object of BaseClass[T] for it's lack of verbosity or IEraseConstraint[int]() for its breaking of base class constrains, should be a compile time error or warning.

Alternatives

No response

Examples

No response

Backwards Compatibility

No response

Links

No response

metagn commented 1 year ago

Related: #21181

I think the "wildcard" generic parameters are allowed to pass any constraint early on (at the generic declaration) but then the constraint is not checked during instantiation

Graveflo commented 1 year ago

Interesting. Sounds like that might be a fairly straight forward fix. This pattern is very easy to do by mistake and can lead to unintended program states. I think that a warning would go a long way here if nothing else because the constraints can be restated. However, more consistent with the rest of the language and in a design where safety is critical, an error makes the most sense.