btyacc(1)
π btyacc(1) β General Commands Manual, but make it cute π
okay bestie, welcome to the btyacc(1) page β¨ it's giving parser-generator realness, and we're gonna get through every single detail together π«Ά
β¨ NAME β¨
btyaccβ an LALR(1) parser generator with support for backtracking π¦
π SYNOPSIS π
btyacc [-b prefix] [-d] [-DNAME ...] [-E] [-l] [-r] [-S x.ske]
[-t] [-v] filename.y
π Description π
okay so btyacc is a modified version of byacc (Berkeley YACC), which in turn is a public domain version of the original AT&T YACC parser generator. periodt. π
btyacc reads the grammar specification in the file filename.y and generates an LR(1) parser for it. The parser consists of a set of LALR(1) parsing tables and a driver routine written in the C programming language. btyacc normally writes the parse tables and the driver routine to the file prefix.tab.c, where prefix defaults to y. π
For a detailed description of the format of a grammar specification, and an excellent tutorial on how to use YACC-like tools, see the info manual for GNU bison. btyacc-specific extensions are explained below. π«Ά
Note: The parser skeleton supplied bybtyacc's upstream author only compiles as C++. Use the skeleton/usr/share/doc/btyacc/examples/btyacc-c.sketo generate a parser that compiles both as C and C++. (Unfortunately, this alternative skeleton does not currently checkmalloc()return values.) π
π Options π
-b prefixβ Change the prefix prepended to the output file names to the string denoted by prefix. The default prefix is the charactery. β¨-dβ Create a header file calledprefix.tab.halong withprefix.tab.c, containing the symbol definitions and a declaration forYYSTYPEandyylval. π-DNAMEβ Define thebtyaccpreprocessor variableNAME, for use with%ifdef NAMEdirectives in the grammar file. π-Eβ Print the preprocessed grammar to standard output. π₯-lβ Do not insert#linedirectives into the generated parser code. π-rβ Write the parser code and the associated tables to different files. Whereas the tables can be found inprefix.tab.cas before, the code now gets written toprefix.code.c. π-S x.skeβ Select a different parser skeleton. The default skeleton is hardwired into the program, but a copy can be found in the filebtyaccpa.ske. π§-tβ Cause debugging code to be compiled into the generated parser. π-vβ Write a human-readable description of the generated parser toy.output. It includes parser states, actions for a look-ahead token and information about any conflicts. β
π¦ BTYACC extensions π¦
Backtracking support π
Okay bestie, so whenever a btyacc generated parser runs into a shift-reduce or reduce-reduce error in the parse table, it remembers the current parse point (like, the stack and the input stream state, no cap), and slides into trial parse mode. Then it keeps parsing, ignoring most rule actions. If it runs into an error β either through the parse table or because an action calls YYERROR β it backtracks to the most recent conflict point and tries a different alternative. If it finds a successful path (reaches the end of the input, or an action calls YYVALID), it backtracks to the point where it first entered trial parse mode, and continues with a full parse (executing all actions), following the path of the successful trial. Periodt. β¨
Actions in btyacc come in two flavors: {} actions, which are only executed when not in trial mode, and [] actions, which are executed regardless of mode. Slay.
Example: In YACC grammars for C, a standard hack known as the "lexer feedback hack" is used to find typedef names. The lexer uses semantic information to decide if any given identifier is a typedef name or not and returns a special token. With btyacc, you no longer need to do this; the lexer should just always return an identifier. The btyacc grammar then needs a rule of the form:
typename: ID [ if (!IsTypeName(LookupId($1))) YYERROR; ]
However, note that adding backtracking rules slows down the parser. In practice, you should try to restrict the number of conflicts in the grammar to what is absolutely necessary. Consider using the "lexer feedback hack" if it is a clean solution, and reserve backtracking for a few special cases. It's giving "use sparingly, queen". π
btyacc runs its trials using the rule "try shifting first, then try reducing in the order that the conflicting rules appear in the input file". This means you can implement semantic disambiguation rules like, for example: (1) If it looks like a declaration it is, otherwise (2) If it looks like an expression it is, otherwise (3) it is a syntax error [Ellis & Stroustrup, Annotated C++ Reference Manual, p93]. To achieve this, put all the rules for declarations before the rules for expressions in the grammar file. Iconic.
Backtracking is only triggered when the parse hits a shift/reduce or reduce/reduce conflict in the table. If you have no conflicts in your grammar, there is no extra cost, other than some extra code which will never be invoked. So chill. β¨
Currently, the generated parser performs no pruning of alternate parsing paths. To avoid an exponential explosion of possible paths (and parsing time), you need to manually tell the parser when it can throw away saved paths using the YYVALID statement. In practice, this turns out to be fairly easy to do. For example, a C++ parser can just contain [YYVALID;] after every complete declaration and statement rule, resulting in the backtracking state being pruned after seeing a ; or } β there will never be a situation in which it is useful to backtrack past either of these. Obsessed with that. π₯
Improved token position handling π
Compilers often need to build ASTs (abstract syntax trees) such that every node in a tree can relate to the parsed program source it came from. The YYPOSN mechanism supported by btyacc helps you in automating the text position computation and in assigning the computed text positions to the AST nodes. It's giving compiler glow-up. π§
In standard YACCs every token and every non-terminal has an YYSTYPE semantic value attached to it. With btyacc, every token and every non-terminal also has an YYPOSN text position attached to it. YYPOSN is a user-defined type.
btyacc maintains a stack of text position values in the same way that it maintains a stack of semantic values. To make use of the text position feature, you need to #define the following:
YYPOSNβ Preprocessor symbol for the C/C++ type of the text position attached to every token and non-terminal.yyposnβ Global variable of typeYYPOSN. The lexer must assign the text position of the returned token toyyposn, just like it assigns the semantic value of the returned token toyylval.YYREDUCEPOSNFUNCβ Preprocessor symbol for a function that is called immediately after the regular grammar rule reduction has been performed, to reduce text positions located on the stack.
Typically, this function extracts text positions from the right-hand side rule components and either assigns them to the returned $$ structure/tree or, if no $$ value is returned, puts them into the ret text position where it will be picked up by other rules later. Its prototype is:
void ReducePosn(
YYPOSN& ret,
YYPOSN* term_posns,
YYSTYPE* term_vals,
int term_no,
int stk_pos,
int yychar,
YYPOSN& yyposn,
UserType extra);
retβ Reference to the text position returned by the rule. You must overwrite this with the computed text position that the rule yields, analogous to the$$semantic value.term_posnsβ Array of the right-hand side rule components'YYPOSNtext positions, analogous to$1,$2, ...,$Nfor the semantic values.term_valsβ Array of the right-hand side rule components'YYSTYPEvalues. These are the$1, ...,$Nthemselves.term_noβ Number of components in the right hand side of the reduced rule, i.e. the size of theterm_posnsandterm_valsarrays. Also equal toNin$1, ...,$N.stk_posβYYSTYPE/YYPOSNstack position before the reduction.yycharβ Lookahead token that immediately follows the reduced right hand side components.yyposnβYYPOSNof the token that immediately follows the reduced right hand side components.extraβ User-defined extra argument passed toReducePosn.YYREDUCEPOSNFUNCARGβ Extra argument passed to theReducePosnfunction. This argument can be any variable defined inbtyaccpa.ske.
Token deallocation during error recovery π§Ή
For most YACC-like parser generators, the action of the generated parser upon encountering a parse error is to throw away semantic values and input tokens until a rule containing the special non-terminal error can be matched. Discarding of tokens is simply performed by overwriting variables and array entries of type YYSTYPE with new values. Messy, right? π
Unfortunately, this approach leads to a memory leak if YYSTYPE is a pointer type. btyacc allows you to supply functions for cleaning up the semantic and text position values, by #defineing the following symbols in the preamble of your grammar file:
YYDELETEVALβ Preprocessor symbol for a function to call before the semantic value of a token or non-terminal is discarded.YYDELETEPOSNβ Preprocessor symbol for a function to call before the text position of a token or non-terminal is discarded.
Both functions are called with two arguments. The first argument of type YYSTYPE or YYPOSN is the value that will be discarded. The second argument is of type int and is one of three values:
0β discarding input token1β discarding state on stack2β cleaning up stack when aborting
Detailed syntax error reporting π
If you #define the preprocessor variable YYERROR_DETAILED in your grammar file, you must also define the following error processing function:
void yyerror_detailed(
char* text,
int errt,
YYSTYPE&
errt_value,
YYPOSN& errt_posn);
textβ error messageerrtβ code of the token that caused the errorerrt_valueβ value of the token that caused the errorerrt_posnβ text position of token that caused error
Preprocessor directives πͺ
btyacc supports defining symbols and acting on them with conditional directives inside grammar files, not unlike the C preprocessor. It's giving mini-C preprocessor but make it parser. β¨
%define NAMEβ Define the preprocessor symbolNAME. Equivalent to the command line switch-DNAME.%ifdef NAMEβ If preprocessor variableNAMEis defined, process the text from this%ifdefto the closing%endif, otherwise skip it.%endifβ Closing directive for%ifdef.%ifdefs cannot be nested.%include FILENAMEβ Process contents of the file namedFILENAME. Only one nesting level of%includeis allowed.%ident STRINGβ Insert an#ident STRINGdirective into the output file.STRINGmust be a string constant enclosed in"".
Inherited attributes π§¬
Inherited attributes are undocumented. (See the README and the btyacc source code for a little information.) If you work out how they work, contact me at <atterer@debian.org>! Seriously, bestie, crack the code and slide into the email. π
π Bugs π
The worst-case complexity of parsing is exponential for any grammar which allows backtracking to take place. In other words, a btyacc-generated parser constitutes a denial-of-service bug if used in applications where an attacker is able to supply specially crafted data as input to the parser. (For all "regular" input data, the potentially exponential complexity is not normally an issue.) So like, do not let randos feed your parser weird stuff. π¨
bison's %expect directive is not supported.
There is no %else and %ifndef. %ifdefs and %includes cannot be nested.
π Authors π
Robert Corbett <robert.corbett@eng.sun.com> / <corbett@berkeley.edu> was one of the original authors of Berkeley byacc. Chris Dodd <chrisd@reservoir.com> had the brilliant idea of adding backtracking capabilities, and is responsible for the initial backtracking changes. Vadim Maslov <vadik@siber.com> further improved the code. Legends, honestly. π«Ά
This documentation was written by Richard Atterer <atterer@debian.org> for the Debian GNU/Linux distribution, but is donated to the public domain and may thus be used freely for any purpose. Public domain slay. π
π Files π
/usr/share/doc/btyacc/examples/btyaccpa.ske/usr/share/doc/btyacc/examples/btyacc-c.ske/usr/share/doc/btyacc/README
π See also π
That's a wrap on the btyacc(1) manual page, bestie β if your system shows a source/version and date footer down there, that's the footer energy, but we're not copying the line, we're just signing off. Byeee! π β¨
π¦ where this page comes from
- debian bookworm: btyacc 3.0+dfsg-1 Β· LicenseRef-public-domain
- debian trixie: btyacc 3.0+dfsg-2 Β· LicenseRef-public-domain
- ubuntu jammy: btyacc 3.0+dfsg-1 Β· LicenseRef-public-domain
- ubuntu noble: btyacc 3.0+dfsg-1 Β· LicenseRef-public-domain
- ubuntu questing: btyacc 3.0+dfsg-2
- ubuntu resolute: btyacc 3.0+dfsg-2build1 Β· LicenseRef-public-domain
- ubuntu stonking: btyacc 3.0+dfsg-3 Β· LicenseRef-public-domain
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms