ctod
GitHub: https://github.com/dkorpel/ctod
Dub: https://code.dlang.org/packages/ctod
In the summer of 2020, before ImportC, I wrote a tool to help me with my D translations of C libraries: glfw-d and libsoundio-d. I wanted to publish it at some point but kind of forgot about it, until Steven Schveighoffer asked about it last week for his D translation of raylib. That made me inspired to work on it again, and I finally fixed the Windows build, so I want to share it now.
It uses tree-sitter-c to parse .c or .h files including preprocessor directives, and then replaces C syntax patterns with roughly equivalent D patterns wherever it needs and can. Because tree-sitter is very good at error-recovery, it will always output a best-effort translated .d file, no matter the content of the .c file.
Example input file main.c:
#include <stdio.h>
#define TAU 6.283185307179586476925
int main(void) {
char buf[32];
sprintf(buf, "tau = %f\n", TAU);
Wait, this line is not C syntax 🤔
return 0;
}
Output main.d:
module main;
@nogc nothrow:
extern(C): __gshared:
public import core.stdc.stdio;
enum TAU = 6.283185307179586476925;
int main() {
char[32] buf;
sprintf(buf.ptr, "tau = %f\n", TAU);
Wait, this_ line is_; not C syntax 🤔
return 0;
}
The output is supposed to be a good starting point for manual translation: tedious syntax changes are done for you, but you're left with the task of translating (non-trivial) macros, fixing errors because of D's stricter type system, and other misc things ctod doesn't translate properly yet (see also issues on GitHub 🙂).
With the rise of ImportC the use cases for this tool decrease, but in case you still find yourself translating C to D, I hope this is of use to you!