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.41k stars 1.47k forks source link

Method dispatch doesn't respect privacy #23912

Open Wh1teDuke opened 1 month ago

Wh1teDuke commented 1 month ago

Code

==> Foo.nim <==
type Foo* = ref object of RootObj
type Bar* = ref object of Foo
method test*(this: Foo) = echo "Foo"
==> BarA.nim <==
import Foo
method test(this: Bar) = echo "Bar A"
==> BarB.nim <==
import Foo
method test(this: Bar) = echo "Bar B"
==> Main.nim <==
import Foo, BarA, BarB
test(Bar())

Expected Foo

Got Bar B

I'm more concerned about the fact that it resolves to BarB.test and I think the compiler should complain.


>nim -v
Nim Compiler Version 2.1.9 [Linux: amd64]
Compiled at 2024-07-31
Copyright (c) 2006-2024 by Andreas Rumpf

git hash: cb156648d69fd0c21ee5d041a98ddc69294eaa96
active boot switches: -d:release
litlighilit commented 1 month ago

I think its doing so is fine.

If using C++/java's class[^cls] as reference, maybe we shall enforce subclass's method must be also exported if its parent does.

However, such a change may break some existing code, but such a break that turns potential pitfalls to compile-error shall be called as improvement.

[^cls]: As in Nim there is just no concept like public/private in C++ or Java. There is just module-level isolation in Nim, which in turn C++ doesn't have (at least before C++23).