grammar::peg(3tcl)
π NAME π
grammar::peg β literally the command for creating and manipulating parsing expression grammars, no cap π
(this is the grammar::peg(3tcl) page, bestie, and it's filed under Grammar operations and usage β¨)
β¨ SYNOPSIS β¨
package require Tcl 8.5 9
package require snit
package require grammar::peg ?0.3?
::grammar::peg pegName ?=|:=|<--|as|deserialize src?
pegName destroy
pegName clear
pegName = srcPEG
pegName --> dstPEG
pegName serialize
pegName deserialize serialization
pegName is valid
pegName start ?pe?
pegName nonterminals
pegName nonterminal add nt pe
pegName nonterminal delete nt1 ?nt2 ...?
pegName nonterminal exists nt
pegName nonterminal rename nt ntnew
pegName nonterminal mode nt ?mode?
pegName nonterminal rule nt
pegName unknown nonterminals
πΈ DESCRIPTION πΈ
So this package hands you a container class for parsing expression grammars β PEGs for short, iykyk π¦. What it lets you do is incrementally build up a grammar, poke at its definition, and ask it questions about itself. That's the whole vibe.
What it does NOT do: it doesn't do the fancy complex operations on your grammar, and it 100% cannot take a grammar definition and run it against a stream of symbols. Not its job, bestie. π ββοΈ
Two packages that do pick up that slack are grammar::mengine and grammar::peg::interpreter. The first one defines a general-purpose virtual machine for matching a character stream, and the second one implements an interpreter for parsing expression grammars sitting right on top of that virtual machine. Teamwork, honestly. π«Ά
π¦ TERMS & CONCEPTS π¦
PEGs are like context-free grammars but not equivalent β and in some cases PEGs are strictly more powerful than context-free grammars (there are PEGs for some languages that aren't even context-free, iconic π). If you want the formal mathematical definition of parsing expressions and parsing expression grammars, it's chilling down in the section PARSING EXPRESSION GRAMMARS.
Short version: we've got terminal symbols, which are the most basic building blocks for sentences, and nonterminal symbols, which come with associated parsing expressions that define the grammatical structure of the sentences. These two symbol sets are distinctive and they do not overlap, periodt. When people talk about symbols they usually drop the word "symbol" entirely (we're all guilty). The union of the terminal and nonterminal symbol sets is called the set of symbols.
Here's a cute little twist: the set of terminal symbols isn't explicitly managed. It's implicitly defined as the set of all characters π. Which means we inherit from Tcl the ability to handle all of Unicode. Slay.
A pair of a nonterminal and a parsing expression is also called a grammatical rule, or just a rule if you're being casual. Inside a rule, the nonterminal is often called the left-hand-side (LHS) and the parsing expression is the right-hand-side (RHS). Standard.
The start expression of a grammar is a parsing expression from which all the sentences contained in the language specified by the grammar are derived. Okay so to make this click, let's pretend for a sec that the RHS of every rule (and the start expression too) is either a sequence of symbols or a series of alternate parsing expressions. In that second case you can read the rule as a whole set of rules, each one providing one alternative for the nonterminal. Now: a parsing expression A' is a derivation of a parsing expression A if we pick one of the nonterminals N in the expression, pick one of the alternative rules R for N, and then replace that nonterminal in A with the RHS of the chosen rule. And this is why terminal symbols are called terminal β they cannot be expanded any further, so they terminate the whole deriving-new-expressions process. So satisfying tbh.
An example, because examples ate:
Rules
(1) A <- a B c
(2a) B <- d B
(2b) B <- e
Some derivations, using starting expression A.
A -/1/-> a B c -/2a/-> a d B c -/2b/-> a d e c
A derived expression that contains only terminal symbols is a sentence. And the set of all sentences that can be derived from the start expression is the language of the grammar. That's the whole point of the exercise π.
Some definitions for nonterminals and expressions, bestie, take notes:
- A nonterminal A is called reachable if it is possible to derive a parsing expression from the start expression which contains A.
- A nonterminal A is called useful if it is possible to derive a sentence from it.
- A nonterminal A is called recursive if it is possible to derive a parsing expression from it which contains A, again.
- The FIRST set of a nonterminal A contains all the symbols which can occur of as the leftmost symbol in a parsing expression derived from A. If the FIRST set contains A itself then that nonterminal is called left-recursive.
- The LAST set of a nonterminal A contains all the symbols which can occur of as the rightmost symbol in a parsing expression derived from A. If the LAST set contains A itself then that nonterminal is called right-recursive.
- The FOLLOW set of a nonterminal A contains all the symbols which can occur after A in a parsing expression derived from the start expression.
- A nonterminal (or parsing expression) is called nullable if the empty sentence can be derived from it.
And now, based on all of the above, definitions for grammars:
- A grammar G is recursive if and only if it contains a nonterminal A which is recursive. The terms left- and right-recursive, and useful, are analogously defined.
- A grammar is minimal if it contains only reachable and useful nonterminals.
- A grammar is wellformed if it is not left-recursive. Such grammars are also complete, which means they always succeed or fail on all input sentences. For an incomplete grammar on the other hand, input sentences exist for which an attempt to match them against the grammar will not terminate. π Not the infinite loop.
- Since we want to allow ourselves to build a grammar incrementally inside a container object, we will encounter stages where the RHS of one or more rules reference symbols that the container doesn't know about yet. Such a grammar we call invalid. And no, we cannot call it incomplete β that word is already taken, see the last item. Sorry, the vocabulary is booked solid π.
π CONTAINER CLASS API π
The package exports the API described right here. Enjoy.
::grammar::peg pegName ?=|:=|<--|as|deserialize src?β This command creates a brand new container object for a parsing expression grammar and returns the fully qualified name of the object command as its result. The API that the returned command follows is described down in the sectionCONTAINER OBJECT API, and you use it to invoke all kinds of operations on the container and the grammar living inside it.
If you don't specify src, your new container β i.e. your grammar β will be empty. Otherwise it will hold a copy of the grammar contained in src. For every operator except deserialize, src has to be a container object reference. The deserialize operator instead requires src to be the serialization of a parsing expression grammar. Different flavor of src, same energy.
An empty grammar has no nonterminal symbols, and its start expression is the empty expression, i.e. epsilon. It is valid, but it is not useful. (A mood, honestly, but for grammars it's just a technical fact π.)
π CONTAINER OBJECT API π
All grammar container objects provide the following methods for manipulating their contents. Every single one, no skipping π:
pegName destroyβ Destroys the grammar, including its storage space and its associated command. Gone, reduced to atoms β¨.pegName clearβ Clears out the definition of the grammar contained inpegName, but does not destroy the object. It stays, just empty. A fresh start, main character energy πΈ.pegName = srcPEGβ Assigns the contents of the grammar contained insrcPEGtopegName, overwriting whatever definition was there. This is the assignment operator for grammars. It copies the grammar contained in the grammar objectsrcPEGover the grammar definition inpegName. The old contents ofpegNameare deleted by this operation. π
This operation is in effect equivalent to
pegName deserialize [srcPEG serialize]
pegName --> dstPEGβ This is the reverse assignment operator for grammars. It copies the automation contained in the objectpegNameover the grammar definition in the objectdstPEG. The old contents ofdstPEGare deleted by this operation.
This operation is in effect equivalent to
dstPEG deserialize [pegName serialize]
pegName serializeβ This method serializes the grammar stored inpegName. In other words it returns a tcl value that completely describes that grammar. Which means you can, for example, transfer grammars over arbitrary channels, do persistence, all that good stuff π¦. This method is also the basis for both the copy constructor and the assignment operator. Look at it carrying the whole team.
The result of this method has to be semantically identical across all implementations of the grammar::peg interface. That's literally what enables us to copy grammars between different implementations of the same interface. Iconic interoperability behavior π.
The result is a list of four elements with this structure:
- The constant string
grammar::peg. - A dictionary. Its keys are the names of all known nonterminal symbols, and their associated values are the parsing expressions describing their sentennial structure.
- A dictionary. Its keys are the names of all known nonterminal symbols, and their associated values are hints to a matcher regarding the semantic values produced by the symbol.
- The last item is a parsing expression, the start expression of the grammar.
Assuming the following PEG for simple mathematical expressions
Digit <- '0'/'1'/'2'/'3'/'4'/'5'/'6'/'7'/'8'/'9'
Sign <- '+' / '-'
Number <- Sign? Digit+
Expression <- '(' Expression ')' / (Factor (MulOp Factor)*)
MulOp <- '*' / '/'
Factor <- Term (AddOp Term)*
AddOp <- '+'/'-'
Term <- Number
a possible serialization is π (bestie, hold that thought β it's literally coming in the next bit, don't go anywhere β¨)
grammar::peg \
{Expression {/ {x ( Expression )} {x Factor {* {x MulOp Factor}}}} \
Factor {x Term {* {x AddOp Term}}} \
Term Number \
MulOp {/ * /} \
AddOp {/ + -} \
Number {x {? Sign} {+ Digit}} \
Sign {/ + -} \
Digit {/ 0 1 2 3 4 5 6 7 8 9} \
} \
{Expression value Factor value \
Term value MulOp value \
AddOp value Number value \
Sign value Digit value \
}
Expression
okay so that's a possible one, because the order of the nonterminals in the dictionary is not relevant. like, the dict is a dict, bestie, it does not care about your ordering opinions. π
pegName deserialize serializationβ this is the complement toserialize. It swaps the grammar definition insidepegNamefor the grammar thatserializationdescribes. and yes β the old contents ofpegNameget deleted by this operation. gone. bye. πpegName is validβ a predicate, bestie. It tests whether the PEG inpegNameis valid. (see the TERMS & CONCEPTS section for what that property even means.) The result is a boolean:trueif the PEG has the tested property,falseotherwise. no cap. β¨pegName start ?pe?β this method defines the start expression of the grammar. It replaces the previously defined start expression with the parsing expressionpe. The method fails and throws an error ifpedoes not contain a valid parsing expression as specified in the section PARSING EXPRESSIONS. and in that case, the existing start expression is not changed. The method returns the empty string as its result. If you call it with no argument at all, it just hands you back the currently defined start expression. cute, right? πpegName nonterminalsβ returns the set of all nonterminal symbols known to the grammar. that's it. that's the whole method. iconic behaviour honestly. πΈpegName nonterminal add nt peβ adds the nonterminalntand its associated parsing expressionpeto the set of nonterminal symbols and rules of the PEG living insidepegName. The method fails and throws an error if either the stringntis already known as a symbol of the grammar, or ifpedoes not contain a valid parsing expression as specified in the section PARSING EXPRESSIONS. In that case the current set of nonterminal symbols and rules is not changed. The method returns the empty string as its result. π«ΆpegName nonterminal delete nt1 ?nt2 ...?β removes the named symbolsnt1,nt2β¦ from the set of nonterminal symbols of the PEG contained inpegName. The method fails and throws an error if <em>any</em> of the strings is not known as a nonterminal symbol. In that case the current set of nonterminal symbols is not changed. The method returns the empty string as its result.
β οΈ lowkey important: the stored grammar becomes invalid if the deleted nonterminals are still referenced by the RHS of rules that are still known. so likeβ¦ be careful. π
pegName nonterminal exists ntβ a predicate. It tests whether the nonterminal symbolntis known to the PEG inpegName. The result is a boolean:trueif the symbolntis known,falseotherwise. vibe check, but for symbols. βpegName nonterminal rename nt ntnewβ renames the nonterminal symbolnttontnew. The method fails and throws an error if eitherntis not known as a nonterminal, or ifntnewis a known symbol. The method returns the empty string as its result. glow-up, but make it a symbol. π β¨pegName nonterminal mode nt ?mode?β this mode returns or sets the semantic mode associated with the nonterminal symbolnt. If no mode is specified, the current mode of the nonterminal is returned. Otherwise the current mode is set tomode. The method fails and throws an error ifntis not known as a nonterminal. The grammar interpreter implemented by the packagegrammar::peg::interpreterrecognizes the following modes:valueβ the semantic value of the nonterminal is the abstract syntax tree created from the ASTs of the RHS and a node for the nonterminal itself. π¦matchβ the semantic value of the nonterminal is an the abstract syntax tree consisting of single a node for the string matched by the RHS. The ASTs generated by the RHS are discarded. ποΈleafβ the semantic value of the nonterminal is an the abstract syntax tree consisting of single a node for the nonterminal itself. The ASTs generated by the RHS are discarded. πdiscardβ the nonterminal has no semantic value. The ASTs generated by the RHS are discarded (as well). π
pegName nonterminal rule ntβ returns the parsing expression associated with the nonterminalnt. The method fails and throws an error ifntis not known as a nonterminal. πpegName unknown nonterminalsβ returns a list containing the names of all nonterminal symbols which are referenced on the RHS of a grammatical rule, but have no rule definining their structure. In other words: a list of the nonterminal symbols which make the grammar invalid. The grammar is valid if this list is empty. so if it's empty? you ate. periodt. π
β¨ PARSING EXPRESSIONS β¨
Various methods of PEG container objects expect a parsing expression as their argument, or will return such. This section specifies the format such parsing expressions are in. buckle up bestie, here's the list π§
- The string
epsilonis an atomic parsing expression. It matches the empty string. - The string
alnumis an atomic parsing expression. It matches any alphanumeric character. - The string
alphais an atomic parsing expression. It matches any alphabetical character. - The string
dotis an atomic parsing expression. It matches any character. - The expression
[list t x]is an atomic parsing expression. It matches the terminal stringx. - The expression
[list n A]is an atomic parsing expression. It matches the nonterminalA. - For parsing expressions
e1,e2, β¦ the result of[list / e1 e2 ... ]is a parsing expression as well. This is the ordered choice, aka prioritized choice. π - For parsing expressions
e1,e2, β¦ the result of[list x e1 e2 ... ]is a parsing expression as well. This is the sequence. β‘οΈ - For a parsing expression
ethe result of[list * e]is a parsing expression as well. This is the kleene closure, describing zero or more repetitions. π - For a parsing expression
ethe result of[list + e]is a parsing expression as well. This is the positive kleene closure, describing one or more repetitions. β - For a parsing expression
ethe result of[list & e]is a parsing expression as well. This is the and lookahead predicate. π - For a parsing expression
ethe result of[list ! e]is a parsing expression as well. This is the not lookahead predicate. π - For a parsing expression
ethe result of[list ? e]is a parsing expression as well. This is the optional input. π
Examples of parsing expressions where already shown, in the description of the method serialize. (go scroll back up, they're right there, i promise π)
π¦ PARSING EXPRESSION GRAMMARS π¦
For the mathematically inclined, a PEG is a 4-tuple (VN,VT,R,eS) where
VNis a set of nonterminal symbols,VTis a set of terminal symbols,Ris a finite set of rules, where each rule is a pair(A,e),AinVN, andea parsing expression.eSis a parsing expression, the start expression.
Further constraints are
- The intersection of
VNandVTis empty. - For all
AinVTexists exactly one pair(A,e)inR. In other words,Ris a function from nonterminal symbols to parsing expressions.
Parsing expression are inductively defined via
- The empty string (
epsilon) is a parsing expression. - A terminal symbol
ais a parsing expression. - A nonterminal symbol
Ais a parsing expression. e1e2is a parsing expression for parsing expressionse1and2. This is called sequence.e1/e2is a parsing expression for parsing expressionse1and2. This is called ordered choice.e*is a parsing expression for parsing expressione. This is called zero-or-more repetitions, also known as kleene closure.e+is a parsing expression for parsing expressione. This is called one-or-more repetitions, also known as positive kleene closure.!eis a parsing expression for parsing expressione1. This is called a not lookahead predicate.&eis a parsing expression for parsing expressione1. This is called an and lookahead predicate.
PEGs are used to define a grammatical structure for streams of symbols over VT. They are a modern phrasing of older formalisms invented by Alexander Birham. These formalisms were called TS (TMG recognition scheme), and gTS (generalized TS). Later they were renamed to TPDL (Top-Down Parsing Languages) and gTPDL (generalized TPDL). history lesson, bestie, take notes π
They can be easily implemented by recursive descent parsers with backtracking. This makes them relatives of LL(k) Context-Free Grammars. family reunion vibes π«Ά
π REFERENCES π
- The Packrat Parsing and Parsing Expression Grammars Page
[http://www.pdos.lcs.mit.edu/~baford/packrat/], by Bryan Ford, Massachusetts Institute of Technology. This is the main entry page to PEGs, and their realization through Packrat Parsers. π - Parsing Techniques - A Practical Guide
[http://www.cs.vu.nl/~dick/PTAPG.html], an online book offering a clear, accessible, and thorough discussion of many different parsing techniques with their interrelations and applicabilities, including error recovery techniques. π - Compilers and Compiler Generators
[http://scifac.ru.ac.za/compilers/], an online book usingCoCo/R, a generator for recursive descent parsers. βοΈ
π BUGS, IDEAS, FEEDBACK π
okay bestie, real talk: this doc and the package it describes are absolutely gonna have bugs and other problems. it's giving "software, but make it human". not a vibe, but it's the truth π
so if you find one, please report it in the category grammar_peg of the Tcllib Trackers at http://core.tcl.tk/tcllib/reportlist. also, if you've got ideas for enhancements β for either the package and/or the documentation β slide those in too, we want them π«Ά
π a lil note on proposing code changes
when you propose code changes, please provide unified diffs, i.e. the output of diff -u. no cap, that's the format that makes everyone's life easier β¨
also note further that attachments are strongly preferred over inlined patches. how do you attach? go to the Edit form of the ticket immediately after creating it, then use the left-most button in the secondary navigation bar. iconic behavior, do it that way π
π KEYWORDS π
these are the lil searchable tags, so here's the full set, no skips:
LL(k)TDPLcontext-free languagesexpressiongrammarparsingparsing expressionparsing expression grammarpush down automatonrecursive descentstatetop-down parsing languagestransducer
ποΈ CATEGORY ποΈ
Grammars and finite automata β that's the whole category, bestie. short, sweet, extremely on brand πΈ
Β©οΈ COPYRIGHT Β©οΈ
Copyright (c) 2005 Andreas Kupries <andreas_kupries@users.sourceforge.net>
that's the whole copyright line, character for character, don't @ me π
and that's a wrap on grammar::peg(3tcl) π this page is part of tcllib, version 0.3, and it's dated 0.3 in the footer β go forth and parse, bestie, you absolutely ate πβ¨ mwah π
π¦ where this page comes from
- debian trixie: tcllib 2.0+dfsg-4 Β· Tcl
- ubuntu questing: tcllib 2.0+dfsg-4
- ubuntu resolute: tcllib 2.0+dfsg-5 Β· Tcl
- ubuntu stonking: tcllib 2.0+dfsg-6 Β· Tcl
- Copyright (c) 2005 Andreas Kupries <andreas_kupries@users\&.sourceforge\&.net>
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms