Search code examples
c++gccannotationsgcc-plugins

Get class annotation using gcc plugins


I am creating a gcc plugin that analyse a C++ file after parsing it. The plugin walks through the classes and generate some information about them. The plug-in is working, this is how I walk through classes.

    cp_binding_level* level(NAMESPACE_LEVEL(nameSpace));
    for (decl = level->names; decl != 0; decl = TREE_CHAIN(decl)) {
        tree type(TREE_TYPE(decl));
        tree_code dc(TREE_CODE(decl));
        tree_code tc;
        if (dc == TYPE_DECL&& tc == RECORD_TYPE &&
            !DECL_IS_BUILTIN (decl) && DECL_ARTIFICIAL (decl)) {
                //Now we know this is a class
                //Do something
        }
     }

I would like to choose which class he can analyse and which one he can't. My first idea is to add some sort of annotation, that I would read when I parse the class, and decide to analyze it or not.

I never used any sort of annotation in C++, so I don't know if this is possible. If so how would you recommend me to use them, and to get the annotation inside the plug-in ? If it's not, is there a good way to do what I need ?


Solution

  • It can be done, it is not too hard, and it is a pretty common thing to do using a GCC plugin.

    First you must register a new attribute. GCC provides the PLUGIN_ATTRIBUTES callback as a convenient time to do so. Your callback function can then call register_attribute to register attributes. This is documented in the manual, just one link away from the spot you linked to.

    With this function you register another callback that is called when your attribute is applied. You'll have to read some GCC header files or source to really understand what this function should do. But, it can easily track whether it is being applied to a class and, if so, make a note of this for later processing.