Code generation and self description
A few weeks ago I proposed here an example of C# code generation.
It remind me an old exercise I used to do when discovering a new language.
"The shortest program which produce its own source code on the standard output."
Of course, programs which read explicitly their source code to reproduce it are not accepted.
The idea of the exercise is to find self reference possibilities offers by the language.I've put the executable here
and the source code is here
Just download and then launch the echo.exe then click the "itself" button , the complete source code is displayed in the upper richtext box. Then click the "compile" button , the source code is compiled and saved in c:\echo.exe (be careful not to replace a program of your owns).
Just launch this new program and compare with the first one.... If you want, you can try to change the code to see effects (debug information shown in the second box).
Briefly the principles:
I used a double coding representation. The C# code contains in one point a string array declaration with all the lines of the code between "" and coma separated. All the line of the code ? Not exactly, the array declaration is replaced into the array itself by an arbitrary string (I choose a French poet's famous verses). When you click the "it self" button this exact string is replace by a construction of the array declaration. So at this time the array contains all the code including its own declaration. Then a "foreach" instruction join all the lines into one big string which is the exact source code.
When you push the "compile" button the text box content is compiled .
There is two key factors in this very solution (I'm sure there is at least another solution ).
- The declaration syntax of an array in C# which authorize long static arrays.
- The compilation feature of the .Net framework.
The main part of the code is writed two times. Maybe there is no true connection with this but I can't help comparing this to the double-helix DNA in living cells.
The comparison with living cells ends here. This code isn't (AFAIK) a kind of virus or worm and can't be used for malicious purpose. (For instance, runtime compiling features can't be used during an in-line context).
Ok, now, two questions :
- Is it possible to code that kind of program in PL-SQL? (;-))
Maybe next time !
- The array based solution is interesting but it doesn't imply the Icodegenerator interface. Is there a solution using a more sophisticated structure than an array?
For instance is it possible that a program build its own abstract description usng this interface?
That's all folks !
Remember there is 10 sorts of people : those who understand native binary code and the others !
Comments, answers and suggestions are welcome!