News for hackers. Stuff that matters.
Re:Flattening ASTs (and Other Compiler Data Structures) by francasso on Sunday July 02, 2023 @05:12AM (#36559731)
This reminds me of a GDC talk where rust was praised because it forces you to either go mad because of the borrow checker or structure code using an entity component system. I find it funny that the value of the borrow checker in all these real world scenarios with complicated lifetimes is to find a way to avoid it entirely by putting stuff in arrays and reference them by their index.
Re:Flattening ASTs (and Other Compiler Data Structures) by PartiallyTyped on Sunday July 02, 2023 @05:21AM (#36559776)
You could say that it forces you to define long living entities that own memory and lend it to short-lived objects.

In the process you avoid use-after-free, double-free, and accessing unallocated memory because the borrowers always live shorter lives than the owners, and can only access borrowed and thus allocated memory that is deallocated once the owner dies, and there is nobody else who can use it or free it once more.

Re:Flattening ASTs (and Other Compiler Data Structures) by eyelidlessness on Sunday July 02, 2023 @05:42AM (#36559901)
It’s almost as if immutability writ large is vindicated, but with a whole lot of complicated rules to let mutation infect everything everywhere even if you’ll never use it. At least that was my takeaway trying to learn Rust.
Re:Flattening ASTs (and Other Compiler Data Structures) by Flow on Sunday July 02, 2023 @09:13AM (#36561179)
Do you think a purely functional language without GC would be much simpler than Rust and Rust's borrow checker? I don't think the mutation part of Rust is what makes it complicated.
Re:Flattening ASTs (and Other Compiler Data Structures) by eyelidlessness on Sunday July 02, 2023 @09:06PM (#36567523)
It’s very possible there’s something I’m missing, but my instinct is: yes, it very probably would. If data can be presumed immutable, a whole lot of ownership rules could be relaxed to scope and cycle counts which could be verified at compile time with no runtime penalty. The whole premise that data needs to be borrowed is explicitly to guard against conflicting views of shared state. Such conflicts can only arise by mutability of shared state. Rust’s solution to that is to limit mutability to only one part of a procedure at a given time. If nothing can mutate state at any point in a program’s lifecycle, that tradeoff can be expanded to basically whatever facilities the hardware/compile target affords.
Re:Flattening ASTs (and Other Compiler Data Structures) by c_crank on Sunday July 02, 2023 @10:37AM (#36561869)
Ada has better tools for the task if mutability is allowed.
Re:Flattening ASTs (and Other Compiler Data Structures) by verdagon on Sunday July 02, 2023 @06:35AM (#36560152)
Ironically, we could say that we're losing the true ownership relationships between the objects, and we're making medium-term memory leaks more likely; drop() can free a Box pointing to a child, but can't free an index. In other words, we lose the guarantee that an element is released for reuse.

AFAICT, a language would need something like higher RAII [0] or linear types [1] for that. I'd love to see Rust adopt these features too one day, though it may be difficult to do backwards compatibly.

[0] https://verdagon.dev/blog/higher-raii-7drl

[1] https://austral-lang.org/linear-types

Re:Flattening ASTs (and Other Compiler Data Structures) by PartiallyTyped on Sunday July 02, 2023 @08:56AM (#36561052)
Re linear types, Rust actually has an affine typesystem, and the compiler complains when you move a variable and try to access it, so instead you need to provide a reference if you intend to do that multiple times.

A reference is a new object that references an existing memory value. You can not store a reference unless the borrow-checker can prove that the object that stores it has a shorter lifetime than the referenced object.

That is also why you can't just pass that reference around willy-nilly, because the reference is consumed due to affine types.

I may misunderstanding something though so feel free to correct me.

Re:Flattening ASTs (and Other Compiler Data Structures) by jlokier on Sunday July 02, 2023 @06:45AM (#36560210)
> In the process you avoid use-after-free, double-free, and accessing unallocated memory

You don't really avoid those things, though. In the process you end up with index-use-after-index-free, double-index-free, and accessing index-unallocated array entries.

These are the exact same bugs the borrow checker prevents in main memory, just hidden from the borrow checker by adding a layer of abstraction.

These are memory-unsafety bugs. You still get the same wrong answers caused by coding errors. Random junk values and behaviours, when dereferencing use-after-free invalid pointers that point to memory reused for a new object. It's just that pointers are now called indexes, and the borrow checker doesn't check these pointers.

It's like turning the borrow checker off for this set of objects. Those long-lived entities you mentioned act as a mechanism to enable that. That's useful to do, but nobody should be under the impression use-after-free, pointers to the wrong objects and other memory-unsafety bugs don't happen in the array index model.

Re:Flattening ASTs (and Other Compiler Data Structures) by avgcorrection on Sunday July 02, 2023 @06:54AM (#36560239)
> These are memory-unsafety bugs.

It seems that these are memory-unsafety bugs with the caveat that they have nothing to do with the memory allocator. Maybe a sort of sandboxed memory unsafety? I don’t know.

Re:Flattening ASTs (and Other Compiler Data Structures) by kmstout on Sunday July 02, 2023 @10:13AM (#36561666)
> nothing to do with the memory allocator

It's an application-specific memory allocator.

Re:Flattening ASTs (and Other Compiler Data Structures) by avgcorrection on Sunday July 02, 2023 @11:35AM (#36562429)
That’s in effect what I’m saying. You’ve implemented a memory allocator using the “system” one.
Re:Flattening ASTs (and Other Compiler Data Structures) by PartiallyTyped on Sunday July 02, 2023 @08:40AM (#36560930)
That's the specific case of (mis)using an arena, no? Could this be extended to the general model of ownership?
Re:Flattening ASTs (and Other Compiler Data Structures) by skybrian on Sunday July 02, 2023 @11:18AM (#36562239)
Yes, this is true, but sometimes it’s because pointer ownership is a poor fit for the problem. Sometimes dangling references are logically possible and what you want. (There should be a runtime check, though. Generation numbers can help.)

A compiler can only prevent bad things from happening within a system, typically just one process. The world around it doesn’t work that way. A system is often a cache, not an owner, and caches go out of date because the world changed without notice. You want to update on what notices you get that the world changed. You can’t prevent inconsistency, only detect it and react by updating or removing outdated information.

This probably isn’t relevant within a batch compiler, but it would be for a language service in an IDE.

Games often simulate worlds where references shouldn’t own things. It would be a weird form of power to remotely prevent something from getting destroyed because you remember it. Even though both objects are within the same process, they’re modeled as independent systems where pointer ownership doesn’t happen.

Re:Flattening ASTs (and Other Compiler Data Structures) by chlorion on Sunday July 02, 2023 @10:43PM (#36568105)
With something like the slotmap, you store a generation counter, so you can't accidentally use something that has been freed and recreated.

It also checks that the slot you are trying to get is occupied, and if it's not it won't let you access it. It actually is forced to check that the slot is occupied because the slot is an enum with vacant and occupied variants, and the vacant variant doesn't have a value to get in the first place. In rust you can't read a data out of an enum without checking the variant first.

With these two restrictions, you can't use stale keys, you can't UAF, and you can't read junk data at all, it's enforced by the type system and the runtime checks.

You can still have keys that are invalid, but the slotmap's "get" method returns an option type, and invalid keys cause it to return "None".

So in practice, you will end up panicking if your keys become invalid (the index operator panics when the return value is "None"), or you will explicitly handle the "None" case and do whatever you want to do.

All of this only applies to this specific data structure though, and the checks do have some performance cost.

Re:Flattening ASTs (and Other Compiler Data Structures) by dist1ll on Sunday July 02, 2023 @06:56AM (#36560252)
Correct. Rust lifetimes become less powerful in certain niches of high-performance programming where you're avoiding the heap or don't have one in the first place. Games, databases, embedded, HPC-style batch workloads, and even compilers.

Of course you still have restrictions on aliasing, so you're not going to get data races. But you'll still get bugs that are essentially equivalent to ones you'd get with raw pointers.

Re:Flattening ASTs (and Other Compiler Data Structures) by pornel on Sunday July 02, 2023 @08:31AM (#36560857)
Note that you still have implicit/elided lifetimes for basically every function argument and every local variable. They’re everywhere, even if you’re not typing 'a.
Re:Flattening ASTs (and Other Compiler Data Structures) by noelwelsh on Sunday July 02, 2023 @07:07AM (#36560306)
Using an entity component system felt like writing very fancy spaghetti code in my limited experience with the Bevy game engine in Rust. No longer having direct references between objects means the type system isn't nearly as useful and I found it very hard to reason about the code. I can believe it becomes useful in very large systems but it was just a hinderance in the small program I was writing.
Re:Flattening ASTs (and Other Compiler Data Structures) by logicchains on Sunday July 02, 2023 @10:12AM (#36561664)
You can use phantom-typed index types (a wrapper type per container) to recover type safety. Or at least you can when using an ECS in C++; I'm not sure how easy it is to write the wrapper types generically in Rust.
Re:Flattening ASTs (and Other Compiler Data Structures) by pornel on Sunday July 02, 2023 @04:58PM (#36565666)
You can have typed indices (https://lib.rs/crates/typed-index-collections), but unless you force the collection to be a singleton, there's no way to prevent mixing of indices between different instances (clones) of the same collection type.
Re:Flattening ASTs (and Other Compiler Data Structures) by syntheweave on Sunday July 02, 2023 @06:20PM (#36566406)
A lot of the mangling produced by ECS is an outcome of representing dynamic behaviors through static optimizations.

If you have a dynamic type that you can attach arbitrary new fields to, then, capability-wise, you have exactly what's needed to make game entities: to do a lookup by entity type, just traverse the list of all entities looking for a magic pattern in the data. To look up a specific one, assign each one a unique ID and search by ID.

The problem is that game developers get anxious about this kind of lackadaisical structure(for good reason, if there's any aim at serious performance) and want to put more things in their own index, and allocate things with a more compact representation and less fragmentation.

And the alternatives are...god object with every possible behavior crammed into an oversized record type, and ECS bookkeeping, in its various flavors, some more compilation-heavy and others more reflective with more runtime editing functionality.

But regardless of what approach you take, every time you introduce dynamism into your entities and enable more flexibility in asset assignment, you convert more of your bugs into data bugs. There are a huge number of bugs in games that are configuration problems with the entity and not a flow control or algorithms issue.

Re:Flattening ASTs (and Other Compiler Data Structures) by bregma on Sunday July 02, 2023 @07:10AM (#36560332)
Pointers are just indexes into memory space. Seems to me that if Rust is trying to solve a general programming problem the borrow checker needs to handle all indexes, not just those specialized for memory space.
Re:Flattening ASTs (and Other Compiler Data Structures) by dist1ll on Sunday July 02, 2023 @07:43AM (#36560503)
I feel that for this to be really viable, Rust would have to allow references that consume less memory (like 8-bit or 16-bit pointers).
Re:Flattening ASTs (and Other Compiler Data Structures) by chubot on Sunday July 02, 2023 @11:36AM (#36562435)
Yes totally, I keep seeing people mention these arena / flattened tree and graph structures, without mentioning memory safety.

And also weird claims that arenas solve memory safety problems in C, when it's equally likely (depending on the program) that they CAUSE dangling pointers, use-after-free, etc.

The same issue comes up in slightly different ways in both C/C++ and Rust

---

My comment on this post from 2 months ago:

https://old.reddit.com/r/ProgrammingLanguages/comments/1350d...

Summary: the upsides are very real, but we should mention the downsides too:

- Arenas punt on memory safety; Ownership can be nontrivial (a bunch of examples)

- Mutation, and appending to list/vectors are complications

- Pointer representations are more friendly to debuggers

My wiki page is linked at the bottom of this article (which I appreciate because it actually has code and measurements!)

https://github.com/oilshell/oil/wiki/Compact-AST-Representat...

Re:Flattening ASTs (and Other Compiler Data Structures) by kazinator on Sunday July 02, 2023 @12:36PM (#36563078)
* * *
Re:Flattening ASTs (and Other Compiler Data Structures) by chubot on Monday July 03, 2023 @12:28PM (#36575259)
Yes, I mentioned the same issue a few days ago -- arenas break ASAN/Valgrind, and those are the BEST tools to ensure memory safety:

https://news.ycombinator.com/item?id=36427264

In response to a claim about arena-based allocators and memory safety

Re:Flattening ASTs (and Other Compiler Data Structures) by kazinator on Monday July 03, 2023 @01:19PM (#36576063)
Maybe Valgrind has an API now to attach a backtrace to a custom allocation out of an arena. I haven't touched that in years. I did the initial Valgrind integration in 2009 and just maintained it with changes to the gc.

I see this in the current manual:

VALGRIND_MALLOCLIKE_BLOCK:

If your program manages its own memory instead of using the standard malloc / new / new[], tools that track information about heap blocks will not do nearly as good a job. For example, Memcheck won't detect nearly as many errors, and the error messages won't be as informative. To improve this situation, use this macro just after your custom allocator allocates some new memory. See the comments in valgrind.h for information on how to use it.

I can't remember whether I saw this before; i.e. is this something existing that had not been useful, or is it something new. I will look into it.

It does look like it should be attacking the same problem: that the errors aren't detected well or nearly as informative in blocks carved out of larger block by custom allocators.

Re:Flattening ASTs (and Other Compiler Data Structures) by kazinator on Tuesday July 04, 2023 @07:37PM (#36593864)
* * *