Buscar en Mind w/o Soul

viernes, mayo 30, 2008

Spirit: Gramáticas flexibles en C++

Una extensión de la librería Boost para generar gramáticas compilables en C++.
Podría usarse para crear nuestro propagador de restricciones.

A simple EBNF grammar snippet:

group ::= '(' expression ')'
factor ::= integer | group
term ::= factor (('*' factor) | ('/' factor))*
expression ::= term (('+' term) | ('-' term))*

is approximated using Spirit's facilities as seen in this code snippet:

group = '(' >> expression >> ')';
factor = integer | group;
term = factor >> *(('*' >> factor) | ('/' >> factor));
expression = term >> *(('+' >> term) | ('-' >> term));

Through the magic of expression templates, this is perfectly valid and executable C++ code. The production rule expression is in fact an object that has a member function parse that does the work given a source code written in the grammar that we have just declared. Yes, it's a calculator. We shall simplify for now by skipping the type declarations and the definition of the rule integer invoked by factor. The production rule expression in our grammar specification, traditionally called the start symbol, can recognize inputs such as:

No hay comentarios: