ctod: a tool that translates C code to D

Dennis dkorpel at gmail.com
Thu Oct 13 19:18:07 UTC 2022


# 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!


More information about the Digitalmars-d-announce mailing list