|
Boost Users : |
Subject: [Boost-users] [spirit] Parsing a value multiple times
From: Ravi (lists_ravi_at_[hidden])
Date: 2010-05-03 00:04:31
Hi,
Is there a standard qi paradigm for parsing a value multiple times? Suppose
a configuration file has three parameters "a", "b" and "c" each of which take
integers. Here's how to parse them in arbitrary order:
struct abc { int a; int b; int c; };
..
// Inside the qi grammar with attribute abc
start = +(
(lit("a") >> lit("=") >> int_[bind(&abc::a,_val)=_1] >> lit(";"))
|(lit("b") >> lit("=") >> int_[bind(&abc::b,_val)=_1] >> lit(";"))
|(lit("c") >> lit("=") >> int_[bind(&abc::c,_val)=_1] >> lit(";"))
);
With the grammar above, the final value of "a" comes from the the last line in
the configuration file of the form "a = 23;" overwriting all previous
statements. This (later values overriding earlier ones) is a fundamental
requirement for this application.
Is there a better way to write the rule above? Can semantic actions be avoided
(perhaps by use of FUSION_ADAPT_STRUCT)?
As far as I can tell, using the "^" operator requires that the members of
struct abc be boost::optionals. This grammar does not need optionals because
the instance of struct abc that is passed to the parsing function is already
initialized with sane defaults.
Second, composing grammars of this form does not seem to scale well. For
example, suppose the configuration above is extended by one parameter, "d",
for a different "composite" configuration file format. The easiest way to
incorporate the new parameter is to copy and paste the old rule:
struct abcd : abc { int d; };
..
// Inside the qi grammar with attribute abcd
start = +(
(lit("a") >> lit("=") >> int_[bind(&abcd::a,_val)=_1] >> lit(";"))
|(lit("b") >> lit("=") >> int_[bind(&abcd::b,_val)=_1] >> lit(";"))
|(lit("c") >> lit("=") >> int_[bind(&abcd::c,_val)=_1] >> lit(";"))
|(lit("d") >> lit("=") >> int_[bind(&abcd::d,_val)=_1] >> lit(";"))
);
The solution above is a clear DRY violation. Is there a solution that avoids
copy-and-paste?
Ravi
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net