ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
35k stars 2.56k forks source link

translate-c: preserve macro names for integer literals #634

Open andrewrk opened 6 years ago

andrewrk commented 6 years ago
#define foo 1
int bar(void) {
    return foo;
}

should translate to:

const foo = 1;
fn bar() -> c_int {
    return foo;
}

clue:

<andrewrk> using the libclang API is there some way to detect that a number literal came from a macro substitution?
<jonastoth> andrewrk: i think there is a `isMacroID` or something similar.
<jonastoth> If you have the codelocation. I have to search it in code.
<jonastoth> but i saw similar stuff in clang-tidy
<LebedevRI> e.g. https://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/SimplifyBooleanExprCheck.cpp?r1=319325&r2=319324&pathrev=319325
jmc-88 commented 3 years ago

Is this a safe/correct substitution? const foo = 1 permanently introduces foo into the global namespace, while #define might be followed by an #undef later on in the file.

alichraghi commented 2 years ago

@andrewrk afaik, zig is able to translate integer literal macro's for a long time 0.10.0-dev.2306+50a5ddecc result this

...
pub export fn bar() c_int {
    return 1;
}
...
pub const foo = @as(c_int, 1);
Vexu commented 2 years ago

The goal of this issue is to translate that as:

...
pub export fn bar() c_int {
    return foo;
}
...
pub const foo = @as(c_int, 1);
alichraghi commented 2 years ago

sorry, my bad