by ridiculous_fish · 10y ago · 0 comments
std::vector<int> foo = ...;
for (iter = foo.begin(); iter != foo.end(); ++iter) {
*iter += 1;
foo[0] += *iter;
}
A naive translation to Rust would run afoul of the borrow checker. If we are to compile C++ to Rust, how are we to address this? Should we simply generate unsafe Rust?The point is to translate new, generally higher level languages to rust. These won't fall afoul of the borrow checker if handled right. I suspect Rust will not have a major restricting effect on their design either. A lot of the borrow checker issues can be papered over with sufficient codegen. When I was working on rust-gc, I often remarked that if we wrote some codegen plugins that convert all types to `Gc<RefCell<Trait>>`, we're effectively Java ;) (Most of this papering over can be done in a way that avoids runtime cost, though not this specific simplistic example for Java)
Though there is this thing called Corrode which is trying to translate C into Rust and iirc they are trying to minimize the unsafe usage in the generated code. That may eventually be able to convert your code into an indexed iteration.
(Also, while the specific code you wrote is safe, if the mutation being performed were more complicated with a non-primitive, it could lead to segfaults)
How would one transpile this code to Rust? Or is the idea that every language ought to have Rust-style semantics? If so, it's hard to reconcile that with "Rust is the new LLVM," since LLVM does not demand such strict semantics.
let mut foo = vec!(1, 2, 3);
for mut iter in 0..foo.len() {
iter += 1;
foo[0] += iter;
}
No unsafe required, I think.But you didn't quite get away with it. The C++ code increments the value in the array through the iterator, while the above Rust increments the iterator (err, index) itself. So it doesn't produce the same result.
More generally, std::vector in C++ typically implements iterators with just raw pointers. This is quite unsafe, but doesn't impose borrow-checker restrictions on the user. How can such languages be compiled to Rust?
I have to admit that I don't understand you here. Can you elaborate on the difference between the two programs?
for (iter = foo.begin(); iter != foo.end(); ++iter) {
*iter += 1;
...
Here `iter` is a pointer. We dereference it and increment the result. This adds 1 to every value in the `foo` vector.The Rust:
for mut iter in 0..foo.len() {
iter += 1;
...
Here `iter` is an array index, and `iter += 1` increments that index. The contents of the `foo` vector are not modified.