Saturday, October 18, 2014

Parser – Function Operator

The Parser class has a single purpose, to take an input string and return tokens of this string.  This is basically like how the special function operator class works.  So the first improvement made to the Parser class was to change it to a function operator class.

The set input function with a single string argument used to set the input string, plus initialize the position and operator state members, was removed.  A input string argument was added to the constructor and initialization of these other members were added.  The token function used to return pointers to tokens from the input string was changed to the operator function:
TokenPtr token(bool operandState)   →    TokenPtr operator()(bool operandState)
Callers now set the input through the constructor and retrieve tokens like this:
QString input = {...};
...
Parser parse {input};
...
TokenPtr token = parse();
Note that the instance was renamed from "parser" to "parse" as this makes the code a read a little better.  No argument is shown because operand state argument has a default value (which is not shown in the function definition above).

The Tester class for the most part looks like above except that the input string is a standard string and is converted to a C-style string with the c_str() string member function (which is then implicitly converted to a QString).  This won't be needed once the parser uses standard strings.

The Translator class changes are a slightly different form because it contains a parser pointer member defined as a std::unique_ptr.  Previously, a single instance was created for the life of the translator instance.  There is no reason to do this since there is nothing in the parser instance that needs to be retained between translations.  A new parser instance is created for each translation and must be deferenced to obtain tokens:
m_parse.reset(new Parser {input});
...
token = (*m_parse)(operand);
And finally before returning, the translate function resets the parser member pointer to the default pointer (calls the reset function with no argument), which deletes the parser instance.  The Translator class will also be changed to a function operator class so this final reset won't be necessary.

[branch parser commit 9e782539f3]

No comments:

Post a Comment

All comments and feedback welcomed, whether positive or negative.
(Anonymous comments are allowed, but comments with URL links or unrelated comments will be removed.)