2 ms·
Having written small compilers or other code-generators targeting both the JVM and .NET runtimes, i can say that the .NET equivalents have some extra simple opt
by whizzter 1y ago
Having written small compilers or other code-generators targeting both the JVM and .NET runtimes, i can say that the .NET equivalents have some extra simple options for scenarios like this.
Both have always supported building libraries/assemblies and loading them (the ASM library+custom classloaders for Java and AssemblyBuilder in .NET are about equally capable).
However .NET also has DynamicMethod that is specifically built to quickly build just small functions that aren't tied to larger contexts (similar API to asm/assemblybuilder).
But an even easier option for stuff exactly like in the article that people don't widely really seem to know about is that Linq (yes that "sql-like" stuff) actually contains parts for deferred method building that can be easily leveraged to quickly produce customized native code methods.
The neat part about the Linq-code generator is that you can just drop in plain C# code-blocks to be translataed by the C# compiler into Linq snippets and then with some helpers transform everything to Linq-tree's that can then be compiled.
The benefit over Asm/AssemblyBuilder/DynamicMethod is that Linq nodes are basically an built-in AST that can be directly leveraged whereas the other API's requires some mapping of your own AST's to the respective stack-machines.
https://asm.ow2.io/ https://asm.ow2.io/
https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.assemblybuilder?view=net-9.0 https://learn.microsoft.com/en-us/dotnet/api/system.reflecti...
https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.dynamicmethod?view=net-9.0 https://learn.microsoft.com/en-us/dotnet/api/system.reflecti...
https://learn.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression-1.compile?view=net-9.0 https://learn.microsoft.com/en-us/dotnet/api/system.linq.exp...