standardese / cppast

Library to parse and work with the C++ AST
Other
1.7k stars 164 forks source link

Empty semantic_parent for outer class/template variable definition #151

Closed deadlocklogic closed 1 year ago

deadlocklogic commented 1 year ago

Explanation of the error.

Input:

cppast::cpp_entity_index _idx;
cppast::libclang_parser _parser;
cppast::libclang_compile_config _config;
auto _file = parse(_idx, "test", R"(
template<typename T>
struct Struct {
static int variable;
};

template<typename T>
int Struct<T>::variable = 1;
)",
                    true);
cppast::visit(*_file, [&](const cppast::cpp_entity& e, cppast::visitor_info info) {
    if (info.event != cppast::visitor_info::container_entity_exit) {
        if (e.kind() == cppast::cpp_entity_kind::variable_t) {
            auto& variable = dynamic_cast<const cppast::cpp_variable&>(e);
            if (variable.is_definition()) {
                auto& _semantic_parent = variable.semantic_parent();
                if (_semantic_parent) {
                    std::cout << "found." << std::endl;
                }
            }
        }
    }
    return true;
});

The semantic_parent is empty, which shouldn't be the case.

foonathan commented 1 year ago

Thanks for reporting, I apparently just forgot to consider variable declarations.

deadlocklogic commented 1 year ago

Just a side question. why the semantic_parent refers to the cpp_class_template and not to the cpp_class as the declaration is contained in the latter? Thanks.

foonathan commented 1 year ago

In an ideal world, cpp_class_template and cpp_class would have no relationship at all, since they're different things. The former only contains the latter to prevent code duplication. If the semantic parent were to refer to cpp_class, we would lose the template parameter information.