C++ reflection (P2996) and moc: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 58: Line 58:


We also have to extract the (meta)types and the parameter names (needed e.g. for QML). This should be perfectly possible using P3096. The "limitation" of having matching parameter names across all declarations isn't so stringent (in theory at least).
We also have to extract the (meta)types and the parameter names (needed e.g. for QML). This should be perfectly possible using P3096. The "limitation" of having matching parameter names across all declarations isn't so stringent (in theory at least).
==== Generation of signals ====
<u>This is something that isn't possible in P2996.</u>
Since signals are "ordinary" member functions, we can't inject a definition for them. We would need something like injection of token sequences (P3294, which is C++29 material at this point) in order to synthesize each definition.<blockquote>Of course we could concoct a brand new design for declaring signals. For instance, instead of them being member functions (needing a definition), they could be some other declaration (an inner typedef? a static data member?), and needing some other facility to activate them (rather than just "calling" them like we do today). That's brand new territory to explore and widely incompatible with our 30y of Qt history, so possibly not worth it.</blockquote>


===== Properties =====
===== Properties =====
Line 91: Line 86:


===== Q_ENUM / Q_FLAG =====
===== Q_ENUM / Q_FLAG =====
moc extracts the enumerators (string/value) pairs, this is perfectly possible with P2996.


== What needs to be generated? ==
== What needs to be generated? ==
In a nutshell: some static data, the implementation of various things declared by the Q_OBJECT macro, the implementation of the class' metaObject() function, the implementation of signals, ...
In a nutshell: some static data, the implementation of various things declared by the Q_OBJECT macro, the implementation of the class' metaObject() function, the implementation of signals, ...


For instance, for QWidget:<syntaxhighlight lang="cpp" line="1">
For instance, for QWidget (in Qt 6.10):<syntaxhighlight lang="cpp" line="1">
namespace {
namespace {
struct qt_meta_tag_ZN7QWidgetE_t {};
struct qt_meta_tag_ZN7QWidgetE_t {};
Line 138: Line 134:
</syntaxhighlight>
</syntaxhighlight>


=== JSON output ===
=== Unique tag ===
I'm not sure what this is for.
 
=== qt_create_metaobjectdata ===
This is the basically the storage for the extracted data:<syntaxhighlight lang="cpp" line="1">
    namespace QMC = QtMocConstants;
    QtMocHelpers::StringRefStorage qt_stringData {
        "QWidget",
        "windowTitleChanged",
...
    };
 
    QtMocHelpers::UintData qt_methods {
        // Signal 'windowTitleChanged'
        QtMocHelpers::SignalData<void(const QString &)>(1, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::QString, 3 },
        }}),
        // Signal 'windowIconChanged'
        QtMocHelpers::SignalData<void(const QIcon &)>(4, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::QIcon, 5 },
        }}),...
    };
    QtMocHelpers::UintData qt_enums {
    };
    return QtMocHelpers::metaObjectData<QWidget, qt_meta_tag_ZN7QWidgetE_t>(QMC::MetaObjectFlag{}, qt_stringData,
            qt_methods, qt_properties, qt_enums);
</syntaxhighlight>
 
=== staticMetaObject ===
 
=== qt_static_metacall ===
 
=== metaObject ===
 
=== qt_metacast ===
 
=== qt_metacall ===
 
=== Signals ===
moc needs to generate the implementation of each signal, which is just a call to QMetaObject::activate.
 
<u>This is something that isn't possible in P2996.</u> Since signals are "ordinary" member functions, we can't inject a definition for them. We would need something like injection of token sequences (P3294, which is C++29 material at this point) in order to synthesize each definition (assuming that we get a "define_function" or similar APIs from reflection).
 
Of course we could concoct a brand new design for declaring signals. For instance, instead of them being member functions (needing a definition), they could be some other declaration (an inner typedef? a static data member?), and needing some other facility to activate them (rather than just "calling" them like we do today). That's brand new territory to explore and widely incompatible with our 30y of Qt history, so possibly not worth it...?
 
== JSON output ==
moc also generates a JSON file with interesting metaobject information for the class. This sounds impossible to achieve with reflection.  
moc also generates a JSON file with interesting metaobject information for the class. This sounds impossible to achieve with reflection.  



Revision as of 15:28, 29 May 2025

This is a WORK IN PROGRESS page to understand the implications of "Reflection for C++" for the future of Qt and moc.

TL;DR

  • Reflection in C++26 might be insufficient for replacing moc.
  • We may require token injection and string-based lookup; at least the first is C++29 material, don't know about the second.
  • Extra fancy features like outputting extra JSON files (or embedding JSON in plugins) may be out of scope for this work.

Why?

moc extracts interesting metadata from QObject subclasses / gadgets / namespaces. This metadata is then used at runtime to implement many different QMetaObject facilities.

C++26 will (likely) ship with compile-time reflection. This means that the work that moc does today (as an external tool, with its custom lexer and parser etc.) could be done by the compiler itself. In the future, this may unlock lots of interesting possibilities (e.g. templated QObjects) and reduce technical debt (no need to maintain our own C++ parser for moc).

However, we're not sure how to get there just yet. Some questions that this work aims to answer:

  • Can we replace moc with a pure C++ solution?
    • Is there something missing from standard C++ that we need for moc?
  • How many source code (API) breaks are to be expected?
    • If there's breakage, can porting tools automate the transition?
  • Are there going to be issues with buildsystems?

Reflection for Standard C++: references

Papers that are interesting for Qt:

What needs to be extracted?

moc extracts:

  • the class name
  • the parent class name (following QObject's inheritance chain)
  • properties (Q_PROPERTY)
  • invokables (methods marked with Q_INVOKABLE, Q_SIGNAL, Q_SLOT; may include constructors)
    • for each invokable, also the parameter lists, i.e. types+names of the arguments; and whether they're defaulted (Qt considers these as separate overloads)
    • the revision number (Q_REVISION)
  • Q_CLASSINFO metadata
  • Q_ENUM and Q_FLAGS

Can C++26 reflection extract the same information?

Class name

Should there be no problems, `display_string_of` and friends give us this info.

Parent class

Again, no problems. Can use `bases_of` and extract the first (or even identify the one that gives us access to QObject). This can be spliced to access that class' metaobject and chain the metaobject to the parent's.

Invokables

Marking them with `signals:` or `public slots:` is not going to work.

Instead, we have to use per-invokable markers. We already have Q_SIGNAL, Q_SLOT, Q_INVOKABLE, which are a bit verbose, get the job done. One can even concoct a porting tool...?

We'll need to have those macros expand to some annotation (see P3394, for instance `[[=Qt::signal{}]]` or similar); when reflecting we'll then be able to query for these annotations and extract the relevant function(s).

We also have to extract the (meta)types and the parameter names (needed e.g. for QML). This should be perfectly possible using P3096. The "limitation" of having matching parameter names across all declarations isn't so stringent (in theory at least).

Properties

At the moment declaring a property looks like this:

Q_PROPERTY(Type propName READ getProp WRITE setProp NOTIFY propChanged RESET resetProp [...])

This is basically a "bag of data" that moc tokenizes (the sequence is pretty much "free form"). The individual "attributes" of a property are extracted and set in the metaobject. Q_PROPERTY itself expands to nothing. There's a bunch of related problems here: in a reflection world we need Q_PROPERTY to expand to something that describes the property. It could be as simple as a tagged string_view:

[[=Qt::property{}]] 
static constexpr std::string_view qt_property_COUNTER =
    "Type propName READ getProp WRITE setProp NOTIFY propChanged RESET resetProp [...]";

We can certainly tokenize the string (i.e. Q_PROPERTY's argument) at compile time, all it's needed is a consteval function (after all that's what std::format does for the format string).

However P2996's reflection (AFAICT) does not give us string-based reflection. In other words, given "getProp" as a string, we would need to "look it up" in the class context and get something like a PMF out of it. That does not seem possible at the moment. :-(

We could engineer an alternative, more structured way to declare properties, for instance something like:

constexpr static QProperty<Class, int> prop = {
  .name = "prop",
  .getter = &Class::getProp,
  .setter = &Class::setProp,
  .notify = &Class::propChanged,
  .stored = true,
};

It's very heavy on the eyes compared to the current solution, but it might just work.

There's a lot of subtle details here that make the exercise scary, for instance what is exactly "getter"? A pointer a to non-static member function which returns `int` and it's `const`? What if it has extra defaulted arguments, or it's not const? And what about `notify`, it could have arbitrary arguments and return values... There's lots of engineering here. Of course, if we get string-based lookup in C++29 the exercise becomes quite moot. :-(

Q_CLASSINFO

These are simple (?) key/value pairs.

Q_ENUM / Q_FLAG

moc extracts the enumerators (string/value) pairs, this is perfectly possible with P2996.

What needs to be generated?

In a nutshell: some static data, the implementation of various things declared by the Q_OBJECT macro, the implementation of the class' metaObject() function, the implementation of signals, ...

For instance, for QWidget (in Qt 6.10):

namespace {
struct qt_meta_tag_ZN7QWidgetE_t {};
} // unnamed namespace

template <> constexpr inline auto QWidget::qt_create_metaobjectdata<qt_meta_tag_ZN7QWidgetE_t>()
{ ... }

Q_CONSTINIT const QMetaObject QWidget::staticMetaObject = { ... }

void QWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { ... }

const QMetaObject *QWidget::metaObject() const { ... }

void *QWidget::qt_metacast(const char *_clname) { ... }

int QWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { ... }

// SIGNAL 0
void QWidget::windowTitleChanged(const QString & _t1)
{
    QMetaObject::activate<void>(this, &staticMetaObject, 0, nullptr, _t1);
}

// SIGNAL 1
void QWidget::windowIconChanged(const QIcon & _t1)
{
    QMetaObject::activate<void>(this, &staticMetaObject, 1, nullptr, _t1);
}

// SIGNAL 2
void QWidget::windowIconTextChanged(const QString & _t1)
{
    QMetaObject::activate<void>(this, &staticMetaObject, 2, nullptr, _t1);
}

// SIGNAL 3
void QWidget::customContextMenuRequested(const QPoint & _t1)
{
    QMetaObject::activate<void>(this, &staticMetaObject, 3, nullptr, _t1);
}

Unique tag

I'm not sure what this is for.

qt_create_metaobjectdata

This is the basically the storage for the extracted data:

    namespace QMC = QtMocConstants;
    QtMocHelpers::StringRefStorage qt_stringData {
        "QWidget",
        "windowTitleChanged",
...
    };

    QtMocHelpers::UintData qt_methods {
        // Signal 'windowTitleChanged'
        QtMocHelpers::SignalData<void(const QString &)>(1, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::QString, 3 },
        }}),
        // Signal 'windowIconChanged'
        QtMocHelpers::SignalData<void(const QIcon &)>(4, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::QIcon, 5 },
        }}),...
    };
    QtMocHelpers::UintData qt_enums {
    };
    return QtMocHelpers::metaObjectData<QWidget, qt_meta_tag_ZN7QWidgetE_t>(QMC::MetaObjectFlag{}, qt_stringData,
            qt_methods, qt_properties, qt_enums);

staticMetaObject

qt_static_metacall

metaObject

qt_metacast

qt_metacall

Signals

moc needs to generate the implementation of each signal, which is just a call to QMetaObject::activate.

This is something that isn't possible in P2996. Since signals are "ordinary" member functions, we can't inject a definition for them. We would need something like injection of token sequences (P3294, which is C++29 material at this point) in order to synthesize each definition (assuming that we get a "define_function" or similar APIs from reflection).

Of course we could concoct a brand new design for declaring signals. For instance, instead of them being member functions (needing a definition), they could be some other declaration (an inner typedef? a static data member?), and needing some other facility to activate them (rather than just "calling" them like we do today). That's brand new territory to explore and widely incompatible with our 30y of Qt history, so possibly not worth it...?

JSON output

moc also generates a JSON file with interesting metaobject information for the class. This sounds impossible to achieve with reflection.

Triggers for moc / buildsystem?

moc needs to be run on source files that define classes or namespaces and in which a "trigger keyword" is found: Q_OBJECT, Q_GADGET, Q_NAMESPACE, etc.

Usually, the buildsystem identifies these files, and prepares build rules so that moc is run on them.

The output of moc is some additional .cpp code, this code can either get compiled standalone (and linked into the final target) via additional build rules, or directly included by a .cpp file (e.g. #include "moc_foo.cpp") in which case no additional rules are needed.

How to "trigger reflection"?

The main idea on the table is that we're going to need a macro of some sorts to be placed in a .cpp file. That macro will expand to everything necessary -- defining all the Q_OBJECT-declared stuff by calling consteval functions that apply reflection, extract the necessary data, build tables and the like.

Something like this:

Q_GENERATE_METAOBJECT(Class)

Having to do add this manually seems annoying though.