Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23789

Bidirectional relationship between nodes in Boost.Spirit

I'm using Boost.Spirit to parse structures similar to

namespace Foo { class Bar { ... } }

This works just fine: I get an object of type namespace_declaration, it has a list of variants for the things it contains, such as class_declarations.

My question is this: how can I ensure that, at the parsing stage, the class_declaration can refer to its containing namespace_declaration? In other words, how can I refer to that object which is the context of what I've just parsed?

Upvotes: 1

Views: 32

Answers (1)

sehe
sehe

Reputation: 393064

You cannot. At least not comfortably.

The fact that you wish for this is probably a sign that you are conflating parsing and processing code.

If all you need is a semantic check, you can try to inject the necessary details in the sub-rules for context, e.g. using inherited attributes.

This can not reasonably be "a bi-directional relationship" if only for the fact that the enclosing construct is (obviously) not even complete yet:

  • In the case of namespace X { class Y { }; } logically you can expect the name "X" to have been parsed - but there's no guarantee that it has already been assigned into the exposed attribute value
  • Idem for the condition expression in the case of while (condition) { statement; }
  • But, consider do { statement; } while (condition); and you can see why you cannot expect statement to know about the enclosing control flow statement.

So, all in all, I would suggest

  1. Separation of concerns: parse first, semantic checks, transformations, processing later
  2. If you must have semantic information on the fly (e.g. because of contextual grammars) pass the context explicitly

Upvotes: 3

Related Questions