[cfe-dev] Getting out body of a while Statement

mats petersson via cfe-dev cfe-dev at lists.llvm.org
Thu Nov 17 09:42:13 PST 2016


Really depends on what you want to achieve [in the big picture, not "I want
a variable holding the content inside the while", but what you are actually
planning to do beyond getting it into a variable - do you want to edit the
source file to add or remove something, check that the body does/doesn't do
something]

Something involving the ASTMatcher would be a starting point:
http://clang.llvm.org/docs/LibASTMatchersReference.html?

If you want the actual source-code, then you'll also need to get out the
source location, and use sourcemanager to get the "section of source code
within the body into a string", but consider that you can have really
"interesting" code:

    while( a > 3 )
    {
    #include "mycode.h"
    }

or:
    while( a > 3 )
     #include "mycode.h"

[where the content in mycode.h contains not just the loop body, but also
further code that continues AFTER the loop.]

or:

    #define SOME_MACRO(x) while(a < (x))

    SOME_MACRO(3)
    {
      ...
    }

or:
    while( a > 3 )
    {
        SOME_MACRO(foo);
    }

where SOME_MACRO expands to some rather large chunk of code - and knowing
the "source" is not really helpful in either of these cases. And of course,
like the #include sample, you can have a the loop body end part way through
the macro, so you probably don't really want to rely on the "string
contains the body of the loop" if you want to do something with the content
of the loop that is of any importance. These are of course simple examples
of "unusual programming", but I guarantee that if you look at enoug code,
you'll find SOMETHING like that.


So, depending on what you actualy want to achieve, you may want to NOT try
to deal with this as files/text strings, but as AST-code.

--
Mats

On 17 November 2016 at 16:04, John Tan via cfe-dev <cfe-dev at lists.llvm.org>
wrote:

> i need help to get out the body of a while statement.
>
>
> While( a > 3) {
>
>
> cout << "hello" <<endl;   << --  I wan to copy out this line and store
> into a variable.
>
> }
>
>
> This is a example , i want to take out whats inside of the while
> statement, and if its possible store it into a variable so i can print the
> result out somewhere.
>
>
> Much appreciated
>
> John Tan.
>
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20161117/e5fc403e/attachment.html>


More information about the cfe-dev mailing list