title: Design Pattern For Making An Assembler
body: <p>I'm making an 8051 assembler.</p>
  
  <p>Before everything is a tokenizer which reads next tokens, sets error flags, recognizes EOF, etc.<br>
  Then there is the main loop of the compiler, which reads next tokens and check for valid mnemonics:</p>
  
  <pre><code>mnemonic= NextToken();
  if (mnemonic.Error)
  {
      //throw some error
  }
  else if (mnemonic.Text == "ADD")
  {
      ...
  }
  else if (mnemonic.Text == "ADDC")
  {
      ...
  }
  </code></pre>
  
  <p>And it continues to several cases. Worse than that is the code inside each case, which checks for valid parameters then converts it to compiled code. Right now it looks like this:</p>
  
  <pre><code>if (mnemonic.Text == "MOV")
  {
      arg1 = NextToken();
      if (arg1.Error) { /* throw error */ break; }
      arg2 = NextToken();
      if (arg2.Error) { /* throw error */ break; }
  
      if (arg1.Text == "A")
      {
          if (arg2.Text == "B")
              output &lt;&lt; 0x1234; //Example compiled code
          else if (arg2.Text == "@B")
              output &lt;&lt; 0x5678; //Example compiled code
          else
              /* throw "Invalid parameters" */
      }
      else if (arg1.Text == "B")
      {
          if (arg2.Text == "A")
              output &lt;&lt; 0x9ABC; //Example compiled code
          else if (arg2.Text == "@A")
              output &lt;&lt; 0x0DEF; //Example compiled code
          else
              /* throw "Invalid parameters" */
      }
  }
  </code></pre>
  
  <p>For each of the mnemonics I have to check for valid parameters then create the correct compiled code. Very similar codes for checking the valid parameters for each mnemonic repeat in each case.</p>
  
  <p>So is there a design pattern for improving this code?<br>
  Or simply a simpler way to implement this?</p>
  
  <p>Edit: I accepted plinth's answer, thanks to him. Still if you have ideas on this, i will be happy to learn them. Thanks all.</p>