|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
Download ExpressionCompiler86_Src.zip - 13.91 KB What Does The Sample DoIt compiles C# lambda expressions into 16-bit executable files. Why Is It Interesting?C# expression trees allow you to analyze C# code and reinterpret it in a different way. E.g. LINQ-to-SQL takes expressions written in C# and turns them into SQL statements. This sample turns (a small subset of) C# into 8086 machine code. BackgroundI have read many blogs about LINQ expression trees and how "cool" they are. However, very few posts explained what actually expression trees are for. This sample demonstrated one possible usage. Some day I may expand this article to further disucss the place of the expression trees in life. Why .Com FilesI chose NB: "com" here is merely a file extensions, as in Compiling ExpressionsAn expression may contain variables and three arithmetic operations: +, -, and *. All arithmetic is done in unsigned 16-bit integers. When the generated COM file executes, it prints a banner, prompts the user for parameter values (if any), calculates the result and displays it. COM files shall be executed in a console window, e.g. from E.g. expression C# for MS-DOS, version 1.0 x? 10 y? 20 ((2 * x) + (3 * y)) = 80 Calling Expression CompilerThe sample provides class // a little wrapper to makes things simpler
static void Compile<T>(string file, Expression<T> expr)
{
using (ExpressionCompiler86 compiler = new
ExpressionCompiler86(file))
{
compiler.Compile(expr);
}
}
...
Compile<Func<int>>( ''constant.com'', () => 42);
Compile<Func<int>>( ''noparams.com&'', () => 1+2+3*4);
Compile<Func<int,int,int>>( ''xy.com'', (x,y) => 2*x + 3*y );
NOTE: quotation marks did not make it through the submission wizard. I had to replace them with double apostrophes ''. Codeproject team has been notified DisclaimerPlease be lenient to the quality of code. It is not production code. It's a sample, or, rather, a proof of concept. It was written in one day. It contains absolutely no automated tests. There absolutely no overflow checks or anything like that. Class names may be questionable. Bugs are likely. Enjoy!
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||