pt(3tcl)
β¨ NAME β¨
okay so bestie, this is the manpage for pt β the Parser Tools Application π it lives in the pt(3tcl) slot of the manual, and it's your main character entrance to the whole Parser Tools situation.
π SYNOPSIS π
package require Tcl 8.5 9
pt generate resultformat ?options...? resultfile inputformat inputfile
π¦ DESCRIPTION π¦
ngl, are you lost? π Are you sitting there like "what is this document even saying"? In that case, go read the overview in the Introduction to Parser Tools first β that's the entrypoint to the entire system this package is part of, iykyk.
So. This document is all about pt, the main application of the module, aka a parser generator β¨ The intended audience is literally people who want to build a parser for some language of their own. But if you're the type who wants to modify the application instead of using it, then head over to the section about the application's Internals for the basic references, bestie π«Ά
It resides in the User Application Layer of Parser Tools.
IMAGE: arch_user_app
π COMMAND LINE π
pt generate resultformat ?options...? resultfile inputformat inputfileβ this sub-command of the application reads the parsing expression grammar stored in the inputfile in the format inputformat, converts it to the resultformat under the direction of the (format-specific) set of options specified by the user, and stores the result in the resultfile.
The inputfile has to exist β no inputfile, no vibes π β while the resultfile may be created, overwriting any pre-existing content of the file. Any missing directory in the path to the resultfile will be created as well. Slay.
The exact form of the result for, and the set of options supported by, the known result-formats are explained in the upcoming sections of this document. The list below is basically an index mapping between format name and its associated section. In alphabetical order, periodt:
cβ a resultformat. See section C Parser.containerβ a resultformat. See section Grammar Container.critclβ a resultformat. See section C Parser Embedded In Tcl.jsonβ a input- and resultformat. See section JSON Grammar Exchange.ooβ a resultformat. See section TclOO Parser.pegβ a input- and resultformat. See section PEG Specification Language.snitβ a resultformat. See section Snit Parser.
So out of the seven possible results, four are parsers outright (c, critcl, oo, and snit), one (container) hands you code you can use together with a generic parser (also known as a grammar interpreter), and the last two (json and peg) are doing double-duty as input formats, which lets you transform grammars for exchange, reformatting, and all that cute stuff π
The created parsers fall into three categories:
.nf + --- C ---> critcl, c | + --- specialized -+ | |
---+ + --- Tcl -> snit, oo | + --- interpreted (Tcl)
------> container .fi
okay so the ASCII diagram above is exactly how it lands in the manpage β the formatter chewed on it a lil π but the info's all there, don't worry.
π₯ Specialized parsers implemented in C
The fastest parsers are created when using the result formats c and critcl. The first returns the raw C code for the parser, while the latter wraps it into a Tcl package using CriTcl.
This makes the latter much easier to use than the former. On the other hand, the former can be adapted to the users' requirements through a multitude of options, allowing for things like usage of the parser outside of a Tcl environment β something the critcl format doesn't support. As such the c format is meant for more advanced users, or users with special needs π
A disadvantage of all the parsers in this section is the need to run them through a C compiler to make them actually executable. This is not something everyone has the necessary tools for π The parsers in the next section are for people under such restrictions.
π Specialized parsers implemented in Tcl
As the parsers in this section are implemented in Tcl they are quite a bit slower than anything from the previous section. On the other hand this allows them to be used in pure-Tcl environments, or in environments which allow only a limited set of binary packages. In the latter case it will be advantageous to lobby for the inclusion of the C-based runtime support (notes below) into the environment, to reduce the impact of Tcl's on the speed of these parsers.
The relevant formats are snit and oo. Both place their result into a Tcl package containing a snit::type, or TclOO class respectively.
Of the supporting runtime, which is the package pt::rde, the user has to know nothing but that it does exist and that the parsers are dependent on it. Knowledge of the API exported by the runtime for the parsers' consumption is not required by the parsers' users. So like, you don't need to know it. It just exists and holds it down π«Ά
π§ Interpreted parsing implemented in Tcl
The last category: grammar interpretation. This means that an interpreter for parsing expression grammars takes the description of the grammar to parse input for, and uses it to guide the parsing process. This is the slowest of the available options, as the interpreter has to continually run through the configured grammar β whereas the specialized parsers of the previous sections have the relevant knowledge about the grammar baked into them π
The only places where using interpretation make sense is where the grammar for some input may be changed interactively by the user, as the interpretation allows for quick turnaround after each change, whereas the previous methods require the generation of a whole new parser, which is not as fast. On the other hand, wherever the grammar to use is fixed, the previous methods are much more advantageous as the time to generate the parser is minuscule compared to the time the parser code is in use. Math is mathing β¨
The relevant result format is container. It (quickly) generates grammar descriptions (instead of a full parser) which match the API expected by ParserTools' grammar interpreter. The latter is provided by the package pt::peg::interp.
All the parsers generated by critcl, snit, and oo, and the grammar interpreter share a common API for access to the actual parsing functionality, making them all plug-compatible π
It is described in the Parser API specification document.
πΈ PEG SPECIFICATION LANGUAGE πΈ
peg, a language for the specification of parsing expression grammars, is meant to be human readable β and writable as well β yet strict enough to allow its processing by machine. Like any computer language. It was defined to make writing the specification of a grammar easy, something the other formats found in the Parser Tools do not lend themselves too.
For either an introduction to or the formal specification of the language, please go and read the PEG Language Tutorial π
When used as a result-format this format supports the following options:
-filestring β the value of this option is the name of the file or other entity from which the grammar came, for which the command is run. The default value isunknown.-namestring β the value of this option is the name of the grammar we are processing. The default value isa_pe_grammar.-userstring β the value of this option is the name of the user for which the command is run. The default value isunknown.-templatestring β the value of this option is a string into which to put the generated text and the values of the other options. The various locations for user-data are expected to be specified with the placeholders listed below. The default value is"@code@".@user@β to be replaced with the value of the option-user.@format@β to be replaced with the the constantPEG.@file@β to be replaced with the value of the option-file.@name@β to be replaced with the value of the option-name.@code@β to be replaced with the generated text.
β JSON GRAMMAR EXCHANGE β
The json format for parsing expression grammars was written as a data exchange format not bound to Tcl. It was defined to allow the exchange of grammars with PackRat/PEG based parser generators for other languages. Networking but make it grammars π
For the formal specification of the JSON grammar exchange format, please go and read The JSON Grammar Exchange Format.
When used as a result-format this format supports the following options:
-filestring β the value of this option is the name of the file or other entity from which the grammar came, for which the command is run. The default value isunknown.-namestring β the value of this option is the name of the grammar we are processing. The default value isa_pe_grammar.-userstring β the value of this option is the name of the user for which the command is run. The default value isunknown.-indentedboolean β if this option is set the system will break the generated JSON across lines and indent it according to its inner structure, with each key of a dictionary on a separate line.
If the option is not set (the default), the whole JSON object will be written on a single line, with minimum spacing between all elements.
-alignedboolean β if this option is set the system will ensure that the values for the keys in a dictionary are vertically aligned with each other, for a nice table effect. To make this work this also implies that-indentedis set.
If the option is not set (the default), the output is formatted as per the value of indented, without trying to align the values for dictionary keys.
π C PARSER EMBEDDED IN TCL π
The critcl format is executable code, bestie β like, an actual parser for the grammar. It's a Tcl package where the real parser implementation is written in C and then embedded into Tcl via the critcl package. iconic behaviour honestly β¨
This result-format supports the following options:
-filestring β this one's the name of the file (or whatever other entity) the grammar came from, yk, the thing the command is run for. default isunknown.-namestring β the name of the grammar we're processing. default isa_pe_grammar.-userstring β the name of the user the command is run for. default isunknown.-classstring β the name of the class to generate, no leading colons pls. default isCLASS.
okay so for a simple value X without colons, like CLASS, the parser command is gonna be X::X. but for a namespaced value X::Y the parser command is just X::Y. slay π
-packagestring β the name of the package to generate. default isPACKAGE.-versionstring β the version of the package to generate. default is1.
β¨ C PARSER β¨
The c format is executable code, a parser for the grammar. The parser implementation is written in C and β the best part β you can tweak it to your exact needs through a multitude of options. main character customisation energy fr fr π
And like, the critcl format? It's literally implemented as a canned configuration of these options sitting on top of the generator for c. obsessed.
This result-format supports the following options:
-filestring β name of the file or other entity the grammar came from, for which the command is run. default isunknown.-namestring β name of the grammar we're processing. default isa_pe_grammar.-userstring β name of the user the command is run for. default isunknown.-templatestring β a string you drop the generated text and the other configuration settings into. the various spots for user-data are expected to be marked with the placeholders listed below π default is"@code@".@user@β gets replaced with the value of the option-user.@format@β gets replaced with the the constantC/PARAM. (yes, the original says "the the", I'm just reporting the vibes π)@file@β gets replaced with the value of the option-file.@name@β gets replaced with the value of the option-name.@code@β gets replaced with the generated Tcl code.
and okay, these next ones are special special, in that they show up inside the generated code and get replaced there too. no cap:
@statedecl@β gets replaced with the value of the optionstate-decl.@stateref@β gets replaced with the value of the optionstate-ref.@strings@β gets replaced with the value of the optionstring-varname.@self@β gets replaced with the value of the optionself-command.@def@β gets replaced with the value of the optionfun-qualifier.@ns@β gets replaced with the value of the optionnamespace.@main@β gets replaced with the value of the optionmain.@prelude@β gets replaced with the value of the optionprelude.
-state-declstring β a C string for the argument declaration to use in the generated parsing functions to refer to the parsing state. basically type + argument name, yk. default is the stringRDE_PARAM p.-state-refstring β a C string for the argument named used in the generated parsing functions to refer to the parsing state. default is the stringp.-self-commandstring β a C string for the reference needed to call the generated parser function (methods ...) from another parser fonction, per the chosen framework (template). default is the empty string.-fun-qualifierstring β a C string holding the attributes to give to the generated functions (methods ...), per the chosen framework (template). default isstatic.-namespacestring β the name of the C namespace the parser functions (methods, ...) shall reside in, or just a general prefix to add to the function names. default is the empty string.-mainstring β the name of the main function (method, ...) that the chosen framework (template) calls to start parsing input. default is__main.-string-varnamestring β the name of the variable used for the table of strings the generated parser uses, i.e. error messages, symbol names, etc. default isp_string.-preludestring β a lil snippet of code to be inserted at the head of each generated parsing function. default is the empty string.-indentinteger β how many characters to indent each line of the generated code by. default is0.-commentsboolean β a flag controlling the generation of code comments containing the original parsing expression a parsing function is for. default ison. π«Ά
πΈ SNIT PARSER πΈ
The snit format is executable code, a parser for the grammar. It's a Tcl package holding a snit::type, i.e. a class, and the instances of that class are literally parsers for the input grammar. it's giving classy π
This result-format supports the following options:
-filestring β name of the file or other entity the grammar came from, for which the command is run. default isunknown.-namestring β name of the grammar we're processing. default isa_pe_grammar.-userstring β name of the user the command is run for. default isunknown.-classstring β the name of the class to generate, without leading colons. and okay bestie, heads up: it serves double-duty as the name of the package to generate too, if option-packageis not specified, see below. default isCLASS, applying if neither option-classnor-packagewere specified. she's doing two jobs, we love a multitasker π-packagestring β the name of the package to generate, without leading colons. and yeah, it also serves double-duty as the name of the class to generate too, if option-classis not specified, see above. default isPACKAGE, applying if neither option-packagenor-classwere specified.-versionstring β the version of the package to generate. default is1.
π¦ TCLOO PARSER π¦
The oo format is executable code, a parser for the grammar. It's a Tcl package holding a TclOO class, whose instances are parsers for the input grammar. object-oriented AND parsing?? the range ππ
This result-format supports the following options:
-filestring β name of the file or other entity the grammar came from, for which the command is run. default isunknown.-namestring β name of the grammar we're processing. default isa_pe_grammar.-userstring β name of the user the command is run for. default isunknown.-classstring β the name of the class to generate, without leading colons. and once again: it serves double-duty as the name of the package to generate too, if option-packageis not specified, see below. default isCLASS, applying if neither option-classnor-packagewere specified.-packagestring β the name of the package to generate, without leading colons. and yep: it serves double-duty as the name of the class to generate too, if option-classis not specified, see above. default isPACKAGE, applying if neither option-packagenor-classwere specified.-versionstring β the version of the package to generate. default is1.
β¨ GRAMMAR CONTAINER β¨
okay bestie, so the container format is another way to describe parsing expression grammars. While data in this format is executable it does not constitute a parser for the grammar. It always has to be used in conjunction with the package pt::peg::interp, a grammar interpreter. π
The format represents grammars by a snit::type, i.e. class, whose instances are API-compatible to the instances of the pt::peg::container package, and which are preloaded with the grammar in question.
This result-format supports the following options:
-filestring β The value of this option is the name of the file or other entity from which the grammar came, for which the command is run. The default value isunknown. ποΈ-namestring β The value of this option is the name of the grammar we are processing. The default value isa_pe_grammar. πΈ-userstring β The value of this option is the name of the user for which the command is run. The default value isunknown. π€-modebulk|incrementalβ The value of this option controls which methods ofpt::peg::containerinstances are used to specify the grammar, i.e. preload it into the container. There are two legal values, as listed below. The default isbulk. βοΈbulkβ In this mode the methodsstart,add,modes, andrulesare used to specify the grammar in a bulk manner, i.e. as a set of nonterminal symbols, and two dictionaries mapping from the symbols to their semantic modes and parsing expressions. This mode is the default. π§Ίincrementalβ In this mode the methodsstart,add,mode, andruleare used to specify the grammar piecemal, with each nonterminal having its own block of defining commands. π§©
-templatestring β The value of this option is a string into which to put the generated code and the other configuration settings. The various locations for user-data are expected to be specified with the placeholders listed below. The default value is"@code@". π@user@β To be replaced with the value of the option-user. π@format@β To be replaced with the the constantCONTAINER. (yes bestie, the original says "the the", we keep it iconic) π@file@β To be replaced with the value of the option-file. π@name@β To be replaced with the value of the option-name. π·οΈ@mode@β To be replaced with the value of the option-mode. π@code@β To be replaced with the generated code. π»
β¨ EXAMPLE β¨
In this section we are working a complete example, starting with a PEG grammar and ending with running the parser generated from it over some input, following the outline shown in the figure below:
IMAGE: flow β imagine a flow chart, bestie, she's serving diagram energy. π
Our grammar, assumed to the stored in the file "calculator.peg" is
PEG calculator (Expression)
Digit <- '0'/'1'/'2'/'3'/'4'/'5'/'6'/'7'/'8'/'9' ;
Sign <- '-' / '+' ;
Number <- Sign? Digit+ ;
Expression <- Term (AddOp Term)* ;
MulOp <- '*' / '/' ;
Term <- Factor (MulOp Factor)* ;
AddOp <- '+'/'-' ;
Factor <- '(' Expression ')' / Number ;
END;
From this we create a snit-based parser via
pt generate snit calculator.tcl -class calculator -name calculator peg calculator.peg
which leaves us with the parser package and class written to the file "calculator.tcl". Assuming that this package is then properly installed in a place where Tcl can find it we can now use this class via a script like
package require calculator
lassign $argv input
set channel [open $input r]
set parser [calculator]
set ast [$parser parse $channel]
$parser destroy
close $channel
... now process the returned abstract syntax tree ...
where the abstract syntax tree stored in the variable will look like
set ast {Expression 0 4
{Factor 0 4
{Term 0 2
{Number 0 2
{Digit 0 0}
{Digit 1 1}
{Digit 2 2}
}
}
{AddOp 3 3}
{Term 4 4
{Number 4 4
{Digit 4 4}
}
}
}
}
assuming that the input file and channel contained the text
120+5
A more graphical representation of the tree would be
.nf +- Digit 0 0 | 1 | | +- Term 0 2 --- Number 0 2 -+- Digit
1 1 | 2 | | | |
+- Digit 2 2 | 0 | | Expression 0
4 --- Factor 0 4 -+----------------------------- AddOp 3 3 | + |
| +- Term 4 4 --- Number 4 4 --- Digit 4 4 | 5 .fi
Regardless, at this point it is the user's responsibility to work with the tree to reach whatever goal she desires. I.e. analyze it, transform it, etc. The package pt::ast should be of help here, providing commands to walk such ASTs structures in various ways. π¦
One important thing to note is that the parsers used here return a data structure representing the structure of the input per the grammar underlying the parser. There are no callbacks during the parsing process, i.e. no parsing actions, as most other parsers will have. π«
Going back to the last snippet of code, the execution of the parser for some input, note how the parser instance follows the specified Parser API. π―
β¨ INTERNALS β¨
This section is intended for users of the application which wish to modify or extend it. Users only interested in the generation of parsers can ignore it. π
The main functionality of the application is encapsulated in the package pt::pgen. Please read it for more information. π
β¨ BUGS, IDEAS, FEEDBACK β¨
This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category pt of the Tcllib Trackers http://core.tcl.tk/tcllib/reportlist. Please also report any ideas for enhancements you may have for either package and/or documentation. ππ‘
When proposing code changes, please provide unified diffs, i.e the output of diff -u. π
Note further that attachments are strongly preferred over inlined patches. Attachments can be made by going to the Edit form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar. π
β¨ KEYWORDS β¨
EBNF, LL(k), PEG, TDPL, context-free languages, expression, grammar, matching, parser, parsing expression, parsing expression grammar, push down automaton, recursive descent, state, top-down parsing languages, transducer π
β¨ CATEGORY β¨
Parsing and Grammars π§
β¨ COPYRIGHT β¨
Copyright (c) 2009 Andreas Kupries <andreas_kupries@users.sourceforge.net> π
okay bestie, that's the whole vibe. this iconic page is from tcllib, version 1, filed under pt(3tcl) β no date on the footer, she's timeless fr fr. now go parse something and slay π
β¨
π¦ 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) 2009 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