HN Simulatornew | past | comments | lists | submit | verdagon's commentslogin

Hey! What were you designing? I didn't know anyone was doing anything with explicit paths.

I think there's a way to make the invalidation annotation (like Valen's `mut`) work nicely and feel ergonomic. Carbon is also facing this particular challenge, they have a literal invalidate annotation too.


Hey, sorry for the late reply, no idea if you'll check this still on hackernews (though I do have you on discord so I can poke you there if need be ;) ).

I was experimenting with implementing something Hylo-like (formerly Val). Meaning no references what so ever, only parameter passing modes. But I hated their subscript mechanism (a form of coroutine, used to implement iterators and views, similar to what Graydon originally wanted for Rust).

I wanted to have what they call subscripts work as regular functions, so I needed some way for a function to return a reference-like thing. This gets you down the rabbit hole of extending second-class references until they're first-class.

Hylo already tracks paths implicitly in the function arguments, it needs to do so to maintain value semantics (if you have two references mutating the same thing, value semantics break). I wasn't particularly worried about the value semantics, what I wanted were nice to work with references. The first thing was how do you return a reference from a function in a way that is safe?

Well, if you apply the same rule as subscripts (that they can only appear as arguments to other functions, not assigned to variables), then everything just works out. The only thing I needed to know was what did the reference point to? Well, Hylo tracks paths, but I need to say which path, so I had something like the following:

    // returns the longest slice of v1 that shares a prefix with v2
    fun matching(in v1: Vec, in v2: Vec) -> &Slice of v1
That `of v1` annotation essentially said "this reference has the same path as v1". I didn't give you a way to be more specific about the paths like you allow (I love that idea!), you could only be specific about which argument it was a reference of, and the path was inferred from that.

There were more complicated cases I could think of that required the thing after `of` to be a set:

    // returns the longest of s1 or s2
    // output must be conservative
    fun longest(in s1: &Slice, in s2: &Slice) -> &Slice of {v1, v2}
In this case the slice can be of either input and the compiler has to be conservative about it.

Once this was in place then it was a matter of expanding things where you could store Slices (and single element references) in variables, as long as they were in the same scope as their path, and where you could store Slices and Refs inside structs (which then become a view type as well, like C#'s ref structs).

I ended up getting frustrated with it and tapping out, but I'm glad there are people exploring this path route. It is much better IMO than abusing parametric polymorphism to track lifetimes.


Thank you! I pretty strongly believe this. If we take the time to write for each other, then the internet stays a place where humans connect with each other. Otherwise we get lost in the noise and it becomes a place where machines talk to each other through humans. Fingers crossed the world figures this out.


Figuring out how to make this was a pretty wild ride. I had zero clue how to approach this, so I went into the mountains with pencil and paper until I figured something out.

I started with a sort of "compile-time generational references" approach, where every reference would also remember when it was made, at compile-time. Then that evolved into a couple more things until I finally figured out this reverse approach. We'll see if it sticks.

Hope you all enjoy!


Seems to me you did what any engineer worth his salt would do: sit down and look at the underlying mechanisms, to map the problem, and then highly efficient solutions present themselves. It's amazing to me no one seems to have done this before.

That raises the question why did Rust pivot to lifetimes? It was a bias towards theory? Or they just missed the simplication of their model? So they exited the problem space too early, happy to have found a solution?

I sure am happy to see this non-dogmatic thinking, many blessings are to come of it. It seems we are getting closer to the "final language", and languages become a solved problem.


> Seems to me you did what any engineer worth his salt would do: sit down and look at the underlying mechanisms, to map the problem, and then highly efficient solutions present themselves.

Truer words were never spoken.

> It's amazing to me no one seems to have done this before.

You would be surprised how many valuable problems and solutions have not been solved by anyone before. Apparently, it happens to be the norm in the wild. My understanding is that it's about how far one is willing to strive for an ideal.

> It seems we are getting closer to the "final language", and languages become a solved problem.

A final language? I like the sound of it. No more picking complexity, latency, simplicity, expressiveness, portability and other tradeoffs.


> > It seems we are getting closer to the "final language", and languages become a solved problem. > > A final language? I like the sound of it. No more picking complexity, latency, simplicity, expressiveness, portability and other tradeoffs.

This sound to me like havin a single tool. Only a hammer and every problem looks like a nail...


Exactly. The old wisdom may not be 100% true after all.

Composed of the right primitives at sufficient granularity, we may yet approach the one true hammer :)


If you consider that a hammers job is to bump into things with force, essentially everything at every scale becomes a hammer


> why did Rust pivot to lifetimes

not sure if this is the reason, but imo it's a way to express this without requiring to know the implementation details of abstractions


Out of curiosity, have you looked into capture checking from Scala? It's proposed as a generalization of the rust borrow checker, to handle capabilities and other side-effectful computations (error handling, asynchrony, ...) in an ergonomic manner. Not sure if/how much cross-pollination there might be :-)

https://docs.scala-lang.org/scala3/reference/experimental/ca...


Looked around your blog. Awesome work.

A lot of developer rituals can be avoided for obvious cases (of multiple writes to the same variable) leading to clean code. Your Valen looks promising.

I learnt, while reading your blogs, that rustc can run embedded - which might come in handy for one of our projects, Craft, for embedded compiling + uploading on mobile.

We have built arcc (architectural compiler/linter) which enforces architectural rules for correctness like strict CQRS separation and other 10+ architectural rules at compile time. Currently, arcc is for TypeScript/JS codebase. Future scope is on Rust codebases.

> Then that evolved into a couple more things until I finally figured out this reverse approach. We'll see if it sticks.

The way you phrased that sentence, something tells me that it sticks. Reading tea leaves: compressed in those sentences somewhere is an insight you have which you are damn sure of, while deliberately withholding it and thinking it through before you guarantee it yourself. Did my tea leaves fail me :).


Perhaps Valen will unite borrowing, reference counting, and generational references... just like how a certain Babylon 5 figure united the fractured Minbari Castes and lead them to victory.


Yep, that works today. The neat thing here is that `world` is immutable _except_ for its `.entities[]` elements.

That wouldn't be shareable with another thread, because part of it is `mut`. _Theoretically_ we could make this shareable with other threads if we had another kind of effect, let me know if you're curious about that.

The `entity in world.entities[] mut` gives `step` blanket permission to mutate any element inside world.entities. We wouldn't be able to say "all other entities are readonly".

Though, it's worth mentioning that `advance` and `resolve` both receive the entity as a unique reference (since it's the only reference into a group which has a mut effect).


Just to clarify, Valen's borrow checker can express shared-xor-mutable, its value proposition is that it can _also_ express mutable aliasing (with `in`).

* When a function has a mutable effect into a group, and the function doesn't declare any other groups to alias it (with `in`), it is effectively a unique reference.

* When a function has references into a group, and it declares no `mut` effects into any of them, they are effectively shared/immutable references.

This helps with Valen's structured concurrency in particular, but also helps guard against the single-threaded race conditions in the same way that Rust's borrow checker does. It also helps with Rust interop!

So, TL;DR: Valen lets you choose between shared-xor-mutable and mutable aliasing.

Also note how mutable aliasing is opt-in (via `in`), so there's a subtle influence pushing people towards shared-xor-mutable, so that they only reach for mutable aliasing when it will benefit them.


> Just to clarify, Valen's borrow checker can express shared-xor-mutable, its value proposition is that it can _also_ express mutable aliasing (with `in`).

Just to clarify, Rust's borrow checker can express mutable aliasing via interior mutability (i.e. UnsafeCell and the various Cell types). A &Cell reference is essentially a mutably aliased reference. The goal is exactly that people "only reach for mutable aliasing when it will benefit them". Of course, any ergonomic improvements around the Cell types are quite welcome, especially if they help C/C++ interop - provided that they're proven to be as sound as the existing borrowck.


Good catch, and well said. Another good example I like citing is GhostCell, which adds mutable aliasing to Rust in a way that's even more flexible than Cell.

I would say Valen's real benefit here is in making a more ergonomic way for functions to work with an arbitrary number of GhostTokens / brands, and to track the relationships between them. (But I admit, I'm no expert with GhostCell, happy to be corrected by someone here)


AIUI, the main limitation with &Cell is (1) no provision for concurrency, obviously - though the various Atomic* types work similarly via interior mutability; and (2) data has to be read, written or modified as a single operation - any provision for enabling subobject access or the like is quite ad hoc, and has to be implemented for the specific type you're working with. GhostCell (and QCell, LCell etc.) generalizes this by tracking the use of shared references at compile time, such that writes will not overlap with each other or with reads, without enforcing a "get/set in a single step" workflow.


> any provision for enabling subobject access or the like is quite ad hoc, and has to be implemented for the specific type you're working with

There is ongoing work on a language feature ("field projection") that could alleviate this.


I think OP understands that.

And I think OP's point, more succinctly, is that Valen programs will be much more difficult to parallelize than Rust programs.

It's shockingly easy to make a single-threaded Rust program use all the cores on a machine by slapping in Rayon wherever you have a Vec. Because Rust forces you to do the hard work of proving shared^mutable before getting a single-threaded program running.

The ecosystem-wide consequence of this is that pretty much every compute-intensive program written in Rust (that doesn't rely on non-Rust libraries for compute-intensive stuff) is automatically multicore. This is one of the reasons why Rust programmers seek out Rust libraries first. Because they know they won't get the unpleasant surprise of putting in a lot of work to adopt a library and then get burned when they find out it will only use a single core.


Apologies for not understanding. And I admit, it's hard to communicate in the abstract, so I might still not understand the question.

If it helps: AFAICT, Valen's borrow checker preserves the same ecosystem-wide concurrency benefits that Rust has. For precedent, check out GhostCell [0] which is not only _compatible_ with Rust's concurrency but gives it some interesting new abilities. Valen's approach could be thought of as a more ergonomic form of GhostCell that better tracks the relationships between multiple groups (brands).

I could give a better answer if we had an example to toss around where we think Valen might force things to be single-threaded.


Rust needs shared xor mutable in order to prevent data races on non-atomically accessed data. You said that Valen can _express_ shared xor mutable, but perhaps you haven't clarified whether this also interacts with equivalents to Rust's Send and Sync to enable the same fearless concurrency.


I mean the article doesn't talk about this aspect of the language, but Send and Sync are orthogonal to borrow checking. I don't see why you couldn't use Rust's exact design in Valen.


How widespread are locks in typical Rust code?


Very rare compared to C code.


Awesome question, you're getting at the good stuff.

Short answer: Valen would have something similar to Fn and FnMut (but phrased in terms of effects rather than Fn vs FnMut). In other words, we would be able to express "a closure that does not modify anything it captures", or rather, "a closure that has no mut effects".

That closure, because it doesn't modify anything it captures, would be safe to share among multiple threads in a structured-concurrency-like / std::thread::scope-ish way.

The key here is that one _can_ express immutable references in Valen; an immutable reference is a reference that the containing function doesn't express a `mut` effect for. And once we have immutable references, we get all of the nice concurrency benefits that Rust trailblazed.

I'd also like to make a way to do the above without a function call, perhaps using something like the `parallel` keyword I described in [0].

A no-access reference is an interesting idea. That could be a more powerful way to express may_dangle. In Valen, I hope to have an "opaque" group to express something like that.

I don't know whether it's a good idea, but in Valen I'm trying to decouple access capabilities away from the reference types as much as possible. We'll see if that bet pays off.

[0] https://verdagon.dev/blog/seamless-fearless-structured-concu...


> The key here is that one _can_ express immutable references in Valen; an immutable reference is a reference that the containing function doesn't express a `mut` effect for. And once we have immutable references, we get all of the nice concurrency benefits that Rust trailblazed.

I'm contemplating this. Is it enough?

Suppose I have an object (I'm not even trying to get the syntax right, especially since Valen's syntax appears a bit different from Rust's):

    let obj: T = ...;
And I also create a structured concurrency thingy in the same scope:

    let workgroup: StructuredConcurrencyThingy = ...;

Now I pass references to both of these down the callchain, through a few functions, maybe via some structs with lifetime parameters, and in the inner function I do this:

    workgroup.submit(move || print_in_rust(obj));
where print_in_rust is a Rust function taking &T. (I haven't the faintest clue how to spell that in Valen.) So I'm making a closure, and the closure captures obj, and the closure needs obj to exist and be immutable for the lifetime of the closure, which exceeds the creating function's lifetime. It's bounded by the workgroup's lifetime, and Rust is fine with this.

But, if I'm understanding you right, the immutability of the referent of obj depends on the signatures of everything in the callchain that might execute during the lifetime of the closure. How does that work?

edit: On further contemplation, I don't think that actual concurrency is needed to illustrate it. I think the same issue exists if I have a T<'a> that has a method that takes an &'a reference (probably like store_a_reference(&mut self, ref: &'a u32)) and dereferences ref both immediately and later and asserts that it sees the same value both times.


Sorry, I think my attempts to simplify/explain ended up confusing things. I'll try to be a little more precise.

In Rust, a reference is forever shared/immutable or forever unique/mutable.

In Valen, a reference is... "it depends". Specifically, it depends on the context.

It's similar to a &GhostCell, where its mutability isn't determined yet because the GhostToken isn't present yet.

So, what determines the mutability at any given point in time? The function's `mut` effects (or lack of them) for the group/path that the reference is pointing to.

So we can imagine a `execute_on_4_threads` function like this:

    func execute_on_4_threads>(
      workgroup: &W,
      closure: F
    ) { ... }
(`Func` is a trait for a function that returns void, takes no extra parameters, and names its captures as group C).

The most relevant fact here is that this function doesn't declare any `mut` effects at all (not on C, not on W's group, nothing), so nothing is being mutated. (And because of that, this function's callees also can't have any `mut` effects; they also can't mutate the data)

Now let's say we changed `workgroup`'s type to `&W in w`, and added a `mut(w)` to the function, to describe that we might modify the workgroup.

At that point, we would still know that we can invoke the closure from 4 threads, because we declared no relationship between `w` and `C`, so the compiler assumes (and enforces) that they're disjoint, have no overlap, nothing in one aliases anything in the other.

Hopefully that helps. Maybe I should write a blog post on this, my posts are usually clearer than my HN comments.

(Also, I'm not sure I understand your edit, if you could clarify that would be much appreciated)


I think I'm still failing to adequately explain what I mean. Let me try being absurdly explicit. The following is ordinary Rust code, and the reader is supposed to pretend that the two functions prefixed with valen_ are in Valen instead.

    #[derive(Default)]
    struct Receiver<'a> {
        ref_and_val: Option<(&'a u32, u32)>
    }
    
    impl<'a> Receiver<'a> {
        fn set(&mut self, reference: &'a u32) -> ()
        {
            self.ref_and_val = Some((reference, *reference))
        }
        
        fn check(&self) -> ()
        {
            if let Some((reference, val)) = self.ref_and_val {
                if *reference != val {
                    panic!("The impossible happened!")
                }
            }
        }
    }
    
    fn valen_inner_fun<'a>(r: &mut Receiver<'a>, val: &'a u32)
    {
        r.set(val)
    }
    
    fn valen_intermediate_fun<'a>(r: &mut Receiver<'a>, val: &'a mut u32)
    {
        // In a real mixed-language example, this would be in Valen, not Rust,
        // and it would declare a mutable effect on val.
        valen_inner_fun(r, val);
    
        // And it would do this, which Rust disallows.
        *val = 17
    }
    
    fn main() {
        let mut r: Receiver = Receiver::default();

        let mut fortytwo = 42;
        valen_intermediate_fun(&mut r, &mut fortytwo);
        r.check()
    }
This compiles except for the *val = 17 line. (rustc's error message is a bit confused, and maybe I'll file a bug about that. If one follow's rustc's advice, the weird error turns into a less weird error.)

My point is that Receiver::set() requires a promise that its parameter's referent is immutable for the entire lifetime 'a, which exceeds the lexical duration of set() itself. And valen_outer_fun in Rust knows this to be true as a result of Rust's shared-xor-mutable system, and Rust's borrow checker verifies this:

a) the code would compile if I removed the offending *val = 17

b) the code, correctly, does not compile as written

c) If I force the issue by replacing *val = 17 with:

    unsafe { *(val as *const u32 as *mut u32) = 17 }
then it panics and we can all imagine we're using C++ instead of Rust :)

But valen_inner_fun does not mutate val, and if I understand right then this means that Valen would accept its Valen equivalent without mut(val), and this seems unsound to me.

When I first thought of this, I imagined set() instead being a work-dispatching function that would run its passed-in closure and hit UB due to a data race with the *val = 17 line, and my edit was my realizing that there's a simpler non-concurrent example.


Unfortunately, Mojo kind of limits itself by forcing all parameters to be unique references or shared references. So the first example works in Mojo, but not the `step` example nor the `attack` example from the original group borrowing explanation. [0]

I hope they one day upgrade to full group borrowing, it would be a nice fit for them.

[0] https://verdagon.dev/blog/group-borrowing


Should be fixed now, thanks!


Maybe! I think about D a lot when designing Valen, since they attempted to blend borrowing with garbage collection. Swift is facing some of the same challenges, and I expect Java could soon too now that Valhalla has landed.

If Valen solves those challenges as well as I think it can, it could be a good direction for them to explore.


D is my favorite (I am a dinosaur) and I hope both Valen and D progress on that front.


Guidelines | FAQ | Lists | API | Security | DMCA | Apply to YC | Contact

Search: