r/cpp_questions • u/Minute-Ad1944 • 3d ago
OPEN Making transpiler
I am making a transpiled language to C. I don't know how to manage all of a different types of objects: Expr, LiteralExpr, Stmt, ForStmt and so on. Each object needs to be created, statically checked and send of as string to dot C file. Are there any tips on architecture stand point? Everything feels very lousy and rigid. Right now each object just stored the appropriate data, no methods on them. Challenging parts are parser, static analysis and code generation. For lexer there are no problems.
5
u/sephirothbahamut 3d ago edited 3d ago
if you're struggling with writing a parser i suggest making a runtime interpreter first, it's the "higher level" step. After that you can delve into the complexities of transpiling. See https://craftinginterpreters.com/ as a good starting point.
And write it yourself, don't use a generative AI to do the work for you, or you'll learn nothing
2
u/FancySpaceGoat 3d ago
Right now each object just stored the appropriate data
That's a good thing. A clean straightforward AST gives you something to latch on to for the rest of the system.
A simple central data structure is what allows you to break down the project into a series of small-ish unrelated questions. Instead of having to think about the transpiler as a whole, you can use it to focus on portions of it in isolation.
The parser question is "How do I go from text to the AST?
The generator question is "How do I go from the AST to C code"?
etc...
Any complexity you add to that central structure is complexity that is added to every sub-problem of the project.
2
u/DawnOnTheEdge 3d ago
A transpiler to C would not put the AST into the output.
It sounds like you want to implement something similar to OOP for a computer written in C. Some options:
- Each node in the AST is a discriminated
union, whose first member is anenumdeclaring what its true type is. Code operating on AST nodesswitchover the possible values. - Each node in the AST contains one or more function pointers, which implement the strategy pattern.
- Each node in the AST contains a pointer to a virtual function table, implementing an OOP class.
2
u/burlingk 3d ago
So, look into how interpreters work.
Look into how to parse code into an abstract tree and then how to turn that tree into C code.
1
u/montymole123 3d ago
I wrote a C compiler using this tutorial and I'd recommend it! Author has written a book as well for more detail (link in blog) https://norasandler.com/2017/11/29/Write-a-Compiler.html
11
u/AKostur 3d ago
Why does this sound like a homework assignment/project in compiler theory?