Skip to content

Handle more sophisticated switch/case patterns#23

Closed
lucic71 wants to merge 24 commits intoCpp2Rust:masterfrom
lucic71:switch
Closed

Handle more sophisticated switch/case patterns#23
lucic71 wants to merge 24 commits intoCpp2Rust:masterfrom
lucic71:switch

Conversation

@lucic71
Copy link
Copy Markdown
Contributor

@lucic71 lucic71 commented Apr 21, 2026

No description provided.

@lucic71 lucic71 marked this pull request as draft April 21, 2026 14:10
lucic71 added 8 commits April 22, 2026 16:46
Rename visited_cases to visited_switch_cases_ and move it in class
scope. VisitSwitchStmt always resets the set of visited switch cases.

The old implementation was buggy because it saved reused SwitchCase
pointers across translation units, making contain() return true for
switches declared in other TUs.
C++ allows:

  switch (x) {
  default:
    ...
  case 1:
    ...
  }

In rust, default needs to be always on the last position, otherwise,
all values of x, even 1, will hit the default arm. Hence, the above C++
exmaple becomes:

  match x {
    1 => ...
    _ => ...
  }

As such, the algorithm for translating the cases becomes:

  for (case: GetTopLevelSwitchCases()) {
    if (ChainContainsDefault(case)) {
      defer the conversion for the end
    }
    Convert(case)
    Convert(GetSwitchArmBody(case))
  }
  Convert(deferred default)

ChainContainsDefault traverses the stacked case statements starting from
a top level case. For example:

  case 2:
  case 3:
  default:
    ...

is deferred for the end of the match arms and is translated as:

  _ => {}

i.e., drop the case 2, case 3 from the output, only convert as if it was
only default.
@lucic71 lucic71 closed this Apr 23, 2026
@lucic71
Copy link
Copy Markdown
Contributor Author

lucic71 commented Apr 23, 2026

Will split this into 3 PRs:

  • default cases in the middle
  • case chains containing default
  • fallthrough

@lucic71 lucic71 mentioned this pull request Apr 23, 2026
@lucic71 lucic71 deleted the switch branch April 29, 2026 13:18
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.

1 participant