immunant / c2rust

Migrate C code to Rust
https://c2rust.com/
Other
4.03k stars 244 forks source link

c2rust Transpilation failure with Struct Initialization Using Expressions #1171

Open Yeaseen opened 1 day ago

Yeaseen commented 1 day ago

Description

c2rust transpiler demonstrates an inability to handle struct initializations where the fields are initialized with expressions that involve operations, including arithmetic, increments, and decrements. This limitation affects the successful transpilation of typical C code patterns where struct fields are dynamically initialized using various expressions.

Source C Code

typedef struct {
    int a;
} Data;

int main() {
    int p = 10;
    Data myDataInc = {p++}; // error here at Post-increment 
    Data myDataDec = {p--}; // error here at Post-decrement
    Data myDataAdd = {p + 4}; // error here at Arithmetic addition
    Data myDataMinus = {p - 4}; // error here at Arithmetic subtraction
    return 0;
}

Transpilation Error

Attempting to transpile the above code using c2rust results in an error message that suggests a fundamental handling issue with expressions in struct field initialization:

c2rust v0.18.0 shows the following error:

$ c2rust-transpile compile_commands.json -e -o transpiled_code --binary runner
Transpiling runner.c
error: Failed to translate main: Expected no statements in field expression

This error reveals that c2rust expects field initializations in struct to be straightforward without involving any operations or statements.

Expected Behavior

c2rust should ideally handle all forms of valid expressions used in struct field initializations, reflecting the diverse and dynamic initialization practices in C programming.

Yeaseen commented 1 day ago

I tried v0.19.0 as well but got a different type of error for the above C code:

$ c2rust-transpile compile_commands.json -e -o transpiled_code --binary runner
Transpiling runner.c
thread 'main' panicked at /home/yeaseen/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.92/src/lib.rs:849:13:
unsupported proc macro punctuation character '('
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
kkysen commented 1 day ago

I tried v0.19.0 as well but got a different type of error for the above C code:

$ c2rust-transpile compile_commands.json -e -o transpiled_code --binary runner
Transpiling runner.c
thread 'main' panicked at /home/yeaseen/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.92/src/lib.rs:849:13:
unsupported proc macro punctuation character '('
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

This error can be fixed by cargo installing with --locked I believe.

The main issue you opened here, we need to fix, though.

Yeaseen commented 1 day ago

@kkysen thanks for --locked option. The latest release, v0.19.0, works fine and gives the same error as the main issue error.