Is it possible to obtain textual representation of an arbitary code?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Jan 26 11:31:37 UTC 2018


On Friday, January 26, 2018 11:18:21 Oleksii Skidan via Digitalmars-d-learn 
wrote:
> Hi,
>
> I wonder if it's possible to convert D language code into a
> string at compile time? C/C++ preprocessor has this feature
> built-in: `#` preprocessing operator allows converting a macro
> argument into a string constant. See the following code snippet
> for example:
>
> ```cplusplus
> #define ASSERT(EXPR) some_function((EXPR), #EXPR)
>
> // Elsewhere in the code:
> void some_function(bool const condition, char const* const expr) {
>    if (!condition) {
>       printf("Assertion failed for: %s\n", expr);
>    }
> }
>
> // Usage:
> ASSERT(a == b); // Will print "Assertion failed for: a == b"
> ```
>
> I could imagine a mixin-based solution in D:
> ```d
> // Usage:
> ASSERT!"a == b";
> ```
> But it seems a bit alien to me. First of all, it kind of
> stringly-typed one. Secondly, neither IDEs nor advanced text
> editors are able to figure out that the string contains actual D
> code, and so neither syntax highlighting nor code assistance work
> with this approach.

You can use stringof on symbols to get their string representation, but you
can't get sections of code that way. D makes it very easy to turn strings
into code using mixin statements, but it doesn't provide ways to take
arbitrary code and turn it into strings. And in many cases, the compiler
wouldn't necessarily have access to the code anyway, just like you wouldn't
in C/C++. C/C++ can do it with macros but not arbitrary code, and D doesn't
have the equivalent of C/C++ macros. Arguably the closest thing that D has
to C/C++ macros is the ability to mixin strings, and if you're mixing in a
string, you already have the code as a string.

And yes, if you use a lot of metaprogramming stuff like string mixins, then
you're not going to have the code to see in your text editor, but that's
what happens when you generate code at compile time rather than having the
code sit in a file.

However, if you want syntax highlighting for a string literal that contains
code, you can use q{} to contain the string literal rather that "" or `` -
e.g. q{auto i = 42;} instead of "auto i = 42;", then most text editors will
highlight the string as if it were just code.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list