Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

cpp-peglib

> 后端框架
Open source

A single file C++ header-only PEG (Parsing Expression Grammars) library

1.0K stars0 likes2 views
WebsiteGitHub

About

A single file C++ header-only PEG (Parsing Expression Grammars) library

cpp-peglib

C++17 header-only PEG (Parsing Expression Grammars) library. You can start using it right away just by including peglib.h in your project.

Since this library only supports C++17 compilers, please make sure that the compiler option -std=c++17 is enabled. (/std:c++17 /Zc:__cplusplus for MSVC)

You can also try the online version, PEG Playground at https://yhirose.github.io/cpp-peglib.

The PEG syntax is well described on page 2 in the document by Bryan Ford. cpp-peglib also supports the following additional syntax for now:

  • '...'i (Case-insensitive literal operator)
  • [...]i (Case-insensitive character class operator)
  • [^...] (Negated character class operator)
  • [^...]i (Case-insensitive negated character class operator)
  • {2,5} (Regex-like repetition operator)
  • `` (Token boundary operator)
  • ~ (Ignore operator)
  • \x20 (Hex number char)
  • \u10FFFF (Unicode char)
  • [\d\w\s], [\D\W\S] (Predefined character classes in a character class, ASCII semantics)
  • [[:alpha:]], [[:^alpha:]] (POSIX character classes in a character class, ASCII semantics: alnum, alpha, ascii, blank, cntrl, digit, graph, lower, print, punct, space, upper, word, xdigit)
  • %whitespace (Automatic whitespace skipping)
  • %word (Word expression)
  • $name( ... ) (Capture scope operator)
  • $name (Named capture operator)
  • $name (Backreference operator)
  • | (Dictionary operator)
  • ↑ (Cut operator)
  • MACRO_NAME( ... ) (Parameterized rule or Macro)
  • { precedence L - + L / * } (Parsing infix expression)
  • Left recursive rules (direct, indirect, and mutual left recursion)
  • %recovery( ... ) (Error recovery operator)
  • exp⇑label or exp^label (Syntax sugar for (exp / %recover(label)))
  • label { error_message "..." } (Error message instruction)
  • { no_ast_opt } (No AST node optimization instruction)
  • { no_whitespace } (Disable %whitespace skipping inside the rule)
  • { ast_name: NodeTag } (AST node name override instruction)

'End of Input' check will be done as default. To disable the check, please call disable_eoi_check.

This library supports the linear-time parsing known as the Packrat parsing. It also supports left recursive grammars (direct, indirect, and mutual) via a seed-growing algorithm, allowing natural expression of left-associative operators.

IMPORTANT NOTE for some Linux distributions such as Ubuntu and CentOS: Need -pthread option when linking. See #23, #46 and #62.

I am sure that you will enjoy this excellent "Practical parsing with PEG and cpp-peglib" article by bert hubert!

How to use

This is a simple calculator sample. It shows how to define grammar, associate semantic actions to the grammar, and handle semantic values.

…

The following example uses `` operator, which is token boundary operator.

cpp
peg::parser parser(R"(
  ROOT   _
  _     ();
};

parser["NUMBER"].predicate = [](const SemanticValues &vs,
                                const std::any & /*dt*/, std::string &msg) {
  if (vs.token_to_number() != 100) {
    msg = "value error!!";
    return false;
  }
  return true;
};

long val;
auto ret = parser.parse("100", val);
assert(ret == true);
assert(val == 100);

ret = parser.parse("200", val);
assert(ret == false);

The predicate can pass data to the action via predicate_data to avoid redundant computation:

…

enter and leave actions are also available.

cpp
parser["RULE"].enter = [](const Context &c, const char* s, size_t n, any& dt) {
  std::cout     # token boundary operator is used.
IDNET       # token boundary operator is used.

The following grammar accepts one, "two three", four.

ROOT         
PHRASE       

%whitespace  `)

Inside a token boundary, whitespace skipping is completely disabled. Character classes (`[...]`) and `.` never skip whitespace by themselves. Knowing these rules explains most surprises with `%whitespace`:

**A rule made only of character classes doesn't skip trailing whitespace.** ([#327](https://github.com/yhirose/cpp-peglib/issues/327)) With the grammar below, `main()` parses but `main ()` doesn't, because `NAME` is not a token — nothing skips the space after it. Wrap lexical rules in a token boundary.

DECL # OK: token boundary skips trailing whitespace


**A literal skips whitespace before a following predicate sees the input.** ([#319](https://github.com/yhirose/cpp-peglib/issues/319)) In `KEYWORD 
KEYWORD ` disables whitespace skipping for everything inside, and the inner one selects the text for `token()`:

StrQuot '"' >


**Rules whose name starts with `_` are hidden from error messages.** If you define `%whitespace` in terms of sub-rules (e.g. to support comments), name them with a leading `_`, otherwise syntax errors report `expecting ` instead of what the user actually needs to fix. ([#292](https://github.com/yhirose/cpp-peglib/issues/292))

%whitespace '>' ETAG ' TAG_NAME test text."); // OK parser.parse("This is a test text."); // NG parser.parse("This is a test text."); // NG


Dictionary
----------

`|` operator allows us to make a word dictionary for fast lookup by using Trie structure internally. We don't have to worry about the order of words.

```peg
START  _

Parsing infix expression by Precedence climbing

Regarding the precedence climbing algorithm, please see this article.

cpp
parser parser(R"(
  EXPRESSION             
  NUMBER                 
  %whitespace             long {
  auto result = any_cast(vs[0]);
  if (vs.size() > 1) {
    auto ope = any_cast(vs[1]);
    auto num = any_cast(vs[2]);
    switch (ope) {
      case '+': result += num; break;
      case '-': result -= num; break;
      case '*': result *= num; break;
      case '/': result /= num; break;
    }
  }
  return result;
};
parser["OPERATOR"] = [](const SemanticValues& vs) { return *vs.sv(); };
parser["NUMBER"] = [](const SemanticValues& vs) { return vs.token_to_number(); };

long val;
parser.parse(" -1 + (1 + 2) * 3 - -1", val);
assert(val == 9);

precedence instruction can be applied only to the following 'list' style rule.

Rule 
  %whitespace (vs[0]) + any_cast(vs[1]);
  case 1: return any_cast(vs[0]) - any_cast(vs[1]);
  default: return any_cast(vs[0]);
  }
};

parser["Term"] = [](const SemanticValues &vs) {
  switch (vs.choice()) {
  case 0: return any_cast(vs[0]) * any_cast(vs[1]);
  case 1: return any_cast(vs[0]) / any_cast(vs[1]);
  default: return any_cast(vs[0]);
  }
};

parser["Number"] = [](const SemanticValues &vs) {
  return vs.token_to_number();
};

long val;
parser.parse("1 - 2 - 3", val);
assert(val == -4);  // Left-associative: (1-2)-3 = -4

parser.parse("8 / 4 / 2", val);
assert(val == 1);   // Left-associative: (8/4)/2 = 1

Direct, indirect, and mutual left recursion are all supported. For example, indirect left recursion works as expected:

peg
A  nodes;  // child nodes
std::weak_ptr     parent;

To walk the tree, switching on tag avoids string comparison. The _ literal in peg::udl turns a node name into the same compile-time tag value:

cpp
using namespace peg::udl;

void traverse(const std::shared_ptr &ast) {
  switch (ast->tag) {
  case "Additive"_: /* ... */ break;
  case "Number"_:   /* ... */ break;
  default:
    for (auto &node : ast->nodes) { traverse(node); }
    break;
  }
}

See actual usages in the AST calculator example and PL/0 language example.

Make a parser with parser combinators

Instead of making a parser by parsing PEG syntax text, we can also construct a parser by hand with parser combinators. Here is an example:

cpp
using namespace peg;
using namespace std;

vector tags;

Definition ROOT, TAG_NAME, _;
ROOT      size_t {
      static vector names = { "PEG", "BNF" };
      for (const auto& name: names) {
        if (name.size() ` earlier in the parse (an unknown name expands to an empty string):

…


As you can see, it can now show more than one error, and provide more meaningful error messages than the default messages.

### Custom error message for definitions

We can associate custom error messages to definitions.

```peg
# custom_message.peg
START        { error_message 'code format error...' }
%whitespace  cat custom_message.txt
0x1234,0x@@@@,0xABCD

> peglint custom_message.peg custom_message.txt
custom_message.txt:1:8: code format error...

NOTE: If there is more than one element with an error message instruction in a prioritized choice, this feature may not work as you expect.

Structured error reports

set_logger receives errors as formatted strings. To build tooling on top of the parser — error codes, localized messages, IDE diagnostics — use set_error_reporter instead, which receives the same errors as structured data before they are flattened into a display string:

cpp
parser.set_error_reporter([](const peg::ErrorReport &r) {
  // r.line, r.col          : 1-based error position
  // r.position             : byte offset in the input
  // r.unexpected_token     : the token found at the error position
  // r.expected_literals    : e.g. {"}", ";"}
  // r.expected_rules       : e.g. {"NAME"} (rules starting with '_' excluded)
  // r.message              : custom error_message if any (placeholders resolved)
  // r.label                : rule name or recovery label the error belongs to
});

Both callbacks can be set at the same time; each error is delivered to both. With error recovery, the reporter is called once per recovered error, so a single parse can produce multiple reports. Mapping r.label to an application-defined error enum is the intended way to get typed errors.

Change the Start Definition Rule

We can change the start definition rule as below.

cpp
auto grammar = R"(
  Start        cd lint
> mkdir build
> cd build
> cmake ..
> make
> ./peglint
usage: grammar_file_path [source_file_path]

  options:
    --source: source text
    --packrat: enable packrat memoise
    --ast: show AST tree
    --opt, --opt-all: optimize all AST nodes except nodes selected with `no_ast_opt` instruction
    --opt-only: optimize only AST nodes selected with `no_ast_opt` instruction
    --trace: show concise trace messages
    --profile: show profile report
    --verbose: verbose output for trace and profile

Grammar check

> cat a.peg
Additive     peglint a.peg
[commandline]:3:35: 'Number' is not defined.

Source check

> cat a.peg
Additive    
%whitespace  peglint --source "1 + a * 3" a.peg
[commandline]:1:3: syntax error

Serialize a grammar for fast startup

A compiled grammar can be serialized to a portable byte blob and later restored without re-running the meta-parse. Deserializing a blob is roughly 40x faster than load_grammar, so an application can embed a prebuilt blob and skip the grammar parsing on startup.

cpp
peg::parser parser(R"(
  ROOT  blob = parser.serialize_grammar();

// ...store/embed the blob, then later:

peg::parser parser2;
parser2.load_blob(blob); // skips the meta-parse

// Re-apply semantic actions / enable_ast() etc. as needed:
parser2["TOKEN"] =

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C++c-plus-pluscppcpp17header-only

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架