Feature discussion: __traits(getSource, function)
Robert Jacques
sandford at jhu.edu
Fri Oct 15 21:23:54 PDT 2010
On Fri, 15 Oct 2010 12:28:59 -0400, Adam D. Ruppe
<destructionator at gmail.com> wrote:
> I have what might be a weird request here: a way to get the source code
> of a
> function (or maybe class, etc. too) out of the compiler as a string
> literal.
>
> Using existing features, I was able to think up a hacky solution: use
> __FILE__, __LINE__, and string import to get the source and read it in.
> But my
> implementation was bug riddled, needed extra code at the function, and
> relied
> on conventions.
>
> So I'd prefer something built in - a trait addition could do the job. I
> looked
> at the compiler's source, and it doesn't seem to keep all the needed info
> around, but I imagine it would be a lot easier for it to figure this out
> than
> doing it with mixins.
>
>
> Why would this be useful? My specific case is taking a D function and
> translating it into javascript at run time, so I can print it out to the
> browser and run it there too. (naturally, this requires some conventions
> and
> simplifcation in the code to work anyway, so my hacky solution works for
> me).
>
> Other advantages might be mixing it with string mixins to edit code at
> compile
> time.
>
>
> Honestly, I'm not sure about what else it would be good for. Can anyone
> think
> of something compelling enough for me to dive into the dmd source and see
> about doing it myself?
>
> I started typing this excited about the possibilities, but I ended up
> changing
> my mind while typing the short list of advantages... but let's discuss
> it. Any
> ideas on how it would be useful?
>
> Perhaps a simpler alternative would be __traits(sourceFile) and
> sourceLine -
> to mimic my current solution.
I would favor some form of AST as opposed to raw strings, but I do believe
this functionality would be useful. One example from C# is how linq allows
backend to generate optimal SQL, etc queries based on the expression tree
of the user's lambda functions.
More information about the Digitalmars-d
mailing list