Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 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
3671480
Add switch! macro
lucic71 Apr 24, 2026
dc444ed
Emit switch! when macro contains fallthroughs
lucic71 Apr 24, 2026
eb0a2a8
Update tests
lucic71 Apr 24, 2026
8f2afd8
Recurse into scopes for search for fallthroughs
lucic71 Apr 24, 2026
620c6e4
Continue does not fallthrough
lucic71 Apr 24, 2026
9ed258c
Merge branch 'master' into fallthrough
lucic71 Apr 28, 2026
18bb458
Use RAII delimiters
lucic71 Apr 29, 2026
7c7ebc4
Delete misplaced block
lucic71 Apr 29, 2026
67c099f
Delete unreachable/unused attributes
lucic71 Apr 29, 2026
b3d767e
Rename variables
lucic71 Apr 29, 2026
68ec441
Format code
lucic71 Apr 29, 2026
ad0e083
Format and check formatting for libcc2rs-macros
lucic71 Apr 29, 2026
91df75d
Make libcc2rs depend on libcc2rs-macros
lucic71 Apr 29, 2026
afe3410
Revert "Delete unreachable/unused attributes"
lucic71 Apr 29, 2026
28b6d71
clippy
lucic71 Apr 29, 2026
2aede89
clippy
lucic71 Apr 29, 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
2 changes: 2 additions & 0 deletions .github/workflows/format.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ jobs:
cargo fmt --manifest-path rules/Cargo.toml -- --check
cargo fmt --manifest-path rule-preprocessor/Cargo.toml -- --check
cargo fmt --manifest-path libcc2rs/Cargo.toml -- --check
cargo fmt --manifest-path libcc2rs-macros/Cargo.toml -- --check
find tests -name '*.rs' -print0 | xargs -0 rustfmt --check

- name: Check Rust lints
run: |
cargo clippy --manifest-path rules/Cargo.toml --all-targets --all-features -- -Dwarnings
cargo +nightly clippy --manifest-path rule-preprocessor/Cargo.toml --all-targets --all-features -- -Dwarnings
cargo clippy --manifest-path libcc2rs/Cargo.toml --all-targets --all-features -- -Dwarnings
cargo clippy --manifest-path libcc2rs-macros/Cargo.toml --all-targets --all-features -- -Dwarnings
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ add_custom_target("format"
COMMAND rustup run ${RUST_STABLE_VERSION} cargo fmt --manifest-path ${PROJECT_SOURCE_DIR}/rules/Cargo.toml
COMMAND rustup run ${RUST_STABLE_VERSION} cargo fmt --manifest-path ${PROJECT_SOURCE_DIR}/rule-preprocessor/Cargo.toml
COMMAND rustup run ${RUST_STABLE_VERSION} cargo fmt --manifest-path ${PROJECT_SOURCE_DIR}/libcc2rs/Cargo.toml
COMMAND rustup run ${RUST_STABLE_VERSION} cargo fmt --manifest-path ${PROJECT_SOURCE_DIR}/libcc2rs-macros/Cargo.toml
DEPENDS "install-rust-toolchain"
COMMENT "Running clang-format and cargo fmt on all source files"
VERBATIM
Expand Down
29 changes: 22 additions & 7 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2704,14 +2704,31 @@ void Converter::EmitSwitchArm(clang::CompoundStmt *body, clang::SwitchCase *sc,
}

bool Converter::VisitSwitchStmt(clang::SwitchStmt *stmt) {
PushBreakTarget push(break_target_, BreakTarget::Switch);
bool has_fallthrough = SwitchHasFallthrough(stmt);
PushBreakTarget push(break_target_, has_fallthrough
? BreakTarget::FallthroughSwitch
: 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("{");
if (has_fallthrough) {
// Use the switch-with-fallthrough macro
StrCat("switch!");
} else {
StrCat("'switch:");
}

PushParen switch_macro_paren(*this, has_fallthrough);
PushBrace switch_label_brace(*this, !has_fallthrough);

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

PushBrace match_brace(*this);

clang::SwitchCase *default_case = nullptr;
for (auto *sc : GetTopLevelSwitchCases(stmt)) {
Expand All @@ -2728,8 +2745,6 @@ bool Converter::VisitSwitchStmt(clang::SwitchStmt *stmt) {
StrCat(R"( _ => {})");
}

StrCat("}");
StrCat("}");
return false;
}

Expand Down
2 changes: 1 addition & 1 deletion cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
std::stack<clang::Expr *> curr_for_inc_;
std::stack<clang::QualType> curr_init_type_;

enum class BreakTarget { Loop, Switch };
enum class BreakTarget { Loop, FallthroughSwitch, Switch };
std::stack<BreakTarget> break_target_;

bool isSwitchBreak() const {
Expand Down
30 changes: 30 additions & 0 deletions cpp2rust/converter/converter_lib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,36 @@ std::vector<clang::Stmt *> GetSwitchCaseBody(clang::CompoundStmt *body,
return out;
}

static bool SwitchCaseHasFallthrough(clang::Stmt *stmt) {
if (!stmt) {
return false;
}
if (auto *compound = clang::dyn_cast<clang::CompoundStmt>(stmt)) {
if (compound->body_empty()) {
return true;
}
return SwitchCaseHasFallthrough(compound->body_back());
}
if (clang::isa<clang::BreakStmt>(stmt) ||
clang::isa<clang::ContinueStmt>(stmt) ||
clang::isa<clang::ReturnStmt>(stmt)) {
return false;
}
return true;
}

bool SwitchHasFallthrough(clang::SwitchStmt *stmt) {
if (auto *body = clang::dyn_cast<clang::CompoundStmt>(stmt->getBody())) {
for (auto top_level_case : GetTopLevelSwitchCases(stmt)) {
auto arm = GetSwitchCaseBody(body, top_level_case);
if (arm.empty() || SwitchCaseHasFallthrough(arm.back())) {
return true;
}
}
}
return false;
}

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
2 changes: 2 additions & 0 deletions cpp2rust/converter/converter_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ bool SwitchCaseContainsDefault(clang::SwitchCase *c);
std::vector<clang::Stmt *> GetSwitchCaseBody(clang::CompoundStmt *body,
clang::SwitchCase *head);

bool SwitchHasFallthrough(clang::SwitchStmt *stmt);

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

} // namespace cpp2rust
15 changes: 15 additions & 0 deletions libcc2rs-macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "libcc2rs-macros"
version = "0.1.0"
edition = "2021"

[lib]
proc-macro = true

[dependencies]
proc-macro2 = "1"
quote = "1"
syn = { version = "2", features = ["full", "visit-mut", "extra-traits"] }

[dev-dependencies]
trybuild = "1"
48 changes: 48 additions & 0 deletions libcc2rs-macros/src/goto.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright (c) 2022-present INESC-ID.
// Distributed under the MIT license that can be found in the LICENSE file.

use proc_macro::TokenStream;
use syn::parse::{Parse, ParseStream};
use syn::{parse_macro_input, Expr, Lifetime, Token};

use crate::state_machine::{Arm, GotoStateMachine, StateMachine};

pub fn expand(input: TokenStream) -> TokenStream {
let GotoBlockInput { arms } = parse_macro_input!(input as GotoBlockInput);
GotoStateMachine {
arms: arms
.into_iter()
.map(|a| Arm {
label: a.label.ident.to_string(),
body: a.body,
})
.collect(),
}
.emit()
.into()
}

struct GotoBlockInput {
arms: Vec<GotoArm>,
}

struct GotoArm {
label: Lifetime,
body: Expr,
}

impl Parse for GotoBlockInput {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut arms = Vec::new();
while !input.is_empty() {
let label: Lifetime = input.parse()?;
input.parse::<Token![=>]>()?;
let body: Expr = input.parse()?;
arms.push(GotoArm { label, body });
if input.peek(Token![,]) {
input.parse::<Token![,]>()?;
}
}
Ok(Self { arms })
}
}
81 changes: 81 additions & 0 deletions libcc2rs-macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright (c) 2022-present INESC-ID.
// Distributed under the MIT license that can be found in the LICENSE file.

use proc_macro::TokenStream;

mod goto;
mod state_machine;
mod switch;

// switch!(match <condition> {
// <pat> [if <guard>] => { /* body; may contain break or continue */ },
// ...
// _ => <body>,
// });
//
// Desugars to a goto_block! with a synthetic dispatch arm prepended.
//
// goto_block! {
// '__dispatch => {
// match <condition> {
// <pat_1> => { __s = 1; continue '__sm; }
// ...
// _ => break '__sm,
// }
// },
// '__c1 => { /* body_1 with `break` rewritten to `break '__sm` */ },
// ...
// '__cN => { /* body_N with same rewrite */ },
// };
//
// __sm is the inner label used to describe the state machine insinde goto_block. See goto_block!
// for more info.

#[proc_macro]
pub fn switch(input: TokenStream) -> TokenStream {
switch::expand(input)
}

// goto_block! {
// '<label> => { /* body; may contain `break` or `continue` */ },
// ...
// };
//
// Expands to
//
// {
// let mut __user_break: bool = false; // only if any arm has `break`
// let mut __user_continue: bool = false; // only if any arm has `continue`
// let mut __s: u32 = 0;
// '__sm: loop {
// match __s {
// 0u32 => {
// /* body_0 with these rewrites (outside nested user loops): */
// /* break; -> { __user_break = true; break '__sm; } */
// /* continue; -> { __user_continue = true; break '__sm; } */
// __s = 1; continue '__sm;
// }
// ...
// (N-1)u32 => { /* body_N-1 with same rewrites */ break '__sm; }
// _ => break '__sm, // written only for match exhaustiveness
// }
// }
// if __user_break { break; } // only if any arm has `break;`
// if __user_continue { continue; } // only if any arm has `continue;`
// }
//
// __user_break and __user_continue propagate the `break`s and `continue`s outside the goto state
// machine loop.

#[proc_macro]
pub fn goto_block(input: TokenStream) -> TokenStream {
goto::expand(input)
}

#[proc_macro]
pub fn goto(_input: TokenStream) -> TokenStream {
quote::quote! {
compile_error!("goto!() can only be used inside goto_block!")
}
.into()
}
Loading
Loading