Is it possible to force Boost.Spirit Qi to behave in such way, that generated grammar would be adjustable in compliance with some runtime-calculable conditions/rules/rates? For example, the input consists of language constructs, that cause the different alternatives during parsing, some more frequently, others -- less. But the order of the alternatives affects on the efficiency, i.e. runtime optimality of the grammar. In some cases it is impossible to determine in advance which alternative will be chosen more often in the case of arbitrary input (which may be strongly clustered).
I know that it is possible to append symbols to qi::symbols
at runtime, but similar behavior would be desirable for some other parsers.
You sadly forgot (?) to include a sample grammar. So I made up my own. It parses a language like this:
Now. You may notice that each "language construct" (as you refer to it in the OP) has an introducing keyword. This is on purpose.
Because, now, we can use
qi::symbols
with these introducer keywords to dispatch rules (this is known as the Nabialek trick):You can see, we store the address of the corresponding grammar rule as the value in the dictionary. Now, we employ the Nabialek trick (uses
qi::_a
local to invoke the subrule):If you wanted a more 'lightweight' grammar, you'd simply remove some features:
You could even dynamically add features to the
language_constructs
in response to input (e.g. a version identifier in the input, or just when parsing failed). I'm not sure whether this would be a good idea, but... it's all possible.A fully functional sample that parses the above program (if supplied in
input.txt
) complete with adhoc "unit tests", distinct keyword checking support, debugging etc.:See it Live on Coliru