Grammatical Patterns
Grammars work by parsing subpatterns recursively. Since capture groups can work as subpatterns, they can be used as productions in a grammar. What you haven’t seen yet is a way to define all your productions separate from calling them.
Obviously, if we’re just using a capture group as a subpattern, it doesn’t matter whether it has actually been used to match anything yet. In fact, when you’re writing a grammar, you generally don’t want your subpatterns called the first time you define them; you’d just like to define them all and then start using them later. What you really want is a way to wall off a part of your pattern for definitions alone, not for execution.
The (?(DEFINE)...) block does
just that. Technically, it’s really just a conditional, like the
(?(
conditional we saw earlier. Here, the condition is COND)...)DEFINE, which turns out to always be
false.[104] So anything you put in a DEFINE block is
guaranteed not to be executed.
The smart-aleck in the class will now point out that the compiler
is free to discard any unused code in a conditional that is always
false. The teacher will point out, however, that this policy applies
only to executable code, not to declarations. And it happens that groups
within the DEFINE block are
considered declarative, so they are not thrown away. They remain quite
callable as subpatterns from elsewhere within the same pattern.
So that’s where we’ll put our grammar. You can put your DEFINE block anywhere you’d like, but usually ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access