Hasty Briefsbeta

Writing a C compiler in 500 lines of Python

7 days ago
  • #python
  • #webassembly
  • #compiler
  • The author wrote a C compiler in 500 lines of Python, targeting WebAssembly.
  • The compiler is single-pass, meaning code generation happens during parsing without building an abstract syntax tree.
  • Key features implemented include arithmetic operations, pointers, arrays, functions, and typedefs.
  • Notable omissions include structs, enums, preprocessor directives, and floating-point types.
  • The compiler uses WebAssembly's structured control flow, which complicates certain constructs like 'for' loops.
  • Error handling is minimal, with basic error messages and stack traces.
  • The compiler passes 34 out of 220 test cases in the c-testsuite and can compile simple programs like a Fibonacci sequence generator.
  • The lexer includes a 'lexer hack' to distinguish between type names and variable names.
  • The compiler maintains its own stack frame for C variables, as WebAssembly's stack cannot be referenced directly.
  • Expression parsing uses a helper function to generate code for different operator precedence levels.