Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC: Remove ~ in favor of box and Box #59

Merged
merged 1 commit into from May 2, 2014

Conversation

pcwalton
Copy link
Contributor

No description provided.

@alexcrichton
Copy link
Member

This will probably need DST to land completely before entirely removing ~, due to ~Trait (I don't think Box<Trait> works right now).

@alexcrichton
Copy link
Member

This also may interact poorly with the widely-used ~str (and less-so-widely used ~[T]), at least until DST lands. These are separate types, though, so perhaps they could stay until DST is landed.

@thestinger
Copy link

We could still start replacing it before removing it completely.

@thehydroimpulse
Copy link

A few questions:

  • Would this keep the same semantics as ~? (I'm assuming it will)
  • Is this going to be the future of the current "something".to_owned()? So it would become box("something")

I think there was a possibility of having Uniq become the library type of ~ which seems to make a little more sense than the more abstract "box" word IMO.

@sfackler
Copy link
Member

@thehydroimpulse to the best of my knowledge to_owned() would still exist as it would produce a Box<str>, where box("something") would produce a Box<&'static str>.

# Alternatives

The other possible design here is to keep `~T` as sugar. The impact of doing this would be that a common pattern would be terser, but I would like to not do this for the reasons stated in "Motivation" above.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 for this. I'm all for removing ~EXPR, but I think ~T is a really nice sugar. Having smart pointers as sigils rather than generics makes reading (and writing) Rust much nicer than the equivalent C++.

To address the motivating points: I think Box is to generic a word to be self-documenting, it doesn't tell us anything about how the type behaves or how it is different from &, *, Rc, etc.

Having more than one way to do something is a noble goal, but we have to balance that against convenience. In this case there is a clear way to decide which to use (whether you are using an allocator or not) and we could even enforce that with a lint.

I'm not sure about the 'blindly adding sigils' thing. It kind of seems like a reasonable argument, but do we know people don't do it? If they see Box<...> everywhere in the code, are they likely to do the same with Box<...>?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having smart pointers as sigils rather than generics makes reading (and writing) Rust much nicer than the equivalent C++.

That's quite subjective, as I think it's far easier to read code when it's using normal syntax instead of a special case in the language. Python is a language often referred to as easy to read, and that's said because it avoids sigils, braces and other line noise. Unique pointers are rarely used, and when they are they're rarely spelled out due to type inference. There are far more common patterns, so I don't understand why this one would deserve syntax hard-wired into the language. Even a module like collections::treemap based on unique pointers barely uses the sigil.

it doesn't tell us anything about how the type behaves or how it is different from &, *, Rc, etc.

It behaves as a normal owned type with a destructor, just like a Vec<T> or a HashMap<K, V>. Rust types are expected to have unique ownership by default so Box<T> is really no less informative than TreeSet<T>. Types like Rc and Arc are very rare exceptions.

Having more than one way to do something is a noble goal, but we have to balance that against convenience. In this case there is a clear way to decide which to use (whether you are using an allocator or not) and we could even enforce that with a lint.

It doesn't make sense to add conveniences for things that are rarely used and meant to be discouraged. Vectors and strings are covered by Vec<T> and StrBuf so the remaining use cases for this are recursive data structures where you really just write out the type a single time in the type definition, owned trait objects (which are almost always avoided in favour of generics) and extremely rare circumstances where you want to hoist something large off the stack rather than just borrowing (I can't find a single case in the Rust codebase - it's just used in recursive data structures to make them smaller).

I'm not sure about the 'blindly adding sigils' thing. It kind of seems like a reasonable argument, but do we know people don't do it?

Few people learning Rust understand that unique pointers are not special and could be implemented in a library. It's clearly not something that's going to get across to newcomers. I've explained this thousands of times to people in #rust... it would be nice if the language just made some effort to avoid obscure, confusing syntax in the first place. The pointer sigils are often brought up as something that makes Rust hard to approach, and the only ones commonly used are & and &mut.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that sigils vs generics is subjective. I don't think Python is a good argument in favour of generics though, as you say it avoids braces (and types, never mind generic types) and the problem I have with generic types is when you get a bunch of them nesting up and it all becomes hard to parse.

I would be in favour of making other more common patterns more convenient too. The difference is here we are talking about removing a convenience rather than adding one.

My point about them being self-explanatory is that you still have to go to the docs to find out what Box means, just like Vec or TreeSet. So this is not an advantage over ~. Box doesn't tell me it is heap allocated, is implemented as a pointer, or is unique. I disagree that Rust types are expected to be unique by default - & is the most common (non-value) type and is not unique, likewise Rc, etc. Only ~ and values are unique, and I believe most programmers with a systems background will have a mental divide between pointer types and value types.

I prefer ~[T] to Vec<T> for the same (admittedly subjective) readability reasons. I'm not sure we should be discouraging use of unique pointers. They are the easiest/best way to allocate something on the heap and that seems kind of popular in other languages. I don't think we understand the cost/benefits of idiomatic Rust programming well enough at this stage to be so bold about what programmers should be doing. In particular, the Rust code base is a compiler implementation, and compilers are a fairly unique kind of programming. We should not generalise from rustc to all programming in Rust.

I don't think it is important what can or can't be implemented in a library or for people to understand how 'special' something is. It is important that people understand the language concepts and how to use them.

I agree we should avoid obscure and confusing syntax, but I don't agree that pointer sigils are. After all, pointers are usually denoted by sigils, particularly in C/C++. Currently we only have one more pointer sigil than C++, so I don't think that criticism of Rust is valid anymore (and I haven't heard it as much recently).

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that sigils vs generics is subjective. I don't think Python is a good argument in favour of generics though, as you say it avoids braces (and types, never mind generic types) and the problem I have with generic types is when you get a bunch of them nesting up and it all becomes hard to parse.

It uses and instead of &&, or instead of ||, list instead of [] and so on. Most people find it far easier to read and search for these than the sigil alternatives. The avoidance of more than one way to do the same thing (like including both ~T and Box<T>) is another reason why people find Python easy to read. There's a consistent style for writing it, so programmers can read each other's code without adjusting to another style.

I would be in favour of making other more common patterns more convenient too. The difference is here we are talking about removing a convenience rather than adding one.

This isn't a common pattern though. The mention of Box<T> occurs a single time for each child in the type definition for a recursive data structure and isn't written out at all in the code. There aren't other common use cases. The type definitions are almost always quite short and there's no need to trim off characters.

My point about them being self-explanatory is that you still have to go to the docs to find out what Box means, just like Vec or TreeSet. So this is not an advantage over ~.

You can easily search for "rust box" on a search engine, and it's a lot harder to search for a sigil not even found on some keyboard layouts. The use of tilde feels a lot like including Unicode mathematical symbols in the language syntax to a lot of programmers. https://en.wikipedia.org/wiki/Tilde#Keyboards

Box doesn't tell me it is heap allocated, is implemented as a pointer, or is unique. I disagree that Rust types are expected to be unique by default - & is the most common (non-value) type and is not unique, likewise Rc, etc. Only ~ and values are unique, and I believe most programmers with a systems background will have a mental divide between pointer types and value types.

The term box in Rust means a heap allocation, so it does tell you that. The HashSet<T> or int type doesn't tell you that it's owned in the name, so I'm not sure why you're applying this logic here but ignoring it for every other type. Unique pointers are certainly a value type, just like Vec<T> and HashMap<K, V>. All 3 of these types contain an internal pointer to their data, but have normal value semantics.

I prefer ~[T] to Vec for the same (admittedly subjective) readability reasons. I'm not sure we should be discouraging use of unique pointers. They are the easiest/best way to allocate something on the heap and that seems kind of popular in other languages. I don't think we understand the cost/benefits of idiomatic Rust programming well enough at this stage to be so bold about what programmers should be doing. In particular, the Rust code base is a compiler implementation, and compilers are a fairly unique kind of programming. We should not generalise from rustc to all programming in Rust.

I think there's little doubt that people find the sigil noise hard to understand. It doesn't exist in other languages, and it's not even familiar to C++ programmers. If Mozilla wants to start paying me for for the hours of time I spend explaining this confusing syntax to people on #rust then I'll stop complaining...

As a compiler implementation, rustc has far more recursive data structures than is the norm elsewhere. I think it's a great place to look to find out if unique pointers are commonly used. Since it's written by people who know the language, it's also a great place to look if you want to determine how frequently unique pointers end up misused due to the overly sweet syntax.

They are the easiest/best way to allocate something on the heap and that seems kind of popular in other languages.

The normal way to do a heap allocation is by using a container performing a heap allocation internally. It's not common to be doing it manually and it indicates that the code needs refactoring or serious reconsideration.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Box doesn't tell me it is heap allocated

really? Hm.

They are the easiest/best way to allocate something on the heap and that seems kind of popular in other languages.

Right, but Rust isn't other languages: you should prefer stack allocation as much as possible. Other languages prefer heap allocation because GC.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@thestinger that box means heap in Rust doesn't help newcomers understand it. They need to find that out from the docs or elsewhere, so it is not self-explanatory.

I argue that pointers (including smart pointers) are different from data structures because they are a pointer, rather than containing a pointer.

I'm not saying ~ is easy to understand, I'm saying it is not much more difficult than Box<T> to understand. C++ uses * and & as pointer sigils and we add another one. What is more difficult to explain is the semantics of ~ and that remains unchanged with Box.

rustc may well have more recursive data structures than other compilers. But it still conforms to well known patterns of compiler implementation that are not often found elsewhere. Designing language which are ideal for writing their own bootstrap compiler and awkward for other tasks is a well-known phenomenon and we should be careful to avoid it (which I think we are, but we need to continue to be careful).

Your point about allocating only in collections to the point of refactoring is extreme. Pretty much any C or C++ code base is full of new/mallocs.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @nick29581. I'm ok with removing ~expr, but I would really like to see ~T stay.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

box only means heap allocating in Rust and we're are talking about learning the language.

Not so, "boxing" is the term of art for indirect heap-allocated structures in FP languages implementations and — although the meaning is somewhat broader[0] — in OO languages with a visible distinction between "object" and "primitive" types such as Java and C#.

[0] it includes both heap-allocation and wrapping in a full-fledged object

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nick29581: It's not obvious that it's simply a completely normal type and not extra language complexity to newcomers. With the Box<T> syntax, it's clearly a normal type name and not some kind of modifier like mut. Many people are confused by the syntax and see it as an ownership operator, rather than a smart pointer type. There's a lot of precedence in other languages for our usage of *T and &T, but ~T is right out of left field.

I'm not saying ~ is easy to understand, I'm saying it is not much more difficult than Box to understand. C++ uses * and & as pointer sigils and we add another one. What is more difficult to explain is the semantics of ~ and that remains unchanged with Box.

The semantics are not hard to explain, because they're the same semantics used by other types like Vec<T>. The tutorial already does a good job explaining ownership and move semantics. The questions from people reading the tutorial are almost always related to confusion about the owned pointer syntax. It will be a bit better without ~str and ~[T], but it's still going to be interpreted as some magical modifier rather than a type.

Your point about allocating only in collections to the point of refactoring is extreme. Pretty much any C or C++ code base is full of new/mallocs.

Modern C++ code does not call malloc or new any more frequently than you do in Rust. It uses std::vector as the main memory allocation tool, with std::unique_ptr being used to build recursive containers or make use of virtual functions.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what was impressive originally was not just ~T but how it had been combined with ~[]; between those characters it had eliminated the 'vocabulary' of unique_ptr, vector, and make_unique .. of course now that ~[T] isn't 'the most widely used collection' ~ appears less. r.e. 'learning the language' one thing I had really liked is this had given Rust an almost json like quality of common data structures that could be pretty-printed looking like the actual language syntax for creating them. As a C++ programmer i'd looked enviously at the way languages with decent repls worked on this front, where you can test snippets interactively. I saw an intriguing function search tool for clojure where you specify some input and some output, and it empirically searches for functions that actually do that transformation. Of course this refers to 'some blessed types' and I certainly agree with the goal of generality/versatility.. making user defined types as powerful as anything in the language.. but nonetheless that was extremely appealing.. a big part of the elegance & fresh feel of rust. I know being interpreted isn't a rust goal , but a language as powerful as C++ with a useful interpretable subset would have been rather interesting

@dobkeratops
Copy link

well moving isn't disasterous, and I can see the benefits of generality. But are you underestimating the value of sugar.

What is rust, but C++14 with a static analyzer?
C++ with nice sugar, a clean break to redesign syntax and make it look less of a mess than C++ does with everything retrofitted into C syntax with templates..

The fact it had compact syntax for the types used most of the time (a std::vector alike being ~[T] , unique_ptr being ~T ) was actually a big draw. Between ()tuples ~ [] .. you could write a lot of useful datastructures without much noise getting in the way of your own symbols.

Still the generality is good. I personally want 32bit indexed vectors on a 64bit machine (for 8gb,16gb targets), and relative/compresed pointers (in arenas/precompiled object graphs) etc. I know i wouldn't have been able to get that with ~[T], ~T.

Whats going to happen with move semantics, will there be generalized mechanisms for that

@thestinger
Copy link

Sugar makes sense for things that are common. Unique pointers are anything but common, because recursive data structure definitions are few and far in between. The sigil is only used to define the data structure itself. The code implementing the data structure never actually uses the sigil due to type inference. There will be a single place where new nodes are created, covered by the box expression.

Whats going to happen with move semantics, will there be generalized mechanisms for that

There's already nothing special about unique pointers in regards to move semantics.

@bstrie
Copy link
Contributor

bstrie commented Apr 30, 2014

I think that the success of removing ~ entirely (i.e. not even leaving it as sugar) is contingent on the oft-repeated assertion that unique pointers are rarely necessary. I agree that the language would be cleaner without it (and I'm less and less sad at this fact as time goes on), but I think we'll be hurting unless we're certain that it's not common enough to warrant sugar.

Perhaps we could find examples of recently-written Rust code (the Ludum Dare entries, perhaps?) and count the frequency of unique pointers for some hard data.

@dobkeratops
Copy link

" because recursive data structure definitions are few and far in between."

they're very common for me. a lot of the code i write is basically "build a recursive datastructure, then work on that to produce something simpler".
its crazy when people seem to know what someone elses use case is :)

Whats the compiler itself going to use, isn't it all @ at the minute, set to change.
i think ~T gets used as an optimization for enums too, to keep the variants a comon size (store some of the data from the larger variants in ~T extention )

@thestinger
Copy link

they're very common for me. a lot of the code i write is basically "build a recursive datastructure, then work on that to produce something simpler".

So you have to write the sigil a single time in the type definition, and those lines are almost always incredibly short. You never have to write it in the code implementing the data structure.

@dobkeratops
Copy link

" and those lines are almost always incredibly short.", yeah with nice sugar, they're pleasingly short :)

@julian1
Copy link

julian1 commented Apr 30, 2014

I thought I was in favor of this, but being able to construct algebraic data types requiring boxing with minimal syntactic noise is an extremely nice property to have. Eg,

let list = Cons(1, ~Cons(2, ~Cons(3, ~Nil)));

This immediately shows off the power of the language for any lisp, ML, haskell programmer.

@thestinger
Copy link

@julian1: That's not a useful data structure. It's also far noisier than it would be if you factored out the code into functions, where you're only going to need the box keyword a single time to create a node. You'll need to spell out Box<T> a single time in the type definition for each child. If it has a variable number of children, then unique pointers aren't involved at all.

@dobkeratops
Copy link

ok well, i can setup the text editor shortcut and keyboard macro to write a symbol. Option<~T> could be OptUniq<T> or OptBox<T> (whch is it?) - i hope you get this in the stdlib, along with VecUniq<T>. That would ease the pain, we'll all be making those types ourselves otherwise

The nice thing about the sigil isn't just that its compact, its the lack of nesting; the unpopularity of lisp should show the significance 'not being nested' can have. Its also the reason (i think) for the popularity of OOP - the a.foo(b) calling syntax is less nested than foo(a,b) when you combine calls.

I had a suggestion which might sound crazy, to use @ like haskells' $ as a tool to fight nesting. imagine if Uniq@T , Rc@T etc were synonymous for Uniq<T>, Rc<T> etc. Then you'd have the potential to substitute that with a single macro keystroke, and single visual character in emacs "pretty-mode".. whatever character would make sense to repurpose for that.. @ reads ok i think since you're used to seeing 'adresses' with an @ in the middle)

@thestinger
Copy link

@bstrie: There's no need for statistics and intuition when we already know when these are useful (recursive data structures, owned trait objects). I can't find a single valid use outside of a recursive data structure or for an owned trait object in the upstream Rust code. There's plenty of code misusing unique pointers and that's an argument for removing the sugar, not keeping it.

@julian1
Copy link

julian1 commented Apr 30, 2014

@thestinger of course it's useful to be able to cleanly construct recursive data structures in code, without having to write a bunch of supporting functions. Otherwise, I agree that other cases are weak, and that they are very prone to misuse. One point - if type constructors were functions (like Haskell) , then could this sugar be handled with macros?

@thestinger
Copy link

ok well, i can setup the text editor shortcut and keyboard macro to write a symbol. Option<~T> could be OptUniq or OptBox (whch is it?) - i hope you get this in the stdlib, along with VecUniq. That would ease the pain, we'll all be making those types ourselves otherwise

I can't really see why the standard library would include a bunch of type aliases for rarely used patterns.

I had a suggestion which might sound crazy, to use @ like haskells' $ as a tool to fight nesting. imagine if Uniq@T , Rc@T etc were synonymous for Uniq etc. you'd have the potential to substitute that with a single macro keystroke, and single visual character in emacs "pretty-mode".. recovering what makes the sigils good. (whatever character would make sense to repurpose for that.. @ reads ok i think since you're used to seeing 'adresses' with an @ in the middle)

The language is designed as a coherent whole and the features are intended to be orthogonal with each other. It makes little sense to provide multiple ways of doing the same thing because a noisy minority dislikes the regular way of doing it. If you have a problem with Rust's generics syntax, then please raise that as an issue. Adding an entirely different generics syntax to live alongside it seems like a really bad way of dealing with it...

Many keyboard layouts do not have a tilde key so trying to argue from the perspective of ease of writing code is not at all sensible. It's a very anglocentric thing to assume... and we often hear people complaining that they don't have this key on #rust.

https://en.wikipedia.org/wiki/Tilde#Keyboards

@dobkeratops
Copy link

"If you have a problem with Rust's generics syntax, then please raise that as an issue" ... The generics syntax is not a problem... when complemented by sugar for common types. Complex types get harder to read , the more you compose. ~T was very easy to compose (eg per Option<~T>).. that was the value. wihtout it we'll need to start creating more vocabulary

@huonw
Copy link
Member

huonw commented Apr 30, 2014

👍 from me. Some people have got the misconception that ~ is some magical "ownership operator" or just generally over use it (e.g. the constructor for a struct returning ~Struct).

If box were used as a general pattern operator, we may want overloadable MoveDeref or else things like let box v = box vec![]; wouldn't work. That said, I think by-ref bindings are probably enough for an initial implementation.

@thestinger
Copy link

@julian1: I have a hard time seeing Some(~x) as cleaner than Some(box x). The latter is easy to type on any keyboard without any modifier keys or memorization of key combinations. It's also very easy to search for the meaning of the box expression. I'm sure you wouldn't be happy if Rust used accents or East Asian characters as part of the syntax, and that's exactly how tilde feels to many people without a US keyboard layout.

@dobkeratops
Copy link

been on uk keyboards and mac keyboards, ~ is fine :)

@thestinger
Copy link

@dobkeratops: I linked https://en.wikipedia.org/wiki/Tilde#Keyboards above. We're had plenty of complaints about this on #rust and it's not something trivial to brush aside. The claim that it's easier to type is simply not true... most people do not find it easier even on a US keyboard, because you need to press a modifier and reach for the upper left corner. It's worse when you don't have the key at all, and you need to use a search engine to figure out how to make one.

@nrc
Copy link
Member

nrc commented Apr 30, 2014

Yeah, I think the fact that ~ is not present on non-anglo keyboards is pretty much a killer argument in favour of this RFC. Which given the reasons I don't like it above, is kind of a shame.

@Florob
Copy link

Florob commented Apr 30, 2014

If ~ is truly not available on some keyboard layouts at all that is indeed a strong point. If it is just uncomfortable, then I'd warn against going down that line of argumentation too strongly. At least on a german keyboard (and I think plenty of other layouts) {} and [] are about as hard, if not harder to type than ~, and I doubt we're getting rid of those even though they are far more common.

@Aatch
Copy link
Contributor

Aatch commented Apr 30, 2014

Just to give my two cents:

I think it's a much better idea to remove the sugar, start using this, then reconsider the sugar. If Rust is serious about being a systems language, then we need to collectively get over this obsession with sugar we seem to have developed. Sugar is, by and large, not a good thing. More often than not it causes programmers to use inflexible patterns, resulting in duplicated effort because using ~ was the easiest option.

@andrew-d
Copy link

So, since this is a major language change, I'd like to weigh in here too 😸

I'm a huge fan of the sugar that ~ provides to the language - as @dobkeratops mentioned above, it's nice to avoid the nesting that could potentially be caused by box. I realize that owned pointers are something that should be discouraged, and that typing a tilde on a non-US English keyboard is difficult, but this is probably the first RFC that has actually made me think "I wish this didn't happen". What people find "nice" is quite often subjective, but in this case, put me down for one more person saying "I subjectively find the ~T syntax to be nice and would prefer that this sugar remain".

Also, some things to consider:

  • If people have an issue with typing ~T, if it's just sugar, they're free to type it out explicitly as box T.
  • As with many low-level languages, different data structures can often have a large effect on performance, and assuming that people writing recursive datastructures is an uncommon case seems like an over-general statement to make. E.g. in game development, using strange data structures like Octrees or VP Trees isn't uncommon.

My 2¢ 😃

@dobkeratops
Copy link

yes, tree structures are very common in graphics. scene graphs, hierarchies.
how you can proclaim 'people shouldn't be using these'...
it is as a graphics programmer that the rust I originally saw was so appealing.. compact syntax for the trees of vectors that i'm writing all the time, elegant function signatures for dealing with them.

@thestinger
Copy link

If people have an issue with typing ~T, if it's just sugar, they're free to type it out explicitly as box T.

This goes against adding orthogonal features and enforcing consistency in the language. Rust has made a lot of effort to remove countless features like structural records to simplify the language. Memory allocation is something Rust intends to discourage, and it's not supposed to be common. There's only going to be a single function creating nodes in a recursive data structure implementation.

As with many low-level languages, different data structures can often have a large effect on performance, and assuming that people writing recursive datastructures is an uncommon case seems like an over-general statement to make. E.g. in game development, using strange data structures like Octrees or VP Trees isn't uncommon.

Instead of making a straw man argument, how about responding to what I actually wrote? Recursive data structure type definitions are few and far between. The Box<T> type will only be spelled out in the type definition, not in the code implementing and using the data structure.

@thestinger
Copy link

@dobkeratops: Rust isn't trying to be the second coming of C++. It is not intended to have every possible feature included in the language and it doesn't try to permit more than one style for writing the same code. It's definitely an opinionated language, while C++ is quite the opposite.

The features in the language have been carefully chosen to be as orthogonal as possible. Many neat but mostly redundant features like structural records and export lists were removed. There's an old list of some here. It follows the Python philosophy of providing only one way to do something whenever it can do it without hurting other goals like performance.

@flaper87
Copy link

flaper87 commented May 1, 2014

👍 from me! Folks already covered pretty much all my thoughts on this already!

Maybe Rust can learn by experimenting with not having the ~ sugar ;) we can always add it back later

Big +1 here! 🍰

@pcwalton
Copy link
Contributor Author

pcwalton commented May 1, 2014

Even if it was as much effort as writing the whole of rust, it would still possibly a worthwhile excercise given the volume of C++ in use. It would seem like a hack, but if lifetimes couldn't be infered they could be annotated by a naming convention or the use of smartpointers with a lifetime template parameter.
The analyzer would be a liberty to tell you where it can't analyze, and annotate for where your 'unsafe blocks' are.

I really don't think it would work. No C++ in existence would pass the borrow check. You'd have to basically rewrite the code, at which point there's little point to using C++—you might as well use a different language (which you've essentially created anyway).

The closest thing was Cyclone, which used garbage collection everywhere. It required a fair number of annotations to make work.

@dobkeratops
Copy link

I really don't think it would work. No C++ in existence would pass the borrow check.
now i didn't say it would be easy, but
the amount of working c++ in existence would suggest safe c++ is possible.

You'd have to basically rewrite the code, at which point there's little point to using C++.

existing source bases which have users depending on them, and mature tools, and programmers with familiarity;

you'd do rolling refactors, code would get progressively cleaned up. And people still get their photoshop, unreal engine, whatever. The tool would asserting where the checks should be in places where rust uses match, and so on. C++ has lambdas now which I think make safe patterns easier (like the rust iterators). If i've understood correctly, proponents of the modern c++ style basically treat * as unsafe, and say everything should be wrapped in smart pointers. The direction you're moving in is very, very close. #define Box unique_ptr :)

@pnkfelix
Copy link
Member

pnkfelix commented May 1, 2014

@dobkeratops I claim that this sub-discussion (of whether one can, as you put it, construct "a 1:1 correspondence to things dobkeratops understood in C++", to the extent of actually building a concrete analysis tool) has taken the comment thread drastically off-course from the content of this RFC.

In my view, the whole point of having the RFC repository has been to try to allow for more focused discussions. If we let these threads spin off in arbitrary directions, the process will not be sustainable.

Therefore, I politely request that the participants in that sub-discussion migrate the discussion of such an analysis to a different forum, such as a reddit thread, and try to refrain from continuing it on this pull request comment thread. That, or I guess try to ensure that every comment you add actually draws some explicit connection to this RFC.

added Postscript: Of course the last line of the previous comment, "#define Box unique_ptr", could be interpreted as the explicit connection to this RFC that I requested. But I do not interpret it as such.

@engstad
Copy link

engstad commented May 1, 2014

I also like this RFC. Initially, when learning the language, it was peppered with tilde symbols, but as I have continued, they use has been minimized to such a degree that I wouldn't mind them going away completely.

One of rust-lang's strengths is that it is obvious what you pay for. That a single symbol may induce calls to allocation functions is counter to that intuition. I would actually go even further, not using box() to both allocate and create the box, but to use a new() function to do it.

@adrientetar
Copy link

@thestinger You have a point, Daniel.

@sinistersnare
Copy link

+1 for removing from the language and re-adding it later if it is deemed wanted.

I think a problem is that people think ~ is used more than it actually is in a post-DST world without ~[] or ~str, and also with the fact that international keyboards sometimes to not even have the tilde key is a very strong argument for removing it, at least for now, from the language.

@dobkeratops
Copy link

"I would actually go even further, not using box() to both allocate and create the box, but to use a new() function to do it."

now, strangely I actually react less badly to this if rust was to use a "new" keyword rather than "box" for this purpose.
so first as a stubborn, conditioned C++ person, i'm shown "~"... its outside of my knowledge, but the payoff from 'getting used to it' was big - significantly less laborious to use than the C++ equivalents. Win.

then changing to 'box'/Box... no benefit, a step backwards. seems like a pointless rename of a concept.

but if it was 'new', I'm already used to reading that for allocation... I can keep more coherence in my head when alternating between C++ and Rust.

that might go against rusts' convention of 'new' for constructors? but if you changed those to '::init' or something, you'd put Rust into a state where its slightly more intuitive for users of other languages, and easier to translate API's directly (e.g. if one wants to make bindings to Rust code in C++..)
a fly in the ointment there- destructuting? match ..{ new x => ..} doesn't look like it makes sense admittedly.

@bstrie
Copy link
Contributor

bstrie commented May 1, 2014

@dobkeratops , for historical context, please see this extensive mailing list thread:

http://thread.gmane.org/gmane.comp.lang.rust.devel/6926

Originally, the box keyword was new! Theoretically we could revisit it, but you would need to address all the remaining arguments against new raised in that thread. And that would be an RFC of its own, of course.

@engstad
Copy link

engstad commented May 1, 2014

To clarify, no - I didn't suggest 'new' as a keyword. To construct an Rc, you use:

let x = Rc::new(5);

I am suggesting that boxed values should use:

let x = Uniq::new(5);

Sidenote: As a game developer, I really hate the fact that words like 'box' and 'crate' are reserved.

@pcwalton
Copy link
Contributor Author

pcwalton commented May 1, 2014

That will not work because of the evaluation order. Please read the thread
@thestinger linked.

On Thursday, May 1, 2014, engstad notifications@github.com wrote:

To clarify, no - I didn't suggest 'new' as a keyword. To construct an Rc,
you use:

let x = Rc::new(5);

I am suggesting that boxed values should use:

let x = Uniq::new(5);

Sidenote: As a game developer, I really hate the fact that words like
'box' and 'crate' are reserved.


Reply to this email directly or view it on GitHub.<
https://ci6.googleusercontent.com/proxy/KlNWva5LPvBDEUt-VnqnepmV3bgH7tudFfZppxtY3BaW5dFPu2iDVa-D-UwsgWkWv9iTMoEzEiArO3f1LXC9RgUPIYp4hJaD83NLbMrz28n8ObpW443gwR1mSwiwY96Vv41JoR9oBiYjRXZm6rU-oSMaP2sZ-jF6trLysQBjFjCeoW0RkBIl-2Ro6z9PNUSSwh7yqbwyptUFaSqGa9kBQRSt1FM2P69945Y2SdhmCEbEl_xUo2HsRB7-0I7-kXmo3xDrSX2vD2Nw2vnMc-IcxDVTJnkU=s0-d-e1-ft#https://github.com/notifications/beacon/157897__eyJzY29wZSI6Ik5ld3NpZXM6QmVhY29uIiwiZXhwaXJlcyI6MTcxNDU5OTk0NywiZGF0YSI6eyJpZCI6MzExODc0MDh9fQ==--5859bebe3cb15fc325fdf05f3bce2d8f521340cc.gif

@dobkeratops
Copy link

ok thanks for the link.

the strong precedence we already have of using new() as a static function for types. Path::init("foo")
looks extremely wrong to me.

Ok so this is just completely subjective.
I would claim as later mentioned, "new" for the part that allocates is the way to 'astonish the smallest number of people' c++, Java.. - and convenient for people who have to jump languages; Rust will not exist in a vacuum. it was good that you did aim for c++ familiarity so much.(IMO).

for 'setup', ::init() doesn't seem wrong to me of course, since i've often written '.._init' in C, and when crossing over between C and C++ . Of course if you've been looking at rust for a while, you'll be imprinted otherwise.
Seems this is just historical path. There was no reason to object to ::new() for initialisation when you had sigils doing the actual job of 'new' , but if you start over, it seems more logical to me to use new for allocation and something else for intiialization (which might just be on the stack).

Perhaps the real issue here is the work in renaming ::new. But you've gone through what I would consider more invasive refactorings already with ~[T] -> Vec and removing @

(@engstad heh . i was going to make a similar comment elsewhere. "just don't reserve barrel, stackable..")

@oblitum
Copy link

oblitum commented May 1, 2014

To clarify, no - I didn't suggest 'new' as a keyword. To construct an Rc, you use:
let x = Rc::new(5);
I am suggesting that boxed values should use:
let x = Uniq::new(5);
Sidenote: As a game developer, I really hate the fact that words like 'box' and 'crate' are
reserved.

That's nice... since I'm expecting we be left for most of Rust code with pointers that come through generics and full support for implicit pointer behavior by implementing a trait.

@pcwalton
Copy link
Contributor Author

pcwalton commented May 1, 2014

It's not just laziness. Path::init() just plain looks ugly.

On Thursday, May 1, 2014, Francisco Lopes notifications@github.com wrote:

To clarify, no - I didn't suggest 'new' as a keyword. To construct an Rc,
you use:
let x = Rc::new(5);
I am suggesting that boxed values should use:
let x = Uniq::new(5);
Sidenote: As a game developer, I really hate the fact that words like
'box' and 'crate' are
reserved.

That's nice... since I'm expecting we be left for most of Rust code with
pointers that come through generics and

@dobkeratops
Copy link

It's not just laziness. Path::init() just plain looks ugly.

completely subjective.
i think Box<T>, Vec<T> looks just plain ugly compared to ~T, ~[T] .. now that i've been 'spoiled' by the existing version of rust :)

@pcwalton
Copy link
Contributor Author

pcwalton commented May 1, 2014

@engstad
Copy link

engstad commented May 1, 2014

@pcwalton I can't find the thread that @thestinger supposedly linked to. Either way, yes - syntax is always contentious, go for the one you like that solves the problem. In this case; a way to specify the allocator.

I'm sorry to hear that there's an evaluation order problem with Uniq::new(5). Perhaps there is a work around? As fine as unique pointers are, they do not solve all problems and I don't feel they require its own special support (in the syntax).

@thestinger
Copy link

The whole point of the box keyword is to generalize an optimization to all smart pointers. The expression ~sub_expr allocates a box, then runs the expression, and runs clean-up code if there's a failure. The box keyword is being added to extend this optimization to all smart pointers and possibly other cases like constructing an element in-place at the end of a vector. It's surely going to be added whether or not the existing syntax changes, so with that in mind it makes sense to remove the redundant, inconsistent and confusing syntax we have now.

@bstrie
Copy link
Contributor

bstrie commented May 1, 2014

I really hate the fact that words like 'box' and 'crate' are reserved.

I've seen Java code that uses variables named klass, might I suggest boks and krate? :3

@nrc
Copy link
Member

nrc commented May 1, 2014

This thread is generating more heat than light.

Please take general conversation elsewhere (e.g., /r/rust).

If you are interested in box vs new please file a new RFC or take it to reddit.

I think most of the debate here comes down to subjectivity. I move that we accept and close this PR, with the understanding that if things turn out to be ugly as hell, there is a possibility of resurrecting ~ or adding some other sugar. Any such possibility should be discussed in another RFC.

@alexcrichton
Copy link
Member

I am going to merge this. This extension to the language is necessary for allocator support, as well as unifying ~ with the other pointer types (Rc/Arc/etc).

The largest point of debate is losing the ~ sugar it seems, and this is a point which can be analyzed after-the-fact (we've got time before 1.0).

@alexcrichton alexcrichton merged commit ff5f67a into rust-lang:master May 2, 2014
withoutboats pushed a commit to withoutboats/rfcs that referenced this pull request Jan 15, 2017
Turns out we're relying on a bugfix in 1.10.0 which renders 1.9.0, the first
release with `catch_unwind`, not usable.

Closes rust-lang#59
@Centril Centril added the A-syntax Syntax related proposals & ideas label Nov 23, 2018
wycats pushed a commit to wycats/rust-rfcs that referenced this pull request Mar 5, 2019
Move completed RFCs and fixup numbering
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-syntax Syntax related proposals & ideas
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet