Skip to content

Example: Counting

Ronald Franco edited this page Dec 21, 2018 · 2 revisions

The following example illustrates how to create a C++11 parser that counts the occurrences of the letter ‘a’ using attribute-flow grammars. The example makes use of the FlexTokenizer class to scan the input string “aaaaa”. The grammar exhibits flow variables and semantic actions to determine the number of a’s parsed.

Flex Specification:

%{
%}

%option noyywrap

%%
a             { return *yytext; }
.             { /* do nothing */ }
%%

Driver Program:

#include <iostream>

#include "parser.h"
#include "flextokenizer.h"

int main()
{
  /* counting parser example */

  /* declare nonterminal A and integer flow variables x and y */ 
  Parser<int> A;
  int x = 0, y = 0;

  /* AFG */
  A>>x = Token('a') & A>>x & [&]{ x++; } | Token('a') & [&]{ x = 1; };

  /* input string */
  const char text[] = "aaaaa";

  /* use the FlexTokenizer class to tokenize input string */
  FlexTokenizer tokens(text);

  /* parse */
  if (A.parse(&tokens))
  {
    std::cout << "Parsing Sucessful: " << x << " a's parsed." << std::endl;
  }
  return 0;
}
Clone this wiki locally