On Thursday, 13 October 2022 at 19:18:07 UTC, Dennis wrote:
# 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](https://code.dlang.org/packages/glfw-d) and
[libsoundio-d](https://code.dlang.org/packages/libsoundio-d). I
wanted to publish it at some point but kind of forgot about it,
until [Steven Schveighoffer asked about
it](https://github.com/dkorpel/glfw-d/discussions/18) last week
for his [D translation of
raylib](https://github.com/schveiguy/draylib). 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](https://github.com/tree-sitter/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:
```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:
```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](https://github.com/dkorpel/ctod/issues) 🙂).
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!
This is cool, I once did a port of DWM (tiling X window manager)
to D because I like DWM, I wanted to learn D from within a code
base I knew reasonably well and I wanted a pure D window manager,
why not?
It was quite tedious though and DWM is pretty clean concise C
code. As an experiment I just did it again with this tool to try
it out and it was fantastic. For that small code base it only
took about 15min to port and get compiling and a few more to fix
the two minor runtime issues. Without this tool it took several
hours to get compiling and then several more to nail down and fix
all the runtime bugs.
Thanks!