corrode icon indicating copy to clipboard operation
corrode copied to clipboard

Provide Corrode-specific versions of system headers

Open jameysharp opened this issue 7 years ago • 0 comments

Consider C's assert.h, which defines a macro named assert. Since Corrode runs the C preprocessor before parsing the input, either the assert macro is expanded to some ugly expression, or you're compiling with -DNDEBUG and the assert macro expands to nothing at all.

Rust provides an equivalent macro (assert!()) and ideally we'd translate to that, to keep the generated source looking as similar as possible to the original.

The best plan I've come up with so far to do that is as follows:

  • Create a directory of Corrode-specific replacements for system headers, such as our own assert.h.
  • Pass the path for that directory to GCC via its -isystem flag, so our headers replace the system headers but not the user's include path. (That way if somebody writes their own assert.h, we won't clobber it.)
  • Define new Corrode-specific builtin functions or variables that we can map to Rust syntax which can't be otherwise expressed in C. For example, __builtin_assert could be interpreted as a function that takes a single boolean argument, and translated to the Rust debug_assert! macro.
  • Provide macros that translate particular C interfaces into the corresponding builtin, so our assert.h would just provide #define assert(cond) __builtin_assert(cond). It should not depend on the C preprocessor definition NDEBUG, because we want the translated assertions to be controlled by Rust compiler flags instead.

Ideally developers could add new builtins by just editing these header files, without having to change Corrode's implementation. To that end maybe these declarations should syntactically just be extern function or variable declarations (so Corrode knows what type to treat them as), and we should introduce a custom function/variable attribute that tells Corrode what Rust to emit whenever the declaration is used.

Besides assert, I'd like to provide Corrode-specific versions of:

  • NULL in conjunction with issue #77.
  • stdint.h, to generate i16::max_value() for INT16_MAX and so on.
  • arpa/inet.h so ntohl and friends become e.g. u32::from_be.

And so on.

jameysharp avatar Oct 18 '16 10:10 jameysharp