Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
9b26449
Move visited_cases in class scope
lucic71 Apr 21, 2026
c33fbee
Handle default as middle case
lucic71 Apr 21, 2026
0c143fe
Add switch tests
lucic71 Apr 21, 2026
614e78e
Fix nested switches
lucic71 Apr 21, 2026
c4880c0
Move helper switch/case functions in converter_lib
lucic71 Apr 22, 2026
2aa8cc8
Emit switch! macro on switch stmt with fallthrough
lucic71 Apr 22, 2026
5455888
Update tests
lucic71 Apr 22, 2026
ac4bb8b
Add impl for switch and goto_block macros
lucic71 Apr 22, 2026
2c48f4a
clang-format
lucic71 Apr 22, 2026
e184ee7
Add switch_break
lucic71 Apr 23, 2026
9f9ee3b
Add SwitchBreakRewriter and LoopControlForbidden
lucic71 Apr 23, 2026
41bf5a3
Replace break with switch_break in tests
lucic71 Apr 23, 2026
caf0176
Import switch_break in libcc2rs
lucic71 Apr 23, 2026
cb7c711
Add negative tests
lucic71 Apr 23, 2026
228f855
Add banner
lucic71 Apr 23, 2026
6558323
Add BreakTarget
lucic71 Apr 23, 2026
c7416fc
Delete switch_break
lucic71 Apr 23, 2026
88ffb77
Update tests
lucic71 Apr 23, 2026
2f6a163
Add GotoStateMachine and SwitchStateMachine
lucic71 Apr 23, 2026
d40aeea
Describe behavior of switch and goto_block
lucic71 Apr 23, 2026
f84dbd4
Rename any to should_emit
lucic71 Apr 23, 2026
10acf9d
Add switch interleaved with loops tests
lucic71 Apr 23, 2026
c90fb38
Fix naming
lucic71 Apr 23, 2026
b0b483c
Drop explicit fallthrough from test
lucic71 Apr 23, 2026
cf8d4f0
Delete libcc2rs-macros
lucic71 Apr 23, 2026
214a0b5
Delete libcc2rs-macros references
lucic71 Apr 23, 2026
0749c51
Drop support for reducible default case chains
lucic71 Apr 23, 2026
23765a0
Delete unused functions
lucic71 Apr 23, 2026
033337f
Rename to break_target
lucic71 Apr 23, 2026
88a6e91
Rename VisitSwitchCase to ConvertSwitchCaseCondition
lucic71 Apr 23, 2026
690f97e
Add EmitSwitchArm
lucic71 Apr 23, 2026
436fc75
Simplify PushBreakTarget
lucic71 Apr 23, 2026
f6b377f
Track current break target using a stack
lucic71 Apr 24, 2026
7bc6f88
Update tests
lucic71 Apr 24, 2026
5caae54
Merge branch 'break-target' into default-case-in-the-middle
lucic71 Apr 24, 2026
cc986ec
Delete the global switch test
lucic71 Apr 24, 2026
77a9bb7
Re-add body declaration
lucic71 Apr 24, 2026
e6a66fd
Update tests
lucic71 Apr 24, 2026
af549fe
Fail if translation-fail test successfully compiles
lucic71 Apr 24, 2026
0ccf03c
Merge branch 'break-target' into default-case-in-the-middle
lucic71 Apr 24, 2026
f9722cd
Update tests
lucic71 Apr 24, 2026
acdbd2b
Merge branch 'master' into default-case-in-the-middle
lucic71 Apr 27, 2026
f209f74
Update tests
lucic71 Apr 27, 2026
aa3013e
Merge branch 'master' into default-case-in-the-middle
lucic71 Apr 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 43 additions & 39 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2621,63 +2621,67 @@ bool Converter::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr *expr) {
return false;
}

static std::unordered_set<clang::SwitchCase *> visited_cases;

bool Converter::VisitSwitchCase(clang::SwitchCase *stmt) {
if (visited_cases.contains(stmt)) {
return false;
bool Converter::ConvertSwitchCaseCondition(clang::SwitchCase *stmt) {
clang::Stmt *cur = stmt;
clang::SwitchCase *last = nullptr;
bool first = true;

while (auto *sc = clang::dyn_cast<clang::SwitchCase>(cur)) {
if (auto *case_stmt = clang::dyn_cast<clang::CaseStmt>(sc)) {
if (!first) {
StrCat("|| v == ");
}
Convert(case_stmt->getLHS());
}
last = sc;
first = false;
cur = sc->getSubStmt();
}
visited_cases.insert(stmt);

if (auto case_stmt = clang::dyn_cast<clang::CaseStmt>(stmt)) {
Convert(case_stmt->getLHS());
if (clang::isa<clang::CaseStmt>(last)) {
StrCat(" => {");
} else /* DefaultStmt */ {
StrCat("_ => {");
}
return false;
}

if (clang::isa<clang::CaseStmt>(stmt->getSubStmt())) {
StrCat("|| v == ");
void Converter::EmitSwitchArm(clang::CompoundStmt *body, clang::SwitchCase *sc,
bool is_default) {
if (is_default) {
StrCat("_ => {");
} else {
if (clang::isa<clang::CaseStmt>(stmt)) {
StrCat(" => {");
} else {
StrCat("_ => {");
}
StrCat("v if v == ");
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.

instead of v == 1 || v == 2 || v == 3, can't you do:

 match x {
            1 | 2 | 3 => ...

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.

It's because of enums. A switch such as:

enum E {
        A,
        B,
        C
};

int main() {
        enum E e = A;
        switch (e) {
        case A:
        case B:
                break;
        case C:
                break;
        }
        return 0;
}

would get translated as:

        match e {
            // (E::A as u32)  is an expression, not a pattern, so it's not allowed to be chained using |
            (E::A as u32) | (E::B as u32) => {
                break;
            }
            v if v == (E::C as u32) => {
                break;
            }
            _ => {}
        }

I think we can just ignore the implicit enum to integer cast in order to allow this to work with | instead of ||

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.

Ok, then let's keep it as-is. In C++ you can mix enums and integers.

ConvertSwitchCaseCondition(sc);
}

Convert(stmt->getSubStmt());
return false;
for (auto *t : GetSwitchCaseBody(body, sc)) {
Convert(t);
}
StrCat("},");
}

bool Converter::VisitSwitchStmt(clang::SwitchStmt *stmt) {
PushBreakTarget push(break_target_, BreakTarget::Switch);
auto *body = clang::dyn_cast<clang::CompoundStmt>(stmt->getBody());
assert(body);

StrCat("'switch: {");
StrCat(std::format("let __match_cond = {};", ToString(stmt->getCond())));
StrCat("match __match_cond");
StrCat("{");

bool has_default_case = false;
auto body = llvm::cast<clang::CompoundStmt>(stmt->getBody());
assert(body);

for (auto it = body->body_begin(), end = body->body_end(); it != end;) {
if (auto switch_case = clang::dyn_cast<clang::SwitchCase>(*it)) {
if (clang::isa<clang::CaseStmt>(switch_case)) {
StrCat("v if v == ");
} else {
has_default_case = true;
}
VisitSwitchCase(switch_case);
++it;
}

while (it != end && !clang::isa<clang::SwitchCase>(*it)) {
Convert(*it);
++it;
clang::SwitchCase *default_case = nullptr;
for (auto *sc : GetTopLevelSwitchCases(stmt)) {
if (SwitchCaseContainsDefault(sc)) {
default_case = sc;
continue;
}

StrCat("},");
EmitSwitchArm(body, sc, /*is_default=*/false);
}

if (!has_default_case) {
if (default_case) {
EmitSwitchArm(body, default_case, /*is_default=*/true);
} else {
StrCat(R"( _ => {})");
}

Expand Down
5 changes: 4 additions & 1 deletion cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,10 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

virtual bool VisitSwitchStmt(clang::SwitchStmt *stmt);

virtual bool VisitSwitchCase(clang::SwitchCase *stmt);
void EmitSwitchArm(clang::CompoundStmt *body, clang::SwitchCase *sc,
bool is_default);

bool ConvertSwitchCaseCondition(clang::SwitchCase *stmt);

virtual bool VisitVAArgExpr(clang::VAArgExpr *expr);

Expand Down
52 changes: 52 additions & 0 deletions cpp2rust/converter/converter_lib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,58 @@ clang::Expr *CreateConversionToBool(clang::Expr *expr, clang::ASTContext &ctx) {
/*BasePath=*/nullptr, clang::VK_PRValue, clang::FPOptionsOverride());
}

std::vector<clang::SwitchCase *>
GetTopLevelSwitchCases(clang::SwitchStmt *stmt) {
std::vector<clang::SwitchCase *> cases;
if (auto *body = llvm::dyn_cast<clang::CompoundStmt>(stmt->getBody())) {
for (auto *s : body->body()) {
if (auto *sc = clang::dyn_cast<clang::SwitchCase>(s)) {
cases.push_back(sc);
}
}
}
return cases;
}

bool SwitchCaseContainsDefault(clang::SwitchCase *c) {
for (clang::Stmt *cur = c;;) {
if (clang::isa<clang::DefaultStmt>(cur)) {
return true;
}
auto *sc = clang::dyn_cast<clang::SwitchCase>(cur);
if (!sc) {
return false;
}
cur = sc->getSubStmt();
}
return false;
}

static clang::Stmt *GetLastStmtOfSwitchCase(clang::SwitchCase *c) {
clang::Stmt *cur = c->getSubStmt();
while (auto *sc = clang::dyn_cast<clang::SwitchCase>(cur)) {
cur = sc->getSubStmt();
}
return cur;
}

std::vector<clang::Stmt *> GetSwitchCaseBody(clang::CompoundStmt *body,
clang::SwitchCase *head) {
std::vector<clang::Stmt *> out;
out.push_back(GetLastStmtOfSwitchCase(head));
auto it = body->body_begin(), end = body->body_end();
while (it != end && *it != head) {
++it;
}
assert(it != end);
++it;
while (it != end && !clang::isa<clang::SwitchCase>(*it)) {
out.push_back(*it);
++it;
}
return out;
}

static std::string_view Trim(std::string_view s) {
auto is_space = [](unsigned char c) { return std::isspace(c); };
auto b = std::find_if_not(s.begin(), s.end(), is_space);
Expand Down
8 changes: 8 additions & 0 deletions cpp2rust/converter/converter_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,14 @@ bool ContainsVAArgExpr(const clang::Stmt *stmt);

clang::Expr *CreateConversionToBool(clang::Expr *expr, clang::ASTContext &ctx);

std::vector<clang::SwitchCase *>
GetTopLevelSwitchCases(clang::SwitchStmt *stmt);

bool SwitchCaseContainsDefault(clang::SwitchCase *c);

std::vector<clang::Stmt *> GetSwitchCaseBody(clang::CompoundStmt *body,
clang::SwitchCase *head);

void Unwrap(std::string &s, std::string_view prefix, std::string_view suffix);

} // namespace cpp2rust
50 changes: 50 additions & 0 deletions tests/unit/out/refcount/switch_case_then_default.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
extern crate libcc2rs;
use libcc2rs::*;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::io::prelude::*;
use std::io::{Read, Seek, Write};
use std::os::fd::AsFd;
use std::rc::{Rc, Weak};
pub fn case_then_default_0(x: i32) -> i32 {
let x: Value<i32> = Rc::new(RefCell::new(x));
let r: Value<i32> = Rc::new(RefCell::new(0));
'switch: {
let __match_cond = (*x.borrow());
match __match_cond {
v if v == 2 => {
(*r.borrow_mut()) = 20;
break 'switch;
}
_ => {
(*r.borrow_mut()) = 10;
break 'switch;
}
}
};
return (*r.borrow());
}
pub fn main() {
std::process::exit(main_0());
}
fn main_0() -> i32 {
assert!(
(({
let _x: i32 = 1;
case_then_default_0(_x)
}) == 10)
);
assert!(
(({
let _x: i32 = 2;
case_then_default_0(_x)
}) == 20)
);
assert!(
(({
let _x: i32 = 99;
case_then_default_0(_x)
}) == 10)
);
return 0;
}
56 changes: 56 additions & 0 deletions tests/unit/out/refcount/switch_cases_and_default_stacked.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
extern crate libcc2rs;
use libcc2rs::*;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::io::prelude::*;
use std::io::{Read, Seek, Write};
use std::os::fd::AsFd;
use std::rc::{Rc, Weak};
pub fn cases_and_default_stacked_0(x: i32) -> i32 {
let x: Value<i32> = Rc::new(RefCell::new(x));
let r: Value<i32> = Rc::new(RefCell::new(0));
'switch: {
let __match_cond = (*x.borrow());
match __match_cond {
v if v == 3 => {
(*r.borrow_mut()) = 3;
break 'switch;
}
_ => {
(*r.borrow_mut()) = 42;
break 'switch;
}
}
};
return (*r.borrow());
}
pub fn main() {
std::process::exit(main_0());
}
fn main_0() -> i32 {
assert!(
(({
let _x: i32 = 1;
cases_and_default_stacked_0(_x)
}) == 42)
);
assert!(
(({
let _x: i32 = 2;
cases_and_default_stacked_0(_x)
}) == 42)
);
assert!(
(({
let _x: i32 = 3;
cases_and_default_stacked_0(_x)
}) == 3)
);
assert!(
(({
let _x: i32 = 99;
cases_and_default_stacked_0(_x)
}) == 42)
);
return 0;
}
8 changes: 4 additions & 4 deletions tests/unit/out/refcount/switch_default_first.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ pub fn default_first_0(x: i32) -> i32 {
'switch: {
let __match_cond = (*x.borrow());
match __match_cond {
_ => {
(*r.borrow_mut()) = 7;
break 'switch;
}
v if v == 1 => {
(*r.borrow_mut()) = 1;
break 'switch;
Expand All @@ -24,6 +20,10 @@ pub fn default_first_0(x: i32) -> i32 {
(*r.borrow_mut()) = 2;
break 'switch;
}
_ => {
(*r.borrow_mut()) = 7;
break 'switch;
}
}
};
return (*r.borrow());
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/out/refcount/switch_default_middle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ pub fn default_middle_0(x: i32) -> i32 {
(*r.borrow_mut()) = 1;
break 'switch;
}
_ => {
(*r.borrow_mut()) = 99;
break 'switch;
}
v if v == 2 => {
(*r.borrow_mut()) = 2;
break 'switch;
}
_ => {
(*r.borrow_mut()) = 99;
break 'switch;
}
}
};
return (*r.borrow());
Expand Down
Loading
Loading