From e3405fdf36717bd4b01bcab64c1747d148c9a78d Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Thu, 28 Nov 2024 00:02:26 +0100 Subject: [PATCH] emit zeroed arrays as `[0; N]` an array like `int x[16] = {}` was emitted as `[0, 0, 0, 0, ...]`, but is not emitted as `[0; 16]`. --- c2rust-transpile/src/translator/literals.rs | 8 ++++++++ tests/arrays/src/arrays.c | 4 +++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/c2rust-transpile/src/translator/literals.rs b/c2rust-transpile/src/translator/literals.rs index d8eb64db64..ba643c1c7d 100644 --- a/c2rust-transpile/src/translator/literals.rs +++ b/c2rust-transpile/src/translator/literals.rs @@ -190,6 +190,14 @@ impl<'c> Translation<'c> { if is_string { let v = ids.first().unwrap(); self.convert_expr(ctx.used(), *v) + } else if ids.len() == 0 && ty.is_integral_type() || ty.is_floating_type() { + // this was likely a C array of the form `int x[16] = {}`, + // we'll emit that as [0; 16]. + let len = mk().lit_expr(mk().int_unsuffixed_lit(n as u128)); + self.implicit_default_expr(ty, ctx.is_static)? + .and_then(|default_value| { + Ok(WithStmts::new_val(mk().repeat_expr(default_value, len))) + }) } else { Ok(ids .iter() diff --git a/tests/arrays/src/arrays.c b/tests/arrays/src/arrays.c index 9a5f3c9f6f..79868f7bfe 100644 --- a/tests/arrays/src/arrays.c +++ b/tests/arrays/src/arrays.c @@ -6,9 +6,11 @@ static char *foo = "mystring"; void entry(const unsigned buffer_size, int buffer[const]) { int arr[1][1] = { 1 }; - arr[0][0] += 9; + int arr2[16] = {}; + arr2[15] += 9; + int i = 0; char abc[] = "abc";