This is the eleventh part of the YAUL series. For your convenience you can find other parts in the table of contents in Part 1 — Introduction
We already know how to parse YAUL application and execute it. Today we are going to compile it to binary and store it on disk.
Compiling
There is just one thing we need to add to YaulCompiler
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static void CompileToAssembly(Expression expression, string assemblyName) { var asmName = new AssemblyName(assemblyName); var asmBuilder = AssemblyBuilder.DefineDynamicAssembly (asmName, AssemblyBuilderAccess.RunAndSave); var moduleBuilder = asmBuilder.DefineDynamicModule(assemblyName, $"{assemblyName}.exe"); var typeBuilder = moduleBuilder.DefineType("Program", TypeAttributes.Public); var methodBuilder = typeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void), new[] { typeof(string) }); Expression.Lambda< Action>(expression).CompileToMethod(methodBuilder); typeBuilder.CreateType(); asmBuilder.SetEntryPoint(methodBuilder); asmBuilder.Save($"{assemblyName}.exe"); } |
Every application needs to have static function call Main
. We create such function, put it in the assembly, and compile one big lambda representing whole script to this function. Next, we mark this function as entry point, and save it on the disk. Everything thanks to LINQ’s magic.
Summary
Our language is finished. We are able to implement simple applications using YAUL, we can compile them to binary and execute them natively (using .NET platform). We have standard functions library. I hope you find it useful despite the name — Yet Another Useless Language.