title: Compiling an AST to Assembly
body: <p>I have an abstract syntax tree that I need to convert to assembly for a virtual machine. I don't know how best to do this so I started using a chain of string templates. Pseudo-code example of what I mean, say a simplistic if-statement with one condition needs to be compiled:</p>
  
  <pre><code>std::string compile_if(Node* n) {
      std::string str = "";
  
      curLabel = nLabels++;
  
      str += compile_comparison(n-&gt;getChild(0));
  
      str += ".true"+curLabel+":";
      str += compile_block(n-&gt;getChild(1));
  
      str += ".false"+curLabel+":";
  
      return str;
  }
  </code></pre>
  
  <p>Where each compile_* generates an assembly string based on the current/next AST nodes. Then the final string is run through an assembler. This seems sloppy and hard to maintain, surely this isn't what most compilers do. Is this a bad idea, should I change it? How do most other compilers generate virtual assembly code / machine code?</p>