145 points · by def- · 11y ago · 66 comments
To me it looks like it makes the unsafety of c more accessible because of better tooling and nicer syntax. Looking at e.g. [1] there are still pointers, null-pointers etc, just like in c. So now you have a language that looks superficially simple but is actually very dangerous. Compare this to e.g. rust which was the most painful thing I learned recently but I also know that it brings something fundamentally new to the table.
Anyway, there's a lot I don't understand about Nim and I'd be happy to see evidence to the contrary.
[1] http://nim-lang.org/0.11.0/tut1.html#advanced-types-referenc...
Nim also has references (ref keyword) which are traced by the GC and therefore safe.
It seems to me the design was chosen more as a way to ensure memory lifetime could be better predicted by the compiler rather than any strong argument for safety.. but then, I'm not well read on the subject, and It's very likely there's good safety arguments for it I'm not aware of.. either way, in my experience nil-deref errors are rarely a painful thing. They happen often, but are also fixed quickly.
It's not that null is not useful. It's that most pointers can never be null, so nullability is the wrong default. And it is useful for the compiler to force you to handle the case in which pointers are null.
> Perhaps by forcing you to be extremely explicit (and enforcing `match` always handles all conditions) you gain some arguable safety, but at what cost?
There's basically no downside to having no null pointers. With constructs like Option::map the code is usually even less verbose than the equivalent code with null.
> It's certainly not easier to use and reason about, IMO.
You never have to worry about your program failing whenever you type "." or "∗". With null, the semantics of the language are that an exception can be thrown [1] whenever those constructs are invoked. That's pretty much objectively easier to reason about.
> It seems to me the design was chosen more as a way to ensure memory lifetime could be better predicted by the compiler rather than any strong argument for safety
Huh? Lifetimes are totally independent. We could have had null pointers with the lifetime system (and there were languages like Cyclone that had both). The system exists precisely because of safety.
We also get some really nice optimizations out of it that are impossible to get in C. All pointers in Rust are dereferenceable per the LLVM definition, which opens up some really neat optimizations like loop invariant code motion on loads.
> in my experience nil-deref errors are rarely a painful thing. They happen often, but are also fixed quickly.
Not in my experience. They show up in production all the time.
[1]: Or you could do what Nim does, and make dereferencing null undefined behavior instead of guaranteeing that an exception is thrown, but that strikes me as worse than what Java does.
Well I agree that it's very useful (and we have that in Nim), but..
> With constructs like Option::map the code is usually even less verbose than the equivalent code with null.
I'm still not convinced of this part. It certainly hasn't been the case with the, admittedly small amount of, Rust code I've seen. However, I'll look for more comparisons in the future (or offer Nim comparisons to Rust snippets anyone posts). Point is, nil is still a useful and commonly used tool. So the argument for verbosity and conveniences is relevant, IMO.
> With null, the semantics of the language are that an exception can be thrown [1] whenever those constructs are invoked. That's pretty much objectively easier to reason about.
That completely depends on how often you want to use nil refs, and how easy they are to use. Like I said in another response, I agree Rust's design may be better for some domains, but I certainly wouldn't call it "objectively" easier to reason about in a general sense.
> Huh? Lifetimes are totally independent.
Well like my post implied, I was only guessing as to the design. And it's interesting to hear that it takes advantages of special compiler optimizations. That said, I still don't see how it's completely decoupled from the life-time system.. you're saying that if I have a Option<> reference to a mutable list in Rust, the compiler can determine weather or not the list is 'frozen' based on the runtime state of that reference?
> Or you could do what Nim does, and make dereferencing null undefined behavior.
I didn't think derefing nil was undefined behavior. I thought only dereferencing a pointer which points to once-valid-but-now-free memory was undefined behavior, and that situation is covered by GCed refs. Can you explain this a bit?
EDIT:
> Not in my experience. They show up in production all the time.
I did say 'rarely', and I drew a comparison to bounds-check crashes, which surely also show up in production.
Static analysis of these lifetimes allow a whole class of errors to be avoided (dangling pointers, double-free, iterator invalidation, etc).
Rust's Options are handy for a lot of stuff (async APIs, concurrent code that may/may not succeed, error codes, etc). But they are just icing really, not really the main thrust of Rust's memory model.
> It's certainly not easier to use and reason about, IMO.
To offer a counter-viewpoint, I find that Option<> (and Result<>) are very easy to reason about. They tell you exactly what to expect from a function, and you don't have to guess if you need to catch exceptions or let them throw higher up. Everything is explicit, the only surprises are panics which are cataclysmic anyhow.
> And it seems just as likely you'll end up crashing your program due to a bounds-check error (which may happen more often since Rust encourages indexing over references due to this very design.. at least, so I've read).
If you use iterators in Rust, you never need to worry about out of bounds errors. In fact they skip range checking altogether, since you are guaranteed that the value you are iterating on won't change under your feet (no iterator invalidation, etc), which generates more efficient code[1]
If you use explicit indexing, then yes, you can have a runtime panic if you go OOB. But that's the nature of explicit indexing. It also has to include those safety checks, so will be slower code.
Just for clarity, we have this in Nim too, eg:
type
Foo = ref object
Bar = object
val: Foo not nil
let
f = Bar() # Error, 'val' must be set
proc foobar(f: Foo not nil): Foo not nil =
return nil # Error, can't return nil
foobar(nil) # Error, can't pass nil
> At best this dangling pointer will look at garbage and cause a crash or undefined behavior. At worst, it will look at other, actively-used memory and cause a security vulnerability.In C/C++, yes, but this isn't so applicable to Nim where we have GCed references and 'not nil' constraints.
> If you use iterators in Rust, you never need to worry about out of bounds errors
Well I was not talking about iterating through a list, but rather maintaining arbitrary indexes to a mutable list. Eg, a Sprite which contains a index to a Texture array. In that scenario it's just as easy to miscalculate and crash your program via a bounds-checking error as it is to crash by nil-deref.
> To offer a counter-viewpoint, I find that Option<> (and Result<>) are very easy to reason about..
It's good that Rust works for you, truly. And like I said in another post, I agree Rust's design here may be better for some domains. However, Nim's design still feels more elegant and straight-forward to me. Luckily, we both get a powerful language that suits us, regardless of which one we prefer :)
Yes. So? A lot of things are useful modelling tools, but that doesn't mean you necessarily want to include them in every reference-like type. A tuple of two things is useful modelling tool; should that then be infused into every type? A "either value or error" is a useful type; should that be infused into every type?
No? Then what makes "Either something or nothing" so special?
There are a number of ways to approach this topic, so I'll just give you one: in languages with more advanced static type systems, you try to encode as much semantic information as possible in the type. As you've said, the idea of null can be useful, so it deserves a place in the type system. You want to separate things that may be null from things that should never be null. This is because not-null is by far the common case. Allowing everything to be nullable by default optimizes for the lesser-used semantic, which is where errors with null come in: you assume that something isn't null, when it actually is.
There are things I don't like about the language (eg. case-insensitivity), but overall if I had to choose a newish language for a new task, I'd choose Nim over Rust and Go. (However, if you threw D into the equation I'd probably go with D simply because I feel it's slightly more mature).
Incidentally, the way I tried to teach myself Nim (and to see if the language was usable for creating small Windows apps) was to write a WinApi program. It took about the same or less effort as what it would have taken me in C/C++, but it just felt much safer and more pleasant to work with.
I felt a bit overwhelmed with the whole wrapping thing.
hWndMain = CreateWindowEx(
WS_EX_TOPMOST, # Optional window styles.
CLASS_NAME, # Window class
WINDOWNAME, # Window text
windowStyles, # Window style
# Size and position
centerX, centerY,
APP_WIDTH, APP_HEIGHT,
cast[HWND](nil), # Parent window
cast[HMENU](nil), # Menu
hInstance, # Instance handle
cast[LPVOID](nil) # Additional application data
);* Nim/GCC gains 2 bytes by smartly reusing the previously set AX register's value to set DI where Rust/Clang uses an immediate
* Nim can't express that stuff after the EXIT syscall is unreachable and wastes a byte on a RETQ.
I am sure many portable devices would benefit if applications were trimmed down.
Frameworks tend to be heavy in size because it needs to accommodate various tasks as well as many platforms it can support. It's not easy to make them modular, so you can pick what you want and leave the rest out to shrink down the size.
For customers, would you rather wait a few days to get a certain feature that works out good enough in a few days or would you rather wait a few months for a feature that works great?
The competition is intense, wait too long to ship a feature and you lose to competitors that managed to get it out sooner than you. So, it's tough to balance each feature and tough to say no to customers, so that you could stay focused and lean.
[1] http://www.muppetlabs.com/~breadbox/software/tiny/teensy.htm...
The actual active code is essentially some text and an interrupt. That much, at least, should be language independent. Are modern compilers incapable of discarding unreferenced code, or am I missing something?
Also there is some overhead every Nim program has. But if you get to bigger programs you'll see that Nim's binary size is just fine, for example a NES emulator is just 136 KB: http://hookrace.net/blog/porting-nes-go-nim/#comparison-of-g...
Nice achievement! The article is quite the journey through various build parameters, switching gcc for clang and glibc for musl along the way. In the end, the secret sauce is syscalls and custom linking, though (as always with this kind of thing).
I think it's a bit of a shame because that's basically the #1 differentiator with languages like Go or Java as far as I'm concerned.
But beyond that it's true that the language itself has a lot of potential for embedded applications. The runtime can be made almost as tiny as C's and with libcore you get a much nicer and safer "bare metal" environment than what you'd get in C. And thanks to LLVM you can easily target a whole bunch of architectures.
Yup, both of these things are true. This is what I meant by increased support: we have a long way to go to make it as nice to use, and on a stable release of Rust. But the fundamentals are in place.
Haha!
What I found was most impressive was the small binary even without the tricks.
Did I miss where he optimized for speed?