Skip to content

Example: ParserPrinter

Ronald Franco edited this page Dec 21, 2018 · 1 revision

The following example exhibits a parser that uses a more complex AFG involving the * operation (0 or more repetitions), ~ operation (optional), and the + operation (1 or more repetitions). The grammar has two nonterminals that are assigned the names “INPUT” and “MORE” using the name() function from the ParserPrinter class. Using the ParserPrinter class, we print the productions of both nonterminals and print the ParseTree object created when parsing the input string “aaacdcdcd” to stdout.

Flex Specification:

%{
%}

%option noyywrap

%%

[abcd]     { return *yytext; }
.          { /* do nothing */ }

%%

Driver Program:

#include <iostream>

#include "parser.h"
#include "parsetree.h"
#include "parserprinter.h"
#include "flextokenizer.h"

int main()
{
  /* ParserPrinter example */

  /* specify nonterminals input and more
     specify terminals a, b, c, and d */
  Parser<> input, more, a('a'), b('b'), c('c'), d('d');

  size_t pos = 0;

  /* AFG */
  input = *(a) & ~(b | +(more));
  more = c & d;
  
  /* create ParserPrinter object */
  ParserPrinter  p;
 
  /* assign names to nonterminals */
  p.name(&input,"INPUT");
  p.name(&more,"MORE");

  /* prints productions for nonterminal input and more to stdout */
  p.print(&input,false);
  p.print(&more,false);

  /* input string */
  std::string text = "aaacdcdcd";

  /* tokenize input string */
  FlexTokenizer tokens(text);

  /* create ParseTree object */
  ParseTree tree;

  /* begin parsing */
  if (input.parse(&tokens,&pos,&tree))
  {
    std::cout << "Parsing successful!" << std::endl;
    
    /* print parse tree to stdout */
    p.print(&tree);
  }

  return 0; 
}
Clone this wiki locally