DEV Community

TheSpacetimeDebugger
TheSpacetimeDebugger

Posted on

I built an open-source Python to C++ AST Transpiler entirely from my phone

Hey everyone! πŸ‘‹

I wanted to share a project I've been pouring my heart into: Astmize. It's an open-source Python-to-C++ transpiler built entirely from my mobile phone (using mobile editors since I don't own a PC at the moment).

Instead of using basic regex or string replacement, Astmize parses Python code into an Abstract Syntax Tree (AST) and maps the logical nodes directly into structurally equivalent, clean C++ code.


πŸ›‘ The C++ Design Bottleneck I Had to Solve

While developing the transpiler from my screen, I hit a massive roadblock regarding type emission. As we know, C++ is statically typed and strictly forbids using auto for non-static class data members without a direct initialization expression, because the compiler must determine the exact object memory layout at compile time.

In Python, fields are dynamically assigned inside __init__ via arguments (e.g., self.speed = speed). Initially, my compiler emitted auto speed; inside the generated C++ class struct, leading to immediate compilation failures.

πŸ’‘ The Solution: Smart Type Inference Engine

To fix this from my phone, I implemented a custom Type Inference Engine in the Python backend that utilizes three core heuristics:

  1. RHS Node Evaluation: Evaluates the Right-Hand Side assignment node to detect concrete primitive constants or explicit type initializers.
  2. Variable Tokenization: Automatically splits attribute names by underscores and parses individual tokens against an explicit C++ type keyword library (e.g., detecting is_ or has_ prefixes infers a bool; tokenizing player_speed maps speed to int).
  3. Safe Fallback Mechanism: If the type remains completely ambiguous, it safely defaults to int instead of emitting an illegal auto, ensuring structural layout validity and preventing compilation blocks.

The live dashboard integrates with standard GCC/Clang via the Wandbox API to compile and run the generated C++ code instantly on the fly.


πŸ”— Check it out here:

I'd absolutely love to get your feedback on the generated C++ structure, how you handle strict type emission in metaprogramming/transpilers, and if there are any C++ edge cases I should guard against!

Drop a ⭐ on GitHub if you find the concept interesting! Happy coding! πŸš€

Top comments (0)