scope objects in boost::spirit and RAII

22 Views Asked by At

In some languages a new scope can be opened and closed again. In C++ this would be the curly brace. Assuming one creates a new scope on encountering an opening curly brace and closes it on encountering the matching closing curly brace. What would happen in case of a parse error before the closing curly brace is encountered? How could one make certain, that the scope opened by the opening curly brace is properly trashed?

2

There are 2 best solutions below

0
sehe On

@sehe This is a question for boost-spirit. Can one simply rely on that the object created by the semantic action for the opening brace is property destroyed when it is not being needed anymore, e.g. when the rule is finished successfully or by an error?

How else would it work? Deterministic destruction at object lifetime is a property of the language. So, unless you're willing to assume Qi leaks memory by design, you're good to go.


Of course, you can forcibly create a memory leak if you insist, e.g. eps[px::new_<int>(42)], but you're able to do the same without Spirit (just use the memory leak operator, operator* new).

Now this comes into play especially/only when you want to use dynamic polymorphism in your AST types:

As I've said before:

You're using semantic actions. As a rule this already misses the sweet spot for embedded grammars, which is why I linked 126 135 answers to Boost Spirit: "Semantic actions are evil"?.

Make that 136 :)

There was this time where I fixed the leaks in a grammar that uses pointer attributes: Building a Custom Expression Tree in Spirit:Qi (Without Utree or Boost::Variant)

0
moaz ahmad On

If parse error occurs before the matching closing brace, it will be taken as invalid scope. The compiler in this case will report it as parse error:

  1. You should check for the semicolons in your code either there is a missing one.

  2. You can restructure your code to avoid parse error.

  3. There are some online tools like onlinegdb that can resolve these issues to some extent by beautifying your code.