title: Constructing custom expression trees while using operators in C#
body: <p>This question is about constructing custom expression trees in .NET using the operators found in C# (or any other language). I provide the question along with some the background information.</p>
  
  <hr>
  
  <p>For my <a href="https://sourceforge.net/projects/sharpassembler/" rel="nofollow">managed 2-phase 64-bit assembler</a> I need support for expressions. For example, one might want to assemble:</p>
  
  <pre><code>mystring: DB 'hello, world'
            TIMES 64-$+mystring DB ' '
  </code></pre>
  
  <p>The expression <code>64-$+mystring</code> must not be a string but an actual valid expression with the benefits of syntax and type checking and IntelliSense in VS, something along the lines of:</p>
  
  <pre><code>64 - Reference.CurrentOffset + new Reference("mystring");
  </code></pre>
  
  <p>This expression is not evaluated when it is constructed. Instead, it is evaluated later in my assembler's context (when it determines the symbol offsets and such). The .NET framework (since .NET 3.5) provides support for expressions trees, and it seems to me that it is ideal for this kind of expressions which are evaluated later or somewhere else.</p>
  
  <p>But I don't know how to ensure that I can use the <em>C# syntax</em> (using +, &lt;&lt;, %, etc..) for constructing the expression tree. I want to prevent things like:</p>
  
  <pre><code>var expression = AssemblerExpression.Subtract(64,
      AssemblerExpression.Add(AssemblerExpression.CurrentOffset(),
          AssemblerExpression.Reference("mystring")))
  </code></pre>
  
  <p>How would you go about this?</p>
  
  <hr>
  
  <p>Note: I need an expression tree to be able to convert the expression into an acceptable custom string representation, and at the same time be able to evaluate it at a point in time other than at its definition.</p>
  
  <hr>
  
  <p>An explanation of my example: <code>64-$+mystring</code>. The <code>$</code> is the current offset, so it is a specific number that is unknown in advance (but known at evaluation time). The <code>mystring</code> is a symbol which may or may not be known at evaluation time (for example when it has not yet been defined). Subtracting a constant C from a symbol S is the same as <code>S + -C</code>. Subtracting two symbols S0 and S1 (<code>S1 - S0</code>) gives the integer difference between the two symbol's values.</p>
  
  <p>However, this question is not really about how to evaluate assembler expressions, but more about <em>how to evaluate any expression that has custom classes in them</em> (for things like the symbols and <code>$</code> in the example) and how to still ensure that it can be pretty-printed using some visitor (thus keeping the tree). And since the .NET framework has its expression trees and visitors, it would be nice to use those, if possible.</p>