Searching for a declaration (using a loop)

This example shows how to search for a specific declaration using a loop on the declarations tree.

Let’s consider the following c++ file (example.hpp):

namespace ns{
    int a = 1;
    int b = 2;
    double c = 3.0;

    double func2(double a) {
        double b = a + 2.0;
        return b;
    }
}

The following code will show you how to loop on the tree and find a declaration

from pygccxml import utils
from pygccxml import declarations
from pygccxml import parser

# Find the location of the xml generator (castxml or gccxml)
generator_path, generator_name = utils.find_xml_generator()

# Configure the xml generator
xml_generator_config = parser.xml_generator_configuration_t(
    xml_generator_path=generator_path,
    xml_generator=generator_name)

# The c++ file we want to parse
filename = "example.hpp"

# Parse the c++ file
decls = parser.parse([filename], xml_generator_config)

global_namespace = declarations.get_global_namespace(decls)

ns_namespace = global_namespace.namespace("ns")

int_type = declarations.cpptypes.int_t()
double_type = declarations.cpptypes.double_t()

for decl in ns_namespace.declarations:
    print(decl)

# This prints all the declarations in the namespace declaration tree:
# ns::a [variable]
# ns::b [variable]
# ns::c [variable]
# double ns::func2(double a) [free function]

# Let's search for specific declarations
for decl in ns_namespace.declarations:
    if decl.name == "b":
        print(decl)
    if isinstance(decl, declarations.free_function_t):
        print(decl)

# This prints:
# ns::b [variable]
# double ns::func2(double a) [free function]