Search code examples
c++c++14boost-spiritboost-spirit-x3

AST arrangement during annotation and after


Tagged AST nodes can be visited during parsing in X3 using annotation_base::on_success.

Can I get their addresses (and store as well as another info, like corresponding input range iterator pair) and rely on its immutability (for all, but maybe except top-level AST node, which can be moved/copied after parse) when use them later?

Can I assume, that the AST nodes did already allocated in a state, which will not be changed when parse returns?

AST is a combination of aggregates and STL containers: recursive tree.


Solution

  • Of course all intermediate AST nodes can be moved/copied as well.

    This is very clear if you, for example, realize what happens when x_rule parses into X and then you parse x_rule % ','. The vector (or other container) will move/copy the X in, and all other elements might move due to reallocation.

    If the goal is to attach some data out-of-tree, without growing the AST nodes too much, you could consider storing the information separately and referring to it (by id, pointer or reference of some kind).

    In that case you might just need to "garbage collect" your separately stored data (and guard against run-away accumulation in the case of heavy backtracking). Using a shared_ptr could get you that conveniently at the cost of more overhead.