Skip to content

Fix compound assignment type casts#228

Merged
nunoplopes merged 2 commits into
Cpp2Rust:masterfrom
joaotgouveia:fix-compound-assignment-type-casts
Jul 6, 2026
Merged

Fix compound assignment type casts#228
nunoplopes merged 2 commits into
Cpp2Rust:masterfrom
joaotgouveia:fix-compound-assignment-type-casts

Conversation

@joaotgouveia

Copy link
Copy Markdown
Contributor

Fixes type casts inside compound assignments under the unsafe model and removes unnecessary casts under the refcount model. When translating binary operators, both unsafe and refcount have a special case for translating compound assignments involving different types.

The types being compared were the original C++ types. However, differences between the original C++ types do not necessarily mean that the corresponding Rust types differ. This caused unnecessary casts to be introduced and, under the unsafe model, resulted in translations that do not compile, such as the following:

int main() {
  std::vector<int> v;
  v.push_back(10);
  v.front() += 5;
  assert(v.front() == 15);
  return v.front();
}
pub fn main() {
    unsafe {
        std::process::exit(main_0() as i32);
    }
}
unsafe fn main_0() -> i32 {
    let mut v: Vec<i32> = Vec::new();
    v.push(10);
    ((v).first_mut().unwrap()) = ((((v).first_mut().unwrap()) as i32) + 5) as i32; // invalid cast
    assert!(((*((v).first_mut().unwrap())) == (15)));
    return (*((v).first_mut().unwrap()));
}

@nunoplopes nunoplopes merged commit 22edd84 into Cpp2Rust:master Jul 6, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants