__traits(documentation, X)
H. S. Teoh
hsteoh at quickfur.ath.cx
Wed Jan 17 22:15:08 UTC 2018
On Wed, Jan 17, 2018 at 06:24:50PM +0000, Simen Kjærås via Digitalmars-d wrote:
[...]
> enum a = import(__FILE__);
> static if (a.indexOf("//") > -1) {
> fireZeMissiles();
> }
[...]
OTOH, this combination of string import and self-referencing __FILE__
opens up a host of curious possibilities (all of which already work
today, btw):
1) Trivial self-reproducing program in D:
import std.stdio;
void main() { write(import(__FILE__)); }
2) Self-checking programs:
import std.algorithm;
static assert(import(__FILE__).canFind("\n/**"),
"Dude, why did you remove the ddoc comment?!");
/** Remove this comment to get a compile error */
void main() {
}
3) Underhanded / deceptive "self-modifying" code:
version(none) {
// This code will never get compiled, right? Right???
import std.stdio;
void main() {
writeln("Launch nuclear missiles");
}
} else {
mixin(() {
import std.array : replace;
return import(__FILE__).replace("none", "all");
}());
}
These are just trivial examples, of course. One can easily imagine more
sophisticated variations that can do all sorts of weird / dangerous
things.
Imagine an advanced version of (2), for example, code that will force a
compilation error if it wasn't formatted correctly.
Or an advanced form of (3) where the real program code is inside an
encrypted comment written in a different language that gets compiled
into D by a CTFE compiler.
Or a CTFE implementation of AST macros that uses libdparse to parse
itself, apply modifications, and mixin. :-D
T
--
"Maybe" is a strange word. When mom or dad says it it means "yes", but when my big brothers say it it means "no"! -- PJ jr.
More information about the Digitalmars-d
mailing list