kleene: A Self-Referential Program Generator

C++ source available here

kleene is a utility that can be used to easily generate C++ programs with access to their own source code. It takes its name from Kleene's Second Recursion Theorem, the result on which it is ultimately based.

The kleene program accepts as input a C++ program, then produces a new C++ file that includes a function kleene::MySource() that returns a copy of the program's source code. It is therefore possible to produce C++ programs that can access and manipulate their own source by writing programs that reference the kleene::MySource() function, then running kleene on the program to produce a new C++ file that can access its own source. The new source file will have extra content not present in the original version of the program (most notably, the logic necessary to construct the program source at runtime,) but otherwise is equivalent to the original program.

For example, using kleene, it is possible to write a Quine program in C++ by simply providing the following program as input to kleene:

#include <iostream>

int main() {
    std::cout << kleene::MySource() << std::endl;
}
	

After processing this program with kleene, the generated source file will, when compiled and executed, produce its own source code.

kleene is mostly of theoretical interest, but it could be used in some nontrivial ways. For example, the program could run its source code through a C++ parser to obtain its own abstract syntax tree. This could then be used to introspect on the program's source to find what classes exist, what methods those classes support, etc. It could also be used to produce programs that could send their source code to remote machines for compilation and execution on the native hardware. Since the source would be available on the remote machine and not just the binary, the executable could be subject to static analysis and verification before it would be compiled.

I built kleene in one sitting and so there are almost certainly bugs lurking here that I didn't find during testing. If you have any suggestions for how to improve the program, send me an email and I'd be glad to take a look at your ideas!