rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
98.44k stars 12.73k forks source link

Tracking issue for RFC #1909: Unsized Rvalues (unsized_locals, unsized_fn_params) #48055

Open aturon opened 6 years ago

aturon commented 6 years ago

This is a tracking issue for the RFC "Unsized Rvalues " (rust-lang/rfcs#1909).

Steps:

Blocking bugs for unsized_fn_params:

Related bugs:

Unresolved questions:

Aaron1011 commented 6 years ago

How do we handle truely-unsized DSTs when we get them?

@aturon: Are you referring to extern type?

aturon commented 6 years ago

@Aaron1011 that was copied straight from the RFC. But yes, I presume that's what it's referring to.

ldr709 commented 6 years ago

Why would unsized temporaries ever be necessary? The only way it would make sense to pass them as arguments would be by fat pointer, and I cannot think of a situation that would require the memory to be copied/moved. They cannot be assigned or returned from functions under the RFC. Unsized local variables could also be treated as pointers.

In other words, is there any reason why unsized temporary elision shouldn't be always guaranteed?

F001 commented 6 years ago

Is there any progress on this issue? I'm trying to implement VLA in the compiler. For the AST and HIR part, I added a new enum member for syntax::ast::ExprKind::Repeat and hir::Expr_::ExprRepeat to save the count expression as below:

enum RepeatSyntax { Dyn, None }
syntax::ast::ExprKind::Repeat(P<Expr>, P<Expr>, RepeatSyntax)

enum RepeatExprCount {
  Const(BodyId),
  Dyn(P<Expr>),
}
hir::Expr_::ExprRepeat(P<Expr>, RepeatExprCount)

But for the MIR part, I have no idea how to construct a correct MIR. Should I update the structure of mir::RValue::Repeat and corresponding trans_rvalue function? What should they look like? What is the expected LLVM-IR?

Thanks in advance if someone would like to write a simple mentoring instruction.

qnighy commented 6 years ago

I'm trying to remove the Sized bounds and translate MIRs accordingly.

mikeyhew commented 6 years ago

An alternative that would solve both of the unresolved questions would be explicit &move references. We could have an explicit alloca! expression that returns &move T, and truly unsized types work with &move T because it is just a pointer.

If I remember correctly, the main reason for this RFC was to get dyn FnOnce() to be callable. Since FnOnce() is not implementable in stable Rust, would it be a backward-compatible change to make FnOnce::call_once take &move Self instead? If that was the case, then we could make &move FnOnce() be callable, as well as Box<FnOnce()> (via DerefMove).

cc @arielb1 (RFC author) @qnighy (currently implementing this RFC in #51131) @eddyb (knows a lot about this stuff)

eddyb commented 6 years ago

@mikeyhew There's not really much of a problem with making by-value self work and IMO it's more ergonomic anyway. We might eventually even have DerefMove without &move at all.

mikeyhew commented 6 years ago

@eddyb

I guess I can see why people think it's more ergonomic: in order to opt into it, you just have to add ?Sized to your function signature, or in the case of trait methods, do nothing. And maybe it will help new users of the language, since &move wouldn't be show up in documentation everywhere.

If we're going to go ahead with this implicit syntax, then there are a few details that would be good to nail down:

mikeyhew commented 6 years ago

@eddyb have you seen @alercah's RFC for DerefMove? https://github.com/rust-lang/rfcs/pull/2439

qnighy commented 6 years ago

As a next step, I'll be working on trait object safety.

alexreg commented 6 years ago

@mikeyhew Sadly @alercah just postponed their DerefMove RFC, but I think a separate RFC for &move that complements that (when it does get revived) would be very much desirable. I would be glad to assist with that even, if you're interested.

mikeyhew commented 6 years ago

@alexreg I would definitely appreciate your help, if I end up writing an RFC for &move.

The idea I have so far is to treat unsized rvalues as a sort of sugar for &move references with an implicit lifetime. So if a function argument has type T, it will be either be passed by value (if T is Sized) or as a &'a move T, and the lifetime 'a of the reference will outlive the function call, but we can't assume any more than that. For an unsized local variable, the lifetime would be the variable's scope. If you want something that lives longer than that, e.g. you want to take an unsized value and return it, you'd have to use an explicit &move reference so that the borrow checker can make sure it lives long enough.

alexreg commented 6 years ago

@mikeyhew That sounds like a reasonable approach to me. Has anyone specified the supposed semantics of &move yet, even informally? (Also, I'm not sure if bikeshedding on this has already been done, but we should probably consider calling it &own.)

eddyb commented 6 years ago

Not sure if this is the right place to document this, but I found a way to make a subset of unsized returns (technically, all of them, given a T -> Box<T> lang item) work without ABI (LLVM) support:

cc @rust-lang/compiler

mikeyhew commented 6 years ago

@alexreg

Has anyone specified the supposed semantics of &move yet, even informally?

I don't think it's been formally specified. Informally, &'a move T is a reference that owns its T. It's like

(Also, I'm not sure if bikeshedding on this has already been done, but we should probably consider calling it &own.)

Don't think that bikeshed has been painted yet. I guess &own is better. It requires a new keyword, but afaik it can be a contextual keyword, and it more accurately describes what is going on. Often times you would use it to avoid moving something in memory, so calling it &move T would be confusing, and plus there's the problem of &move ||{}, which looks like &move (||{}) but would have to mean & (move ||{}) for backward compatibility.

eddyb commented 6 years ago

@mikeyhew Oh, I'm sorry I haven't replied to the &move thread, only noticed just now that some of it was addressed at me. I don't think &move is a good desugaring for unsized values.

At most, &move T (without an explicit lifetime), is an ABI detail of passing down a T argument "by reference" - we already do this for types larger than registers, and it naturally extends to unsized T.

And even with &move T in the language, you don't get a mechanism for returning "detached" ownership of an unsized value, based solely on it, as returning &'a move T means the T value must live "higher-up" (i.e. 'a is for how long the caller provided the memory space for the T value).

My previous comment, https://github.com/rust-lang/rust/issues/48055#issuecomment-415980600 provides one such mechanism, that we can implement today (others exist but require e.g. adding a new calling convention to LLVM). Only one such mechanism, if general enough to support all callees (of Rust ABI), is needed, in order to support the surface-level feature, and its details can/should remain implementation-defined.


So IMO &move T is orthogonal and the only intersection here is that it "happens to" match what some ABIs do when they have to pass large (or in this case, of unknown size) values in calls. I do want something like &move T for opting into Box's behavior from any library etc. but not for this.

arielb1 commented 6 years ago

@eddyb

Automatic boxing by the compiler feels weird to me (it occurs only in this special case), and people will do MyRef::new(x.clone(), do_xyz()?), which feels like it would require autoboxing to implement sanely.

However, we can force unsized returns to always happen the "right way" (i.e., to immediately be passed to a function with an unsized parameter) by a check in MIR. Maybe we should do that?

eddyb commented 6 years ago

@arielb1 Yes, I'm suggesting that we can start with that MIR check and maybe add autoboxing if we want to (and only if an allocator is even available).

hanna-kruppe commented 6 years ago

A check that the unsized return value is immediately passed to another function, which can then be CPS'd without all the usual problems of CPS in Rust, sounds like it would work well enough technically. However, the user experience might be non-obvious:

I think it's worthwhile thinking long and hard whether there might be more tailored features that address the usage patterns that we want to enable with unsized return values. For example, cloning trait objects might also be achieved by extending box.

eddyb commented 6 years ago

@rkruppe If we can manage to "pass" unsized values down the stack without actually copying them, I don't think the stack usage should actually increase from what you would need to e.g. call Box::new.

For example, cloning trait objects might also be achieved by extending box.

Sure, but, AFAIK, all ideas, until now, for "emplace" / boxing, seemed to involve generics, whereas my scheme operates at the ABI level and requires making no assumptions about the unsized type. (e.g. @nikomatsakis' previous ideas relied on the fact that Clone::clone returns Self, therefore, you can get the size/alignment from its self value, and allocate the destination before calling it)

hanna-kruppe commented 6 years ago

@rkruppe If we can manage to "pass" unsized values down the stack without actually copying them, I don't think the stack usage should actually increase from what you would need to e.g. call Box::new.

The stack size increase is not from the unsized value but from the rest of the stack frame of the unsized-value-returning function. For example,

fn new() -> dyn Debug {
    let _buf1 = [0u8; 1 << 10]; // this remains allocated "after returning" ...
    "hello world" // ... because here we actually call take()
}
fn take(arg: dyn Debug) {
    let _buf2 = [0u8; 1 << 10];
    println!("{:?}", arg);
}
fn foo() {
    take(new()); // 2 KB peak stack usage, not 1 KB
}

(And we can't do tail call optimization because new is passing a pointer to its stack frame to the continuation, so its stack frame needs to be preserved until after the call.)

eddyb commented 6 years ago

@rkruppe I assume you meant take instead of arg? However, I think you need to take into account that _buf1 is not live when the the function returns, and continuation get called. At that point, only a copy of "hello world" should be left on the stack.

In other words, your new function is entirely equivalent to this:

fn new() -> dyn Debug {
    let return_value: dyn Debug = {
        let _buf1 = [0u8; 1 << 10];
        "hello world"
    };
    return_value
}

EDIT: @rkruppe clarified below.

hanna-kruppe commented 6 years ago

We discussed on IRC, for the record: LLVM does not shrink the stack frame (by adjusting the stack pointer), not ever for static allocs and only on explicit request (stacksave/stackrestore intrinsics) for dynamic allocas.

qnighy commented 6 years ago

@eddyb would you help me with design decision? For by-value trait object safety, I need to insert shims to force the receiver to be passed by reference in the ABI. For example, for

trait Foo {
    fn foo(self);
}

to be object safe, <Foo as Foo>::foo should be able to call <T as Foo>::foo without knowing T. However, concrete <T as Foo>::foos may receive self directly, making it difficult to call the method without knowledge of T. Therefore we need a shim of <T as Foo>::foo that always receives self indirectly.

The problem is: how do I introduce two instances of <i32 as Foo>::foo for example? AFAICT there are two ways:

  1. Introduce a new DefPath Foo::foo::{{vtable-shim}}. This is rather straightforward but we'll need to change all the related IDs: NodeId, HirId, DefId, Node, and DefPath. This seems too much for mere shims.
  2. Use the same DefPath Foo::foo, but include another salt for the symbol hash to distinguish it from the original Foo::foo. It still affects back to rustc::ty but will not change syntax.

I've been mainly working with the first approach, but am being attracted by the second one. I'd like to know if there are any circumstances that we should prefer either of these.

eddyb commented 6 years ago

I'd think you'd use a new variant in InstanceDef, and manually craft it, when creating the vtable. And in the MIR shim code, you'd need to habdle that new variant. I would expect that would be enough for the symbols to be distinct (if not, that's a separate bug).

Centril commented 6 years ago

With respect to the surface syntax for VLAs, I'm highly (to put it mildly) skeptical of permitting [T; n] because:

I'd suggest that we should use [T; dyn expr] or [T; let expr] to distinguish; this also has the advantage that you don't have to store anything in a temporary.

I'll add an unresolved question for this.

alexreg commented 6 years ago

[T; dyn expr] makes sense to me, for the reason you suggest.

qnighy commented 6 years ago

As #54183 is merged, <dyn FnOnce>::call_once is callable now! I'm going to work on these two things:

Next step I: unsized temporary elision

As a next step, I'm thinking of implementing unsized temporary elision. I think we can do this as follows: firstly, we can restrict allocas to "unsized rvalue generation sites". The only unsized rvalue generation sites we already have are dereferences of Box. We can codegen other unsized rvalue assignments as mere copies of references.

In addition to that, we can probably infer lifetimes of each unsized rvalue using the borrow checker. Then, if the origin of an unsized rvalue generation site lives longer than required, we can elide the alloca there.

Next step II: Box<FnOnce>

Not being exactly part of #48055, it would be useful to implement FnOnce for Box<impl FnOnce>. I think I can do this without making it insta-stable or immediately breaking fnbox #28796, thanks to specialization.

alexreg commented 6 years ago

@qnighy Great work. Thanks for your ongoing efforts with this... and I agree, those seem like good next steps to take.

qnighy commented 6 years ago

Ah, annotating a trait impl with #[unstable] doesn't make sense? impl CoerceUnsized<NonNull<U>> for NonNull<T> has one but doesn't show any message on the doc. It can be used without features. Does anyone have an idea to prevent impl<F: FnOnce> FnOnce for Box<F> from being insta-stable?

SimonSapin commented 6 years ago

Calling Box<FnOnce()> seems to work now:

#![feature(unsized_locals)]
fn a(f: Box<FnOnce()>) { f() }

(Playground)

SimonSapin commented 6 years ago

Indeed, stability attributes do not work on impl (unfortunately). As far as I know there is no way to add unstable impls if both the trait and the type are stable.

However FnBox itself is unstable, so breaking it is acceptable if a migration path is immediately available. (Even though we should prefer not to if there’s a reasonable alternative.)

eddyb commented 6 years ago

In addition to that, we can probably infer lifetimes of each unsized rvalue using the borrow checker. Then, if the origin of an unsized rvalue generation site lives longer than required, we can elide the alloca there.

This sounds like a full-on MIR local reuse optimization, which may seem deceptively simple at first, but requires quite the complex analysis of all possible interactions in time, including across loop iterations. I had something at some point that could even apply here, but I'm not sure it could be landed any time soon.

F001 commented 6 years ago

Since unsized values can be used in more circumstances, should we add T: ?Sized bound for more types in std? For example:

pub enum Option<T: ?Sized>{}
pub enum Result<T: ?Sized, E> {}
pub struct AssertUnwindSafe<T: ?Sized>(T);
eddyb commented 6 years ago

@F001 Unsized enums are disallowed today and part of it has to do with the fact that all enum layout optimizations would have to either be disabled or reified into the vtable.

ghost commented 6 years ago

While playing with the unsized_locals feature, I ran into a stumbling block: mem::forget() and mem::drop() don't accept T: ?Sized.

What's the plan for allowing ?Sized types in these and related functions?

eddyb commented 6 years ago

@stjepang sounds like an oversight, feel free to open a PR to relax those bounds. EDIT: we probably need to go around and see what APIs can benefit from this now.

Centril commented 6 years ago

@eddyb shouldn't we wait until unsized_locals is stabilized before doing that?

cramertj commented 6 years ago

@Centril It seems unlikely that we'd see anyone relying on them accepting ?Sized on stable without using the unsized_locals feature, but I suppose it is technically possible to do so.

eddyb commented 6 years ago

@cramertj I don't see how, moves aren't shouldn't be allowed out of !Sized places, on stable. (looks like my intuition was wrong, and might have some bugs, see https://github.com/rust-lang/rust/pull/55785#issuecomment-437162862)

cramertj commented 6 years ago

@eddyb You can observe that the function can be constructed with those type params, just not apply them:

#![feature(unsized_locals)] // for the fn declaration

fn my_drop<T>(_: T) {}
fn my_unsized_drop<T: ?Sized>(_: T) {}
trait Trait {}

fn main() {
    let _ = my_drop::<()>;
    // let _ = my_drop::<dyn Trait>; // This one won't compile
    let _ = my_unsized_drop::<()>;
    let _ = my_unsized_drop::<dyn Trait>; // This will compile
}
qnighy commented 6 years ago

As I said in https://github.com/rust-lang/rust/pull/51131#issuecomment-394076603, I've once attempted to add Sizedness check for function arguments (it would solve https://github.com/rust-lang/rust/issues/50940 too); that, however, turned out to be difficult. The problem case was something like this:

pub trait Pattern<'a> {
    type Searcher;
}

fn clone<'a, P: Pattern<'a>>(this: &MatchesInternal<'a, P>) -> MatchesInternal<'a, P> where P::Searcher: Clone {
    MatchesInternal(this.0.clone())
}

pub struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher);

fn main() {}

Here P::Searcher: Clone implies P::Searcher: Sized. As bounds take precedence in trait selection, during type inference, P::Searcher arbitrarily appears in places where Sized is demanded. That (in combination with the additional Sized bounds) broke compilation of this simple code.

Therefore, I'm thinking of adding an independent pass (or adding a check to an existing pass) after typeck to ensure Sizedness (although I have other things to do regarding unsized rvalues).

earthengine commented 5 years ago

(moved from internals)

I recently make a lot of mistakes by missing impl in function signatures. Almost everytime I was protected by the fact that unsized values cannot appear in function signatures, either argument or return position.

For myself, I would turn on #![deny(bare_trait_objects)] to gain more protection.

I think this could happen to others as well, so I guess unless we prohibited raw Trait appear in function sigtures, stablizing unsized_locals would make things worse as we lost protections. Maybe when it lands it is a good time to also make #![deny(bare_trait_objects)] default?

alexreg commented 5 years ago

@earthengine I agree. I wish we had implemented this and made #![deny(bare_trait_objects)] default for the 2018 edition, in fact! It's too late now, sadly (until the next edition, at least).

alercah commented 5 years ago

Could it be made deny-by-default only in those places where it was previously disallowed, so that no currently-invalid code becomes accepted?

alexreg commented 5 years ago

@alercah That sounds complicated due to the way the linting system currently works... maybe possible though. @arielb1, any thoughts?

alercah commented 5 years ago

Maybe make it two separate lints?

alexreg commented 5 years ago

Yes, that's the obvious solution... seems kind of ugly though?

alercah commented 5 years ago

Could they be pseudonamespaced like clippy lints? #[deny(bare_trait_objects::all)] or #[allow(bare_trait_objects::unsize)]

alexreg commented 5 years ago

That's an interesting idea. I don't know, but @arielb1 probably does.