Parsing with Boost Spirit X3
Channel: Utah Cpp Programmers
Date: 2023-09-14

Almost 10 years ago, we looked at Spirit 2.x for parsing. Since that time the Spirit library has evolved to Spirit X3, a C++14 version of Spirit that is "an object-oriented, recursive-descent parser for C++". Spirit X3 is a header-only library that allows you to write your grammar directly in C++ using the mechanism of expression templates. When expressed as a Spirit X3 grammar in C++, the resulting code closely resembles BNF (Backus-Naur Form) representations of a grammar.

The common result of parsing a piece of text is an abstract syntax tree (AST) that represents the structure parsed from the input. Spirit has a rich system of attribute synthesis that can be used to build the AST directly during parsing. The application uses the resulting AST from parsing to perform some function. In a compiler, the AST is used to generate code in some form for the target processor.

This month, Richard Thomson will give us a refresher on parsing with Spirit X3. Along the way we'll look at the following topics:

- How to parse basic primitive values (float, int, string, etc.)
- How to combine primitive parsers to handle complex sequences and structures
- How to add error handling to the parse process
- How to annotate parsed elements with the location in the source input for better error messages
- How to customize the parsing process with a custom AST data structure
- How to traverse the custom AST using the Visitor pattern

Example code: https://github.com/LegalizeAdulthood/spirit-x3-examples

Past topics: https://utahcpp.wordpress.com/past-meeting-topics/
Future topics: https://utahcpp.wordpress.com/future-meeting-topics/
Meetup: https://www.meetup.com/utah-cpp-programmers/