Uses of Parser Generators

We tend to think of parser generators as being used to implement the front-end of a programming language compiler, and having graduated from writing the desk-calculator program this is typically what we use them for. In this article we’ll take a look at another application of parser generators, specifically bisonc++, which is creating visualizations of state-transition diagrams for regular expressions.

Regular expressions (regexes for short) are concise ways of writing string-matching patterns. There are lots of operators for POSIX-compatible regexes, but the basis operators are (in order of precedence highest to lowest) the Kleene-closure (a* for zero or more a‘s), concatenation (ab for a followed by b) and set union (a|b for either a or b) . From these we get the identities a+ = aa* and a? = (a|ε) where epsilon derives the empty string. (Operators + and ? are assumed to have precedence equal to *, and cannot be used in combination with each other.)

The grammar for our parser of regexes (which would be ambiguous without operator precedence being specified) can therefore be formalized as:

R ← R* | R+ | R? | RR | R ‘|’ R | char

The representation of each node can be a C++ class, where the name of the node, its numerical ID and a list of edges can be implemented as:

class Node {
public:
    enum class NodeType : char { None = '?', Start = 'S', Accept = 'A', Disjunct = '|', Concatenate = '.', Star = '*', Question = '?', Plus = '+', Letter = 'z' };
    Node(NodeType type, int id = -1, const std::string& name = "")
        : type{ type }, id{ id },
            name{ name.empty() ? (std::string{} + std::to_underlying(type)) : name }
            {}
     void addEdgeTo(const std::shared_ptr<Node>& node) {
        if ((node->getType() != Node::NodeType::Letter)
            && (node->getType() != Node::NodeType::Accept)) {
                throw std::runtime_error("Cannot add edge to this node type.");
            }
        if (std::find_if(edges.begin(), edges.end(),
                [&node](const auto& n){ return n.lock() == node; }
            ) == edges.end()) {
            edges.push_back(node);
        }
    }
    const NodeType getType() const { return type; }
    int getId() const { return id; }
    const std::string getName() const {
        return name.empty() ? (std::string{} + std::to_underlying(type)) : name;
    }
    const auto& getEdges() const { return edges; }
    const auto& getFirst() const { return first; }
    const auto& getLast() const { return last; }
    bool isNullable() const { return nullable; }
    const std::shared_ptr<Node>& getLeft() const { return left; }
    const std::shared_ptr<Node>& getRight() const { return right; }

    static void appendUnique(std::vector<std::shared_ptr<Node>>& dest,
                             const std::vector<std::shared_ptr<Node>>& src) {
        for (const auto& item : src) {
            if (std::find(dest.begin(), dest.end(), item) == dest.end()) {
                dest.push_back(item);
            }
        }
    }

    static std::shared_ptr<Node> makeLetter(int id, const std::string& name) {
        auto node = std::make_shared<Node>(NodeType::Letter, id, name);
        node->nullable = false;
        node->first.push_back(node);
        node->last.push_back(node);
        return node;
    }

    static std::shared_ptr<Node> makeDisjunct(std::shared_ptr<Node> left, std::shared_ptr<Node> right) {
        auto node = std::make_shared<Node>(NodeType::Disjunct);
        node->left = std::move(left);
        node->right = std::move(right);
        node->nullable = node->left->nullable || node->right->nullable;
        node->first = node->left->first;
        appendUnique(node->first, node->right->first);
        node->last = node->left->last;
        appendUnique(node->last, node->right->last);
        return node;
    }

    static std::shared_ptr<Node> makeConcat(std::shared_ptr<Node> left, std::shared_ptr<Node> right) {
        auto node = std::make_shared<Node>(NodeType::Concatenate);
        node->left = std::move(left);
        node->right = std::move(right);
        for (const auto& u : node->left->last) {
            for (const auto& v : node->right->first) {
                u->addEdgeTo(v);
            }
        }
        node->nullable = node->left->nullable && node->right->nullable;
        node->first = node->left->first;
        if (node->left->nullable) {
            appendUnique(node->first, node->right->first);
        }
        node->last = node->right->last;
        if (node->right->nullable) {
            appendUnique(node->last, node->left->last);
        }
        return node;
    }

    static std::shared_ptr<Node> makeStar(std::shared_ptr<Node> child) {
        auto node = std::make_shared<Node>(NodeType::Star);
        node->left = std::move(child);
        for (const auto& u : node->left->last) {
            for (const auto& v : node->left->first) {
                u->addEdgeTo(v);
            }
        }
        node->nullable = true;
        node->first = node->left->first;
        node->last = node->left->last;
        return node;
    }

    static std::shared_ptr<Node> makePlus(std::shared_ptr<Node> child) {
        auto node = std::make_shared<Node>(NodeType::Plus);
        node->left = std::move(child);
        for (const auto& u : node->left->last) {
            for (const auto& v : node->left->first) {
                u->addEdgeTo(v);
            }
        }
        node->nullable = node->left->nullable;
        node->first = node->left->first;
        node->last = node->left->last;
        return node;
    }

    static std::shared_ptr<Node> makeQuestion(std::shared_ptr<Node> child) {
        auto node = std::make_shared<Node>(NodeType::Question);
        node->left = std::move(child);
        node->nullable = true;
        node->first = node->left->first;
        node->last = node->left->last;
        return node;
    }

    static std::shared_ptr<Node> makeStart(std::shared_ptr<Node> regex, int acceptId) {
        auto start = std::make_shared<Node>(NodeType::Start, 0);
        auto accept = std::make_shared<Node>(NodeType::Accept, acceptId);
        start->left = std::move(regex);
        start->right = accept;

        for (const auto& v : start->left->first) {
            start->addEdgeTo(v);
        }
        if (start->left->nullable) {
            start->addEdgeTo(accept);
        }
        for (const auto& u : start->left->last) {
            u->addEdgeTo(accept);
        }
        return start;
    }

    template<typename Callable>
    void visit(const Callable& c) {
        if (left != nullptr) {
            left->visit(c);
        }
        std::invoke(c, *this);
        if (right != nullptr) {
            right->visit(c);
        }
    }
private:
    NodeType type;
    int id;
    std::string name;
    bool nullable{ false };
    std::vector<std::shared_ptr<Node>> first;
    std::vector<std::shared_ptr<Node>> last;
    std::vector<std::weak_ptr<Node>> edges;
    std::shared_ptr<Node> left, right;
};

Update 2026/11/07: This class originally used std::list<Node>::iterator to store the edges, but it was decided to go back to traditional syntax tree convention and use std::shared_ptr<Node> as the semantic type.

The constructor takes up to three parameters, these being the node type (leaf node Start, Accept and Letter or non-leaf node operator), identifier (used only for leaf nodes which are shown in the final diagram) and name (Letter nodes only). Edges are stored as std::weak_ptr<Node> to prevent circular references and member function addEdgeTo() allows for creating them. In keeping with encapsulation patterns, getters are provided for all of the private data members.

Static factory functions are used to create new nodes of a particular type, and these reference their child nodes data members to set their own left, right (if used), first, last, nullable (used if the entity can be bypassed, such as with operator ?) and create any edges (which go from rightmost of one subtree to leftmost of the next).

The Visitor Pattern is implemented with the function visit() which accepts a callable object (lambdas defined in main.cc) to walk the tree in depth-first left-to-right order. This is how the nodes and edges are listed for the GraphViz output.

For the parser there are four tokens, CHAR, LPAREN, RPAREN and ERROR, together with four operators, BAR, PLUS, STAR and QUESTION. The first operator (having least precedence) is left-associative, the rest are right-associative. (Concatenation has precedence after BAR, but does not use an operator symbol.) All of these are exported to the header file Tokens.h.

Update 2024/10/05: It was found that attempts to use %prec for concatenation did not work correctly on regexes such as (aa|bb)+ so the code has been rewritten to use rule-based precedence.

The complete parser file grammar.y is shown below (apologies for lack of syntax highlighting):

%scanner-token-function scanner.lex()
%stype std::shared_ptr<Node>
%token-path Tokens.h
%token CHAR LPAREN RPAREN ERROR BAR PLUS STAR QUESTION

%%

start       : regex EOF  { $$ = Node::makeStart(std::move($1), ++nodeId); nodes = std::move($$); }
            ;

regex       : disjunct              { $$ = std::move($1); }
            ;

disjunct    : disjunct BAR concatenate  { $$ = Node::makeDisjunct(std::move($1), std::move($3)); }
            | concatenate           { $$ = std::move($1); }
            ;

concatenate : concatenate unary     { $$ = Node::makeConcat(std::move($1), std::move($2)); }
            | unary                 { $$ = std::move($1); }
            ;

unary       : unary STAR            {
                                        $$ = Node::makeStar(std::move($1));
                                    }
            | unary QUESTION        {
                                        $$ = Node::makeQuestion(std::move($1));
                                    }
            | unary PLUS            {
                                        $$ = Node::makePlus(std::move($1));
                                    }
            | LPAREN regex RPAREN   {
                                        $$ = std::move($2);
                                    }
            | CHAR                  {
                                        $$ = Node::makeLetter(++nodeId, scanner.matched());
                                    }
            ;

This can be compiled with the invocation bisonc++ grammar.y and an explanation of the rules follows, almost all of which call a make... member of class Node, and all of which use std::move.

After rule regex there are three further rules to create a regex: disjuct which recognizes |, concatenate which does not have an associated operator, and unary which handles *, ? and +; the resulting grammar is unambiguous and creates no shift-reduce or reduce-reduce conflicts (which bisonc++ would warn about):

  1. unary STAR matches a trailing * for “zero-or-more”.
  2. unary QUESTION matches a trailing ? for “optional”, and sets nullable.
  3. unary PLUS matches a trailing + for “one-or-more”.
  4. concatenate unary handles concatenation.
  5. disjunct BAR concatenate is the only way for the diagram to bifurcate, matching an infix |.
  6. Parentheses are handled in the same way as for arithmetic expressions, as they provide syntactic grouping only.
  7. Encountering a single character increases the nodeId count and creates a letter node.

The scanner file scanner.l uses tokens generated from the parser file, but otherwise its implementation is simple:

letter  [a-z]
%%
{letter}    return Tokens::CHAR;
"+"         return Tokens::PLUS;
"*"         return Tokens::STAR;
"?"         return Tokens::QUESTION;
"|"         return Tokens::BAR;
"("         return Tokens::LPAREN;
")"         return Tokens::RPAREN;
.|\n        return Tokens::ERROR;

This file can be processed with the invocation flexc++ scanner.l.

Note that some hand-editing of the auto-generated Scanner.h, Parser.h and Parser.ih is necessary to allow the auto-generated files lex.cc and parser.cc to compile:

// Scanner.h
#include "Tokens.h"
// Parser.h
#include "Parserbase.h"
#include "Scanner.h"
#include "Node.h"

class Parser: public ParserBase
{

    public:
        Parser() = delete;
        Parser(Scanner& scanner, std::shared_ptr<Node>& nodes) : scanner{ scanner }, nodes{ nodes } {}
        int parse();

    private:
        Scanner& scanner;
        std::shared_ptr<Node>& nodes;
        int nodeId{ 0 };
// Parser.ih
#include "Node.h"
#include "Parser.h"

inline void Parser::error()
{
    std::cerr << "Bad regex.\n";
}

The driver reads strings of regexes from standard input and outputs GraphViz in textual format suitable for cut-and-pasting into a tool such as xdot:

#include "Node.h"
#include "Scanner.h"
#include "Parser.h"
#include <sstream>
#include <iostream>

int main(const int argc, const char **argv) {
    if (argc < 2) {
        std::cout << "Please enter a regex, or blank line to end:\n";
    }
    for (int arg = 1; (argc == 1) || (arg < argc); ) {
        std::string str;
        if (argc == 1) {
            getline(std::cin, str);
        }
        else {
            str = argv[arg++];
        }
        if (str.empty()) {
            return 0;
        }
        std::istringstream input(str);
        std::shared_ptr<Node> tree;
        Scanner scanner(input);
        Parser parser(scanner, tree);
        if (!parser.parse()) {
            std::cout << "digraph regex {\n  graph [label=\""
                << str << "\", root=q" << tree->getId()
                << ",  rankdir=LR, ranksep=0.6]\n"
                << "  node [shape=circle, fixedsize=true, width=0.4];\n\n";
            tree->visit(
                [](const Node& node){
                    if ((node.getType() == Node::NodeType::Letter)
                        || (node.getType() == Node::NodeType::Start)
                        || (node.getType() == Node::NodeType::Accept)) {
                            std::cout << "  q" << node.getId() << " [label=\"";
                            std::cout << node.getName() << "\"";
                            if ((node.getType() == Node::NodeType::Start)
                                || (node.getType() == Node::NodeType::Accept)) {
                                    std::cout << ", peripheries=2";
                            }
                            std::cout << "];\n";
                    }
                }
            );
            std::cout << '\n';
            tree->visit(
                [](const Node& node){
                    for (const auto& edge : node.getEdges()) {
                        std::shared_ptr<Node> target = edge.lock();
                        std::cout << "  q" << node.getId() << " -> q" << target->getId() << " [label=\"";
                        if (target->getType() == Node::NodeType::Letter) {
                            std::cout << target->getName();
                        }
                        else {
                            std::cout << "ε";
                        }
                        std::cout << "\"";
                        if (node.getId() == target->getId()) {
                            std::cout << ", dir=back";
                        }
                        std::cout << "];\n";
                    }
                }
            );
            std::cout << "}\n";
        }
    }
}

Use of getline() and an std::istringstream allows for end-of-input markers to be passed to the parser. After basic configuration options a list of nodes (q0, q1,…) with labels is output (not necessarily in order, but this is not a problem in practice), followed by a list of appropriately labelled edges from each node. Where a node has an edge back to itself (as for a+ or a*) the arrow direction is reversed.

With the fairly complex regex (ab)*(a|b)+a? (that is: zero or more abs, followed by either a or b one or more times, followed by an optional a) the output produced is as follows:

Edit: Compound disjunction-using regexes such as (a|b|c) now do display satisfactorily due to major changes to the Node class.

That’s all for this article, hopefully you’ll have become intrigued by the possibilities of using parser generators to solve programming challenges. It’s a form of functional programming, which might even generate an interest in true FP languages like Haskell. Source code for this article is available on GitHub.

Leave a Reply