Skip to content

Interpreter

Difficulty: Advanced

Prerequisites

Key concepts

  • interpreter pattern
  • abstract syntax tree
  • grammar
  • recursive descent
  • operator precedence
  • What the Interpreter pattern is for: a small language whose sentences your program must understand, such as rules, filters, or search queries.
  • How each rule of the language becomes a class, so that one sentence becomes a tree of objects that can be evaluated.
  • How a small parser turns text into that tree, and why the parser must refuse bad input, including input that is too large.
  • When a table, a library, or a real scripting language is a better choice, and why this pattern is rare in practice.

An online shop runs promotions. The marketing team writes the rule for each promotion in a configuration file, and the program decides which promotions apply to an order. An order is described by a set of facts that are true for it: member, staff, first_order, express, heavy, gift, suspended.

  1. FR-1 A rule combines facts with and, or, not, and parentheses, for example: (member or staff) and (express or gift) and not suspended.
  2. FR-2 Rules change without rebuilding the program: they are read as text when it starts.
  3. FR-3 A rule with a mistake, such as a misspelled fact or a missing parenthesis, is refused when it is loaded, with a message that says where the mistake is. It must not quietly evaluate to false for every order.
  4. FR-4 The program can show each rule as it understood it, with the grouping made explicit, so that the team can check it.
  5. C-1 (constraint) The configuration is written by people, not checked by a compiler: a rule may be very long or deeply nested by mistake, and the program must not crash on it.

Before writing a language, try a table. Each row says “all of these facts are true, and none of these are”; a promotion with several rows applies if any of its rows does.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.hpp
namespace before {
// One row: the rule applies if all of `all_of` are true and none of
// `none_of` are. A rule with several rows applies if any row does.
// So a table can say "this and this, but not that" in one row, and "or"
// only by adding more rows. A rule such as "(member or staff) and
// (express or gift)" needs one row for each combination: 2 x 2 = 4.
struct Row {
std::string rule;
std::vector<std::string> all_of;
std::vector<std::string> none_of;
};
// True if any row named `rule` applies to an order whose true facts are
// `true_facts`. An unknown rule name (or a misspelled fact) is not an
// error here: no row matches, so the answer is simply false.
bool applies(const std::vector<Row>& table, std::string_view rule,
const rules::Names& true_facts);
// How many rows the table spends on `rule`.
std::size_t rows_for(const std::vector<Row>& table, std::string_view rule);
} // namespace before

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Each row is {rule name, facts that must be true, facts that must be
// false}. free_shipping ("member and not heavy, or staff") takes two
// rows. gift_wrap ("member or staff", and "express or gift", and not
// suspended) takes four: one per pair of choices, each repeating
// "not suspended".
const std::vector<before::Row> table{
{"free_shipping", {"member"}, {"heavy"}},
{"free_shipping", {"staff"}, {}},
{"welcome_discount", {"first_order"}, {"suspended"}},
{"gift_wrap", {"member", "express"}, {"suspended"}},
{"gift_wrap", {"member", "gift"}, {"suspended"}},
{"gift_wrap", {"staff", "express"}, {"suspended"}},
{"gift_wrap", {"staff", "gift"}, {"suspended"}},
};
std::cout << "before: gift_wrap needs " << before::rows_for(table, "gift_wrap")
<< " rows in the table\n";

A table like this is easy to store, to edit in a spreadsheet or an admin page, and to check. It can even express every rule made of and, or, and not: any such rule can be rewritten as “this combination, or that one, or that one”. So it works. Its problem is size, and what size does to the people reading it:

  • Rows multiply. (member or staff) and (express or gift) is two choices times two choices, so four rows. Add a third “either of two” condition and it is eight. The short rule the team had in mind is gone; what is left is its expansion.
  • The rule is spread over rows. To change “express or gift” to “express or gift or fragile”, someone must work out that this means two new rows, one for each of the member and staff choices; to drop gift, they must find and delete the two rows that came from it. Either way they edit the expansion, not the rule.
  • Nothing in the table checks the fact names (FR-3). A row with "memebr" is never true, and nothing says so.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_interpreter.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false. LLD_CHECK_EQ(actual, expected) does the same
// for actual == expected and also prints both values when they differ.
// They come from the site's small test header, lld_test.hpp.
//
// One "or" inside each of two groups already costs four rows. The two
// checks show the table working (staff + gift matches the last row) and
// a near miss (staff without express or gift matches none).
LLD_TEST(before_a_table_needs_a_row_for_every_combination) {
// (member or staff) and (express or gift): 2 x 2 = 4 rows.
const std::vector<before::Row> table{
{"r", {"member", "express"}, {}},
{"r", {"member", "gift"}, {}},
{"r", {"staff", "express"}, {}},
{"r", {"staff", "gift"}, {}},
};
LLD_CHECK(before::applies(table, "r", {"staff", "gift"}));
LLD_CHECK(!before::applies(table, "r", {"staff", "member"}));
// 4u is an unsigned 4, the same kind of number rows_for returns.
LLD_CHECK_EQ(before::rows_for(table, "r"), 4u);
}

If your rules are flat (“all of these, none of those”) the table is the right design, and you should stop here. The rest of this page is for rules that nest.

Interpreter represents each rule of a small language’s grammar as a class. A sentence in the language becomes a tree of objects of those classes, and the sentence is evaluated by asking the root of the tree, which asks its children.

The language here has a grammar: the rules that say which sentences are valid and how they group. In words: a rule is one or more and-groups joined by or; an and-group is one or more not-terms joined by and; a not-term is either not followed by another not-term, or a fact, or a whole rule in parentheses. That order is what makes not bind tightest and or loosest, as in most programming languages.

Its participants:

  • The abstract expression: the interface of every node, here Expression, with evaluate.
  • Terminal expressions: the leaves, which hold no other expressions. Here, Fact.
  • Nonterminal expressions: nodes that combine others, one class per grammar rule that combines. Here, Not, And, and Or.
  • The context: the information that evaluation reads. Here, the set of facts that are true for one order.
  • The client builds or receives the tree and evaluates it. Here, RuleSet, using a parser to build the trees.

The tree is often called an abstract syntax tree: “abstract” because it keeps the structure of the sentence (what groups with what) and drops the spelling (spaces, parentheses).

One class per grammar rule; And, Or, and Not own their operands
Text description of the diagram

A class diagram. Expression is abstract, with evaluate, which takes the set of true facts and returns a bool, and describe, which returns a string. Four classes derive from it: Fact, which holds a name; Not, which holds one operand; and And and Or, which each hold a left and a right operand. Filled-diamond lines from Not, And, and Or back to Expression show that each owns its operands: one for Not, two for And and Or. RuleSet holds the set of known fact names and a vector of rules, has add, which takes a name and the rule’s text, and matching, which takes the true facts and returns the names of the rules that apply. A filled-diamond line from RuleSet to Expression shows that it owns one tree per rule, through each Rule.

Diagram source (Mermaid)
classDiagram
class Expression {
  <<abstract>>
  +evaluate(true_facts) bool
  +describe() string
}
class Fact {
  -string name_
}
class Not {
  -ExpressionPtr operand_
}
class And {
  -ExpressionPtr left_
  -ExpressionPtr right_
}
class Or {
  -ExpressionPtr left_
  -ExpressionPtr right_
}
class RuleSet {
  -Names known_
  -vector~Rule~ rules_
  +add(name, text) void
  +matching(true_facts) vector~string~
}
Expression <|-- Fact
Expression <|-- Not
Expression <|-- And
Expression <|-- Or
Not *-- "1" Expression : operand_
And *-- "2" Expression : left_, right_
Or *-- "2" Expression : left_, right_
RuleSet *-- "0..*" Expression : one tree per rule

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

expression.hpp
// A set of fact names. For one order, it holds the facts that are true;
// every other known fact is false.
// `using` gives the type a short name. std::set keeps the names sorted
// with no duplicates. std::less<> (with empty brackets) lets the set
// compare a stored std::string with a std::string_view directly, so
// contains(word) can look up a piece of text without first copying it
// into a new std::string.
using Names = std::set<std::string, std::less<>>;
// One node of a rule's tree. A rule is evaluated by asking its root.
// It is the interface every node type implements: a fact, a not, an and,
// or an or. Each node answers two questions about itself: is it true for
// this order (evaluate), and how is it written (describe).
class Expression {
public:
// Virtual, so that deleting a node through an ExpressionPtr (a pointer
// to the base class) runs the right derived destructor too.
virtual ~Expression() = default;
// No copying: nodes live in a tree and are handled through pointers.
// A copy through the base class would slice off the derived part.
Expression(const Expression&) = delete;
Expression& operator=(const Expression&) = delete;
// `= 0` makes these pure virtual: Expression has no body for them, and
// each node class must supply its own. The facts that are true for one
// order come in as a parameter, so the same tree can answer for many
// orders. Both are const: evaluating or describing changes nothing.
[[nodiscard]] virtual bool evaluate(const Names& true_facts) const = 0;
[[nodiscard]] virtual std::string describe() const = 0;
protected:
// Protected: only the node classes deriving from Expression can call
// it, so nobody creates a bare Expression.
Expression() = default;
};
// The owning pointer to a node. unique_ptr: exactly one owner, and the
// node is deleted when its owner goes away. Deleting a parent therefore
// deletes its whole subtree. `const Expression`: once built, a node
// cannot be changed through this pointer.
using ExpressionPtr = std::unique_ptr<const Expression>;

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

expression.hpp
// The four node types, one per piece of the rule language. `final` means
// no class may derive from them. A Fact is a leaf: it holds a name and no
// children. Not owns one child; And and Or own two. Each child is an
// ExpressionPtr, so a parent owns its children outright.
class Fact final : public Expression {
public:
explicit Fact(std::string name);
bool evaluate(const Names& true_facts) const override;
std::string describe() const override;
private:
std::string name_;
};
// "not X": true when X is false.
class Not final : public Expression {
public:
explicit Not(ExpressionPtr operand);
bool evaluate(const Names& true_facts) const override;
std::string describe() const override;
private:
ExpressionPtr operand_;
};
// "left and right": true when both are. Or below is the same shape.
class And final : public Expression {
public:
And(ExpressionPtr left, ExpressionPtr right);
bool evaluate(const Names& true_facts) const override;
std::string describe() const override;
private:
ExpressionPtr left_;
ExpressionPtr right_;
};
class Or final : public Expression {
public:
Or(ExpressionPtr left, ExpressionPtr right);
bool evaluate(const Names& true_facts) const override;
std::string describe() const override;
private:
ExpressionPtr left_;
ExpressionPtr right_;
};
  • Expression is an interface for nodes owned through a pointer. Copying is deleted, so a node cannot be sliced or copied by mistake, and the destructor is virtual, because trees delete nodes through ExpressionPtr.
  • ExpressionPtr is std::unique_ptr<const Expression>. Each node owns its children, and the tree is a tree, not a graph: no node has two parents. The const means that once a tree is built, nobody can change it.
  • The context is a parameter, not a member. evaluate takes the true facts each time, so one tree can be evaluated for many orders. It is const, and the nodes keep no state that changes, so several threads may evaluate the same tree at the same time, as long as nothing modifies it.
  • Each concrete class is final. These are the grammar’s rules, and nothing should change what and means by deriving from And.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

expression.cpp
// A fact is true for an order exactly when its name is in the order's set
// of true facts. The name is taken by value and moved into name_ (no second
// copy). Throws std::invalid_argument for an empty name.
Fact::Fact(std::string name) : name_{std::move(name)} {
if (name_.empty()) {
throw std::invalid_argument("a fact needs a name");
}
}
bool Fact::evaluate(const Names& true_facts) const {
return true_facts.contains(name_);
}
std::string Fact::describe() const { return name_; }
// `require` (a small helper earlier in this file) throws
// std::invalid_argument if the pointer is null, and otherwise hands it
// straight back. std::move passes ownership of the child along: a
// unique_ptr cannot be copied, only moved. So every Not that exists has a
// child, and Not now owns it.
Not::Not(ExpressionPtr operand) : operand_{require(std::move(operand))} {}
// Ask the child, then flip the answer. `->` calls through the pointer.
bool Not::evaluate(const Names& true_facts) const {
return !operand_->evaluate(true_facts);
}
std::string Not::describe() const { return "not " + operand_->describe(); }
// Both children are required. If `right` is null, require throws after
// left_ was set; left_ is then destroyed, so its subtree is not leaked.
And::And(ExpressionPtr left, ExpressionPtr right)
: left_{require(std::move(left))}, right_{require(std::move(right))} {}
// Recursion: each child evaluates its own subtree the same way. `&&`
// stops early: if the left side is false, the right side is never asked.
bool And::evaluate(const Names& true_facts) const {
return left_->evaluate(true_facts) && right_->evaluate(true_facts);
}
// Brackets round every and, so the grouping is always visible.
std::string And::describe() const {
return "(" + left_->describe() + " and " + right_->describe() + ")";
}
Or::Or(ExpressionPtr left, ExpressionPtr right)
: left_{require(std::move(left))}, right_{require(std::move(right))} {}
// `||` stops early too: if the left side is true, the right is skipped.
bool Or::evaluate(const Names& true_facts) const {
return left_->evaluate(true_facts) || right_->evaluate(true_facts);
}
std::string Or::describe() const {
return "(" + left_->describe() + " or " + right_->describe() + ")";
}
How this code works: Evaluating one rule for one order

The rule free_shipping is member and not heavy or staff. The parser turns it into this tree: an Or whose left child is And(Fact member, Not(Fact heavy)) and whose right child is Fact staff. Take the first order in main.cpp, whose true facts are member and express.

  1. matching calls evaluate on the root, the Or.
  2. Or::evaluate asks its left child first: the And.
  3. And::evaluate asks its left child, Fact member. member is in the set, so it answers true.
  4. Because the left side was true, && goes on and the And asks its right child, the Not. The Not asks Fact heavy, which answers false (heavy is not in the set), and flips it to true.
  5. The And has true and true, so it returns true to the Or.
  6. The Or’s left side is true, so || stops there: Fact staff is never asked. The rule matches.

Now the third order: express, heavy, staff, suspended. In step 3, Fact member answers false, so && stops and the And returns false without asking the Not. The Or then asks its right side, Fact staff, which is true. Both orders get free shipping, as the output shows.

Every answer was produced by one small evaluate asking its children and combining their answers. No node knows the whole rule.

  • Each node does one small thing. A Fact looks itself up; Not negates its operand; And and Or combine their two. The meaning of a whole rule comes from the shape of the tree.
  • && and || stop early. And does not evaluate its right operand if the left one is false. Here that only saves time; in a language whose leaves have effects, it would change behaviour, and you would need to decide whether you want it.
  • Constructors refuse null operands, so every tree that exists is complete.
  • describe adds parentheses around every and and or (FR-4). It is a second operation over the same tree, which matters for adding operations.
The tree for (member or staff) and (express or gift) and not suspended
Text description of the diagram

A tree for the gift-wrap rule. The root is an And node. Its left child is another And node, and its right child is a Not node, whose single child is the fact suspended. The inner And node has two Or nodes as children: the first Or has the facts member and staff, and the second has express and gift. Because the parser joins a chain of ands from the left, the first two groups are combined first, and the not-suspended term is joined to that result at the root.

Diagram source (Mermaid)
flowchart TD
A2["And"] --> A1["And"]
A2 --> N["Not"]
N --> S["Fact: suspended"]
A1 --> O1["Or"]
A1 --> O2["Or"]
O1 --> M["Fact: member"]
O1 --> ST["Fact: staff"]
O2 --> E["Fact: express"]
O2 --> G["Fact: gift"]

To evaluate the rule for an order, the program calls evaluate on the root. The root asks its left child, which asks the first Or and, only if that is true, the second; each Or stops at its first true fact. Then, if the left side was true, the root asks the Not node. Each question is answered by one small class.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

parser.hpp
// Thrown for a rule that does not follow the grammar. position() is the
// index in the text where the problem was found.
// Index 0 is the first character. Deriving from std::runtime_error gives
// it what(), the message, which also ends with " at position N".
class ParseError : public std::runtime_error {
public:
ParseError(const std::string& message, std::size_t position);
std::size_t position() const noexcept { return position_; }
private:
std::size_t position_;
};
// Grammar, loosest first:
// (Read := as "is made of", { ... } as "repeated zero or more times", | as
// "or", and quoted words as literal text. The lower a line, the tighter
// it binds: "not" before "and", "and" before "or".)
// rule := and_rule { "or" and_rule }
// and_rule := not_rule { "and" not_rule }
// not_rule := "not" not_rule | primary
// primary := fact | "(" rule ")"
// A fact must be one of `known`. Text longer than max_length, or nested
// deeper than max_depth, is refused, so a rule's tree stays small.
// `inline constexpr`: compile-time constants that every file including
// this header shares as one definition.
inline constexpr std::size_t max_length = 1000;
inline constexpr int max_depth = 50;
// Turns rule text into a tree and returns its root, which the caller now
// owns. Throws ParseError if the text is too long, too deep, names an
// unknown fact, or breaks the grammar; no tree is returned in that case.
[[nodiscard]] ExpressionPtr parse(std::string_view text, const Names& known);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

parser.cpp
// A recursive-descent parser: one function per grammar line. It turns
// text into a tree; it does not evaluate anything.
// It reads the text left to right with one index, position_. Each
// parse_ function reads the longest piece of text its grammar line
// allows, starting at position_, leaves position_ just after it, and
// returns the tree for that piece. A function for a looser line calls the
// one for the next tighter line to read each of its parts. Any error
// throws ParseError at once. The `depth` parameter counts how many "not"s
// and "("s enclose the current point, to refuse very deep nesting.
//
// The helpers it uses (defined after this excerpt): skip_spaces() moves
// past spaces; read_word() reads the run of lowercase letters and _ at
// position_ (maybe empty); accept_word(word) and accept_char(ch) skip
// spaces, then consume that word or character and return true if it comes
// next, or otherwise leave the rest unread and return false.
class Parser {
public:
// Keeps a view of the text and a reference to the known facts; it
// copies neither, so both must outlive the parser. parse() below
// uses it within one expression, so they do.
Parser(std::string_view text, const Names& known) : text_{text}, known_{known} {}
// Parse one whole rule, then insist that nothing but spaces is left:
// "member staff" reads "member", stops at "staff", and is refused here.
ExpressionPtr parse_all() {
ExpressionPtr result = parse_rule(0);
skip_spaces();
if (position_ != text_.size()) {
throw ParseError{"expected \"and\", \"or\", or the end", position_};
}
return result;
}
private:
// rule := and_rule { "or" and_rule }
// Read one and_rule; then, for each "or" that follows, read the next
// and_rule and join the two under a new Or node. The new node takes
// ownership of the tree so far (std::move(left)) and becomes `left`,
// so "a or b or c" builds Or(Or(a, b), c): grouped from the left.
// std::move only marks `left` as movable; the move happens inside the
// Or constructor, after parse_and has returned. If parse_and throws,
// `left` still owns its tree and frees it as the exception passes.
ExpressionPtr parse_rule(int depth) {
ExpressionPtr left = parse_and(depth);
while (accept_word("or")) {
left = std::make_unique<Or>(std::move(left), parse_and(depth));
}
return left;
}
// and_rule := not_rule { "and" not_rule }, built the same way as above.
// Because parse_rule calls this for each side of an "or", every "and"
// is grouped before the "or"s around it.
ExpressionPtr parse_and(int depth) {
ExpressionPtr left = parse_not(depth);
while (accept_word("and")) {
left = std::make_unique<And>(std::move(left), parse_not(depth));
}
return left;
}
// not_rule := "not" not_rule | primary
// After a "not", call this function again, one level deeper, for what
// it negates; so "not not x" is Not(Not(x)). check_depth throws once
// depth passes max_depth.
ExpressionPtr parse_not(int depth) {
check_depth(depth);
if (accept_word("not")) {
return std::make_unique<Not>(parse_not(depth + 1));
}
return parse_primary(depth);
}
// primary := fact | "(" rule ")"
// Either a whole rule in brackets (start again from the loosest line,
// one level deeper) or a single fact name.
ExpressionPtr parse_primary(int depth) {
skip_spaces();
if (accept_char('(')) {
ExpressionPtr inner = parse_rule(depth + 1);
if (!accept_char(')')) {
throw ParseError{"expected \")\"", position_};
}
return inner; // the brackets leave no node: they only group
}
// Remember where the word starts, so an error can point at it.
const std::size_t start = position_;
const std::string_view word = read_word();
// No word here (the end of the text, or a character such as ")", a
// digit, or a capital letter), or a keyword where a fact should be,
// as in "member and or staff".
if (word.empty() || is_keyword(word)) {
throw ParseError{"expected a fact or \"(\"", start};
}
// A misspelled or unknown fact is refused now, at load time.
if (!known_.contains(word)) {
throw ParseError{"unknown fact \"" + std::string{word} + "\"", start};
}
// std::string{word} copies the text out of the view: the Fact must
// keep its own name, because the rule text may not outlive it.
return std::make_unique<Fact>(std::string{word});
}
How this code works: Parsing member and not heavy or staff

Each step names the function that is running, what it reads, and what it returns. The depth stays 0 except inside the not.

  1. parse_all calls parse_rule(0), which calls parse_and(0), which calls parse_not(0).
  2. parse_not(0): accept_word("not") reads member, which is not not, so it puts the position back. parse_primary finds no (, reads the word member, checks that it is known, and returns Fact member.
  3. Back in parse_and: accept_word("and") succeeds. It calls parse_not(0) for the right side.
  4. This time accept_word("not") succeeds, so parse_not(1) is called. It reads heavy and returns Fact heavy. The outer call wraps it: Not(Fact heavy).
  5. parse_and builds And(Fact member, Not(Fact heavy)), which becomes its new left. The next word is or, not and, so accept_word puts the position back and the loop ends. parse_and returns the And tree.
  6. Back in parse_rule: accept_word("or") succeeds. It calls parse_and(0), which (through parse_not and parse_primary) returns Fact staff. parse_rule builds Or(And(...), Fact staff).
  7. accept_word("or") finds the end of the text, so the loop ends and parse_rule returns the Or.
  8. parse_all skips spaces, sees that the position is at the end of the text, and returns the tree.

Its describe() is ((member and not heavy) or staff), the first rule line of the output. The and was grouped first only because parse_rule asked parse_and for a whole side before it looked for or.

An error stops everything at once. In member and or staff, step 3 calls parse_not after the and. It reads the word or at index 11. That is a keyword, so parse_primary throws ParseError with position 11, and no tree is returned. Any nodes already built are owned by local ExpressionPtr variables, which free them as the exception passes.

This is a recursive-descent parser: one function per line of the grammar, each calling the functions for the lines below it.

  • Precedence comes from which function calls which. parse_rule handles or and calls parse_and for each side, so an and is always grouped before the or around it. not is handled lowest down, so it binds tightest.
  • Loops make and and or group from the left. a or b or c becomes ((a or b) or c). For and and or the grouping does not change the answer, but it does change the tree’s shape.
  • Words are matched whole. accept_word("or") reads the whole next word and compares it, so a fact called order is never mistaken for or followed by der.
  • Fact names are checked against the known list while parsing (FR-3). A misspelled fact is an error at load time, not a rule that is never true. Because of that check, evaluation can safely treat “not in the set of true facts” as false. (The facts passed to evaluate are not checked; that is the caller’s job.) A fact name is made of lowercase letters and _ only, so Member and a2 are refused.
  • Errors carry a position. ParseError::position() is the zero-based index in the text where the problem was found, and the message includes it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

rule_set.hpp
// Named rules over a fixed vocabulary of facts, as loaded from configuration.
// This is the pattern's client: it parses each rule once, keeps the tree,
// and asks every tree about each order. `known` is the list of fact names
// a rule may use.
class RuleSet {
public:
explicit RuleSet(Names known) : known_{std::move(known)} {}
// Copying is deleted (each tree has one owner); moving is allowed,
// and hands the trees over to the new RuleSet.
RuleSet(const RuleSet&) = delete; // owns trees
RuleSet& operator=(const RuleSet&) = delete;
RuleSet(RuleSet&&) = default;
RuleSet& operator=(RuleSet&&) = default;
// Throws ParseError, and adds nothing, if `text` is not a valid rule.
void add(std::string name, std::string_view text);
// The names of the rules that are true for one order, in the order the
// rules were added.
[[nodiscard]] std::vector<std::string> matching(const Names& true_facts) const;
// One "name = fully bracketed rule" line per rule, from describe().
[[nodiscard]] std::vector<std::string> descriptions() const;
private:
// One rule: its name and the root of its tree, which it owns.
struct Rule {
std::string name;
ExpressionPtr condition;
};
Names known_;
std::vector<Rule> rules_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

rule_set.cpp
// Parse first, change second: if parse throws, rules_ is untouched. Then
// the name and the tree are both moved into a new Rule at the end of
// rules_ (the tree cannot be copied, only moved).
void RuleSet::add(std::string name, std::string_view text) {
ExpressionPtr condition = parse(text, known_); // may throw; nothing added yet
rules_.push_back(Rule{std::move(name), std::move(condition)});
}
// Ask each tree's root about this order; evaluate works down the tree.
// The names are copied into the result, so it does not depend on the
// RuleSet staying alive.
std::vector<std::string> RuleSet::matching(const Names& true_facts) const {
std::vector<std::string> names;
for (const Rule& rule : rules_) {
if (rule.condition->evaluate(true_facts)) {
names.push_back(rule.name);
}
}
return names;
}
  • add parses before it changes anything. If the text is bad, parse throws and rules_ is untouched.
  • RuleSet owns its trees, inside Rule. Because ExpressionPtr is a unique_ptr, Rule is movable but not copyable. RuleSet says so explicitly, by deleting its copy operations: without that, the compiler would still declare a copy constructor, and a copy would fail only when used, with an error deep inside the standard library.

class Expression

abstract; owned through ExpressionPtr

Member functions

  • virtual bool evaluate(const Names& true_facts) const = 0;
  • virtual std::string describe() const = 0; parenthesises every and/or
  • virtual ~Expression() = default;

class Fact final

terminal: a leaf

Data members

  • std::string name_;

Member functions

  • explicit Fact(std::string name); throws std::invalid_argument if empty
  • bool evaluate(const Names& true_facts) const override;

class Not final

nonterminal

Data members

  • ExpressionPtr operand_;

Member functions

  • explicit Not(ExpressionPtr operand); throws std::invalid_argument if null
  • bool evaluate(const Names& true_facts) const override;

class And final

nonterminal; Or is the same shape

Data members

  • ExpressionPtr left_;
  • ExpressionPtr right_;

Member functions

  • And(ExpressionPtr left, ExpressionPtr right); throws std::invalid_argument if null
  • bool evaluate(const Names& true_facts) const override; stops early on false

class RuleSet

the client

Data members

  • Names known_; the facts a rule may name
  • std::vector<Rule> rules_;

Member functions

  • explicit RuleSet(Names known);
  • void add(std::string name, std::string_view text); throws ParseError; adds nothing
  • std::vector<std::string> matching(const Names& true_facts) const;
  • std::vector<std::string> descriptions() const;
The expression nodes, the parser's entry point, and the rule set

The outline leaves out Or (the same shape as And), the describe overrides, ParseError, the free function parse, and the Rule struct.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// The inner braces build the Names set of every fact a rule may use.
rules::RuleSet promotions{
{"member", "staff", "first_order", "express", "heavy", "gift", "suspended"}};
// Each add parses the text into a tree once; the trees are reused below.
promotions.add("free_shipping", "member and not heavy or staff");
promotions.add("welcome_discount", "first_order and not suspended");
promotions.add("gift_wrap", "(member or staff) and (express or gift) and not suspended");
std::cout << "rules:\n";
for (const std::string& line : promotions.descriptions()) {
std::cout << " " << line << '\n';
}
// For each order (its set of true facts, defined above this excerpt),
// print its facts and the rules that match it. join (a small helper in
// this file) glues strings together with a separator; the braces build
// a temporary vector from the set, whose names come out sorted.
for (const rules::Names& order : orders) {
std::cout << join({order.begin(), order.end()}, ", ") << ": "
<< join(promotions.matching(order), " ") << '\n';
}
// Three broken rules. Each add throws ParseError before anything is
// added, so the rule set is unchanged; catch prints the reason, which
// what() returns with the position.
for (const char* bad : {"member and or staff", "vip or staff", "(member or staff"}) {
try {
promotions.add("broken", bad);
} catch (const rules::ParseError& e) {
std::cout << "refused \"" << bad << "\": " << e.what() << '\n';
}
}
Expected output
before: gift_wrap needs 4 rows in the table
rules:
free_shipping = ((member and not heavy) or staff)
welcome_discount = (first_order and not suspended)
gift_wrap = (((member or staff) and (express or gift)) and not suspended)
express, member: free_shipping gift_wrap
first_order, gift, heavy: welcome_discount
express, heavy, staff, suspended: free_shipping
first_order, member, suspended: free_shipping
refused "member and or staff": expected a fact or "(" at position 11
refused "vip or staff": unknown fact "vip" at position 0
refused "(member or staff": expected ")" at position 16
the table and the rules agree on 4 of 4 orders

Read the output against the requirements:

  • The descriptions show the grouping (FR-4). member and not heavy or staff is understood as ((member and not heavy) or staff), which is what the team meant: staff get free shipping even for heavy orders.
  • Each order gets the promotions its facts allow (FR-1). The staff order is suspended, so it gets no gift wrap, but free shipping only asks about member, heavy, and staff, so it still applies.
  • Three bad rules are refused, each with a position (FR-3): an or where a fact should be, a misspelled or unknown fact, and a missing ) at the end of the text.
  • The last line compares the two designs. For all four orders, the table and the parsed rules pick the same promotions; the difference between them is how the rules are written and checked, not what they can express.

The program writes its rules into the source to stay self-contained; in the real program they would be read from the configuration file (FR-2).

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_interpreter.cpp
// No parser: the tree for "member and not heavy" is built directly from
// nodes. Each make_unique creates a node and returns the ExpressionPtr
// that owns it; And takes ownership of both children. The order
// {"member"} is true, {"member", "heavy"} is not, and describe() shows
// the brackets the And node adds.
LLD_TEST(a_tree_built_by_hand_evaluates_like_the_text) {
using namespace rules; // lets the test write And, Fact, Not without rules::
// member and not heavy
const And rule{std::make_unique<Fact>("member"),
std::make_unique<Not>(std::make_unique<Fact>("heavy"))};
LLD_CHECK(rule.evaluate({"member"}));
LLD_CHECK(!rule.evaluate({"member", "heavy"}));
LLD_CHECK_EQ(rule.describe(), std::string{"(member and not heavy)"});
}
// The describe() output shows how the parser grouped the text. With only
// "member" true, "member or (staff and heavy)" is true, but the version
// with explicit brackets, "(member or staff) and heavy", is false, so the
// grouping really changes the answer. eval is a small helper at the top
// of the test file: it parses the text and evaluates the tree at once.
LLD_TEST(and_binds_tighter_than_or_and_not_tightest) {
LLD_CHECK_EQ(rules::parse("member or staff and heavy", known)->describe(),
std::string{"(member or (staff and heavy))"});
LLD_CHECK_EQ(rules::parse("not member and staff", known)->describe(),
std::string{"(not member and staff)"});
LLD_CHECK(eval("member or staff and heavy", {"member"}));
LLD_CHECK(!eval("(member or staff) and heavy", {"member"}));
}
// "Round trip": describe a tree, parse that text again, and describe the
// new tree. The two descriptions must be identical, so the brackets that
// describe() adds mean exactly what the parser understood.
LLD_TEST(a_description_parses_back_to_the_same_tree) {
const auto first = rules::parse("not (member or staff) and gift or express", known);
const auto again = rules::parse(first->describe(), known);
LLD_CHECK_EQ(again->describe(), first->describe());
}
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws
// an exception of that type. In order: an unknown fact, empty text, an
// "and" with nothing after it, two facts with no operator between them,
// a missing ")", a keyword where a fact should be, and a capital letter
// (fact names are lowercase letters and _ only).
LLD_TEST(unknown_facts_and_bad_grammar_are_refused) {
LLD_CHECK_THROWS(rules::parse("vip", known), rules::ParseError);
LLD_CHECK_THROWS(rules::parse("", known), rules::ParseError);
LLD_CHECK_THROWS(rules::parse("member and", known), rules::ParseError);
LLD_CHECK_THROWS(rules::parse("member staff", known), rules::ParseError);
LLD_CHECK_THROWS(rules::parse("(member", known), rules::ParseError);
LLD_CHECK_THROWS(rules::parse("and", known), rules::ParseError);
LLD_CHECK_THROWS(rules::parse("Member", known), rules::ParseError);
}
// The bad word, "or", starts at index 11 of "member and or staff" (count
// from 0: "member " is 0 to 6, "and " is 7 to 10). (void) discards the
// tree parse would return; LLD_CHECK(false) is reached, and fails the
// test, only if parse did not throw.
LLD_TEST(the_error_says_where) {
try {
(void)rules::parse("member and or staff", known);
LLD_CHECK(false);
} catch (const rules::ParseError& e) {
LLD_CHECK_EQ(e.position(), 11u);
}
}
// Each limit is tested just past it (refused) and just inside it
// (accepted). Each "not" and each "(" adds one level of nesting.
LLD_TEST(deep_nesting_and_long_rules_are_refused) {
// 51 copies of "not " (max_depth is 50): one too many.
std::string deep;
for (int i = 0; i < rules::max_depth + 1; ++i) {
deep += "not ";
}
LLD_CHECK_THROWS(rules::parse(deep + "member", known), rules::ParseError);
// substr(4) drops the first four characters, one "not ", leaving 50.
// An even number of nots cancels out, so the rule is true for member.
LLD_CHECK(rules::parse(deep.substr(4) + "member", known)->evaluate({"member"})); // 50 nots
// std::string(count, ch) is `count` copies of one character: 51 "("s
// and 51 ")"s, refused; then 50 of each, accepted.
const std::string open(rules::max_depth + 1, '(');
const std::string close(rules::max_depth + 1, ')');
LLD_CHECK_THROWS(rules::parse(open + "member" + close, known), rules::ParseError);
LLD_CHECK(rules::parse(open.substr(1) + "member" + close.substr(1), known)
->evaluate({"member"}));
// No nesting at all, only length: grow "member or member or ..." until
// it is longer than max_length characters, which parse must refuse.
std::string long_rule = "member";
while (long_rule.size() <= rules::max_length) {
long_rule += " or member";
}
LLD_CHECK_THROWS(rules::parse(long_rule, known), rules::ParseError);
}
// nullptr converts to an empty ExpressionPtr; the node constructors throw
// std::invalid_argument rather than build a tree with a hole in it.
LLD_TEST(null_operands_are_refused) {
LLD_CHECK_THROWS(rules::Not{nullptr}, std::invalid_argument);
LLD_CHECK_THROWS(rules::Or(std::make_unique<rules::Fact>("member"), nullptr),
std::invalid_argument);
}
  • a_tree_built_by_hand_evaluates_like_the_text builds a tree without the parser: the pattern does not need one.
  • and_binds_tighter_than_or_and_not_tightest pins the precedence, and a_description_parses_back_to_the_same_tree checks that describe and parse agree with each other, for rules well inside the limits. A description adds parentheses, so a rule near max_length can describe into text the parser refuses.
  • deep_nesting_and_long_rules_are_refused checks both limits from the warning above.

Adding an operator, or adding an operation

Section titled “Adding an operator, or adding an operation”

The two kinds of change are not equally easy:

  • A new operator (for example xor) is one new class and a few small changes to the parser. No existing node changes. The exercise does this.
  • A new operation (for example “list the facts this rule uses”, or “simplify not not a to a”, or “turn this rule into a database query”) must be added to every node class as a new virtual function. With four classes that is fine. With forty, and with operations added often, it is the problem the Visitor pattern addresses, by moving each operation into one class of its own.

A modern C++ alternative is to make the node a std::variant of small structs and write each operation as one function that uses std::visit. Adding an operation is then easy, and adding a node type means changing every operation instead: the same trade-off, turned around. The variant does not remove the ownership question: a node that holds other nodes still holds them through a pointer, such as a std::unique_ptr, because a type cannot contain itself by value.

  • You have a small language, with a few rules that nest: filters, permission rules, search queries, simple formulas.
  • Its sentences are written by people or come from outside the program, so they cannot be written as C++.
  • You need to evaluate the same sentence many times (for many orders), or do several things with it (evaluate, describe, check), so it is worth turning into a tree once.
  • The rules are flat. “All of these, none of those” fits in a table, as in the before-version. A table is simpler to store, edit, and check.
  • The language is not small. With variables, functions, loops, or dozens of operators, a class per grammar rule becomes a large hierarchy, and a hand-written parser becomes hard to get right. Use a parser generator, or embed an existing scripting language, rather than inventing one.
  • Speed matters a great deal. Walking a tree of virtual calls is slow compared with compiled code. Tools that evaluate rules very often usually compile them first into something flatter, such as a list of instructions.
  • The rules are always known when you compile. Then they are just C++ functions: bool free_shipping(const Order&).
  • A parser to write and test. Here it is longer than all the nodes together, and most of the bugs in a language are in its parser.
  • Recursion in every operation, with the stack limit it brings; hence the limits on depth and length.
  • A class per grammar rule, and a virtual call per node visited.
  • Error messages are your job. The compiler checks C++; nothing checks your language except the code you write for it.
  • Evaluating text directly, by searching strings for " and " each time a rule is checked. It is slower, it gets precedence wrong, and it reports errors (if at all) while evaluating, not while loading.
  • Treating unknown names as false. A typo then turns a promotion off, silently. Check names when the rule is loaded.
  • No limits on input. A rule from a file, a web form, or another program can be any size; an unbounded recursive parser can be made to crash.
  • Growing the language without a plan. Each “small” addition (numbers, comparisons, variables) adds node classes, parser code, and error cases. When the list keeps growing, consider an existing language.
  • “Add xor.” One class and one parser function; see the exercise.
  • “Rules may compare numbers: total >= 50.” The context becomes richer (facts with values, not just a set of names), evaluate needs that context, and the parser needs numbers and comparison operators. This is the point at which to ask whether the language is still small.
  • “Show which facts a rule uses, in the admin page.” A new operation: either add a virtual function to every node, or look at Visitor.
  • “Marketing want to edit rules in a form, not as text.” The form can build the tree directly, through the same node classes, with no parser at all.

Exercise: Add an xor operator

Add xor (“exactly one of the two”) to the language, so that gift xor express is true for an order with one of those facts and false for an order with both or neither.

  1. Which classes and functions must change, and which stay as they are?
  2. Where in the grammar should xor go: tighter than and, between and and or, or looser than or? Choose one and justify it.
  3. Can Xor::evaluate stop early, as And and Or do?
  4. A fact is called xor_flag. Does your change break it?
Show the explained answer

1. Add one class, Xor, next to And and Or, with the same shape:

class Xor final : public Expression {
public:
Xor(ExpressionPtr left, ExpressionPtr right);
bool evaluate(const Names& true_facts) const override;
std::string describe() const override;
private:
ExpressionPtr left_;
ExpressionPtr right_;
};
Xor::Xor(ExpressionPtr left, ExpressionPtr right)
: left_{require(std::move(left))}, right_{require(std::move(right))} {}
// Exclusive or: true when exactly one side is true. On two bools, != is
// exactly that. Unlike && and ||, it must always ask both sides.
bool Xor::evaluate(const Names& true_facts) const {
return left_->evaluate(true_facts) != right_->evaluate(true_facts);
}
std::string Xor::describe() const {
return "(" + left_->describe() + " xor " + right_->describe() + ")";
}

In the parser, add one grammar level and one function, and make parse_rule call it instead of parse_and:

// rule := xor_rule { "or" xor_rule }
// xor_rule := and_rule { "xor" and_rule }
// The same loop as parse_and, one level looser: each side is a whole
// and_rule, so "and" binds tighter than "xor", and "xor" tighter than "or".
ExpressionPtr parse_xor(int depth) {
ExpressionPtr left = parse_and(depth);
while (accept_word("xor")) {
left = std::make_unique<Xor>(std::move(left), parse_and(depth));
}
return left;
}

Put Xor’s functions in expression.cpp, where require is. Also add "xor" to is_keyword, so that it cannot be used as a fact name, and to the “expected …” message in parse_all. Fact, Not, And, Or, and RuleSet do not change at all.

2. Between and and or is a reasonable choice, and the one made here: it matches C++’s bitwise operators, where ^ binds tighter than | and looser than & (though in C++, ^ binds tighter than both && and ||). Any of the three is defensible if it is written down; what matters is that it is fixed, documented, and tested, and that describe shows the grouping so nobody has to remember. With this choice, member or gift xor express and member describes as (member or (gift xor (express and member))).

3. No. The answer depends on both sides whatever the left one is, so both must always be evaluated.

4. No. accept_word reads the whole word, xor_flag, and compares it with xor, so they never match. What reserving xor does break is a fact named exactly xor, which can no longer be used: the real compatibility risk of adding a keyword. In a scratch program built from the example’s files with this change, gift xor express evaluated to true for an order with only gift, false for one with gift, express, and member, true for one with only express, and false for one with no facts; and xor_flag parsed as a fact.

  • Composite: the tree of expressions is a composite. Interpreter adds the idea that each node class is a rule of a grammar, and that the main operation is evaluating a sentence. See Composite.
  • Visitor: moves operations out of the node classes, so new operations do not change every node. See Visitor.
  • Strategy: each rule here could also be a std::function<bool(const Names&)>, built from lambdas. That is fine when rules are written in C++; Interpreter is for rules that arrive as data. See Strategy.
  • Interpreter represents a small language as one class per grammar rule, so a sentence becomes a tree of objects that evaluates itself.
  • The pattern starts from the tree. A parser (or a form, or a JSON reader) builds it; in practice the parser is the bigger part.
  • In C++, own children with std::unique_ptr<const Expression>, pass the context to evaluate as a parameter, and keep the tree immutable once built.
  • Refuse bad input when loading: unknown names, bad grammar, and rules too long or too deep for a recursive design.
  • Try a table first. Reach for Interpreter when rules nest, and for an existing language when your language stops being small.