Skip to content

Translate goto label attached to switch case#189

Merged
nunoplopes merged 3 commits into
Cpp2Rust:masterfrom
lucic71:switch-case-label
Jun 12, 2026
Merged

Translate goto label attached to switch case#189
nunoplopes merged 3 commits into
Cpp2Rust:masterfrom
lucic71:switch-case-label

Conversation

@lucic71

@lucic71 lucic71 commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Translates a label atttached to a switch case, from:

  switch (n) {
  target:
  case 0:
    ...
  case 1:
    ...
    goto target;

to

    switch!(match n {
        __v if __v == 0 => 'target: {
            ...
        }
        __v if __v == 1 => {
            ...
            goto!('target);
        }

To make this work, I refactored all switch-analysing functions into a single struct, called SwitchArm. Now, VisitSwitchStmt first calls AnalyzeSwitchArms, then iterates over the SwitchArms and generates the corresponding Rust code. Each SwitchArm has a field called label used for generating __v if __v == 0 => 'target: {, i.e. a labeled block in Rust.

The changes in libcc2rs-macros/src/switch.rs are minimal. I added support for accepting a labeled block in the switch! macro.

Comment thread cpp2rust/converter/converter_lib.cpp Outdated
}

if (auto *sc = clang::dyn_cast<clang::SwitchCase>(inner)) {
arms.push_back({{GetLastStmtOfSwitchCase(sc)},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

you can use emplace_back without {} (more efficient, constructs in place)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

@lucic71 lucic71 force-pushed the switch-case-label branch from 6083460 to 5512310 Compare June 12, 2026 20:18
@nunoplopes nunoplopes merged commit c48eecc into Cpp2Rust:master Jun 12, 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