Server IP : 103.119.228.120 / Your IP : 3.144.93.34 Web Server : Apache System : Linux v8.techscape8.com 3.10.0-1160.119.1.el7.tuxcare.els2.x86_64 #1 SMP Mon Jul 15 12:09:18 UTC 2024 x86_64 User : nobody ( 99) PHP Version : 5.6.40 Disable Function : shell_exec,symlink,system,exec,proc_get_status,proc_nice,proc_terminate,define_syslog_variables,syslog,openlog,closelog,escapeshellcmd,passthru,ocinum cols,ini_alter,leak,listen,chgrp,apache_note,apache_setenv,debugger_on,debugger_off,ftp_exec,dl,dll,myshellexec,proc_open,socket_bind,proc_close,escapeshellarg,parse_ini_filepopen,fpassthru,exec,passthru,escapeshellarg,escapeshellcmd,proc_close,proc_open,ini_alter,popen,show_source,proc_nice,proc_terminate,proc_get_status,proc_close,pfsockopen,leak,apache_child_terminate,posix_kill,posix_mkfifo,posix_setpgid,posix_setsid,posix_setuid,dl,symlink,shell_exec,system,dl,passthru,escapeshellarg,escapeshellcmd,myshellexec,c99_buff_prepare,c99_sess_put,fpassthru,getdisfunc,fx29exec,fx29exec2,is_windows,disp_freespace,fx29sh_getupdate,fx29_buff_prepare,fx29_sess_put,fx29shexit,fx29fsearch,fx29ftpbrutecheck,fx29sh_tools,fx29sh_about,milw0rm,imagez,sh_name,myshellexec,checkproxyhost,dosyayicek,c99_buff_prepare,c99_sess_put,c99getsource,c99sh_getupdate,c99fsearch,c99shexit,view_perms,posix_getpwuid,posix_getgrgid,posix_kill,parse_perms,parsesort,view_perms_color,set_encoder_input,ls_setcheckboxall,ls_reverse_all,rsg_read,rsg_glob,selfURL,dispsecinfo,unix2DosTime,addFile,system,get_users,view_size,DirFiles,DirFilesWide,DirPrintHTMLHeaders,GetFilesTotal,GetTitles,GetTimeTotal,GetMatchesCount,GetFileMatchesCount,GetResultFiles,fs_copy_dir,fs_copy_obj,fs_move_dir,fs_move_obj,fs_rmdir,SearchText,getmicrotime MySQL : ON | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /usr/local/ssl/local/ssl/local/share/man/man3/ |
Upload File : |
.\" Automatically generated by Pod::Man 2.27 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "Parse::RecDescent 3" .TH Parse::RecDescent 3 "2016-08-24" "perl v5.16.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Parse::RecDescent \- Generate Recursive\-Descent Parsers .SH "VERSION" .IX Header "VERSION" This document describes version 1.967013 of Parse::RecDescent released September 27th, 2015. .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use Parse::RecDescent; \& \& # Generate a parser from the specification in $grammar: \& \& $parser = new Parse::RecDescent ($grammar); \& \& # Generate a parser from the specification in $othergrammar \& \& $anotherparser = new Parse::RecDescent ($othergrammar); \& \& \& # Parse $text using rule \*(Aqstartrule\*(Aq (which must be \& # defined in $grammar): \& \& $parser\->startrule($text); \& \& \& # Parse $text using rule \*(Aqotherrule\*(Aq (which must also \& # be defined in $grammar): \& \& $parser\->otherrule($text); \& \& \& # Change the universal token prefix pattern \& # before building a grammar \& # (the default is: \*(Aq\es*\*(Aq): \& \& $Parse::RecDescent::skip = \*(Aq[ \et]+\*(Aq; \& \& \& # Replace productions of existing rules (or create new ones) \& # with the productions defined in $newgrammar: \& \& $parser\->Replace($newgrammar); \& \& \& # Extend existing rules (or create new ones) \& # by adding extra productions defined in $moregrammar: \& \& $parser\->Extend($moregrammar); \& \& \& # Global flags (useful as command line arguments under \-s): \& \& $::RD_ERRORS # unless undefined, report fatal errors \& $::RD_WARN # unless undefined, also report non\-fatal problems \& $::RD_HINT # if defined, also suggestion remedies \& $::RD_TRACE # if defined, also trace parsers\*(Aq behaviour \& $::RD_AUTOSTUB # if defined, generates "stubs" for undefined rules \& $::RD_AUTOACTION # if defined, appends specified action to productions .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" .SS "Overview" .IX Subsection "Overview" Parse::RecDescent incrementally generates top-down recursive-descent text parsers from simple \fIyacc\fR\-like grammar specifications. It provides: .IP "\(bu" 4 Regular expressions or literal strings as terminals (tokens), .IP "\(bu" 4 Multiple (non-contiguous) productions for any rule, .IP "\(bu" 4 Repeated and optional subrules within productions, .IP "\(bu" 4 Full access to Perl within actions specified as part of the grammar, .IP "\(bu" 4 Simple automated error reporting during parser generation and parsing, .IP "\(bu" 4 The ability to commit to, uncommit to, or reject particular productions during a parse, .IP "\(bu" 4 The ability to pass data up and down the parse tree (\*(L"down\*(R" via subrule argument lists, \*(L"up\*(R" via subrule return values) .IP "\(bu" 4 Incremental extension of the parsing grammar (even during a parse), .IP "\(bu" 4 Precompilation of parser objects, .IP "\(bu" 4 User-definable reduce-reduce conflict resolution via \&\*(L"scoring\*(R" of matching productions. .ie n .SS "Using ""Parse::RecDescent""" .el .SS "Using \f(CWParse::RecDescent\fP" .IX Subsection "Using Parse::RecDescent" Parser objects are created by calling \f(CW\*(C`Parse::RecDescent::new\*(C'\fR, passing in a grammar specification (see the following subsections). If the grammar is correct, \f(CW\*(C`new\*(C'\fR returns a blessed reference which can then be used to initiate parsing through any rule specified in the original grammar. A typical sequence looks like this: .PP .Vb 3 \& $grammar = q { \& # GRAMMAR SPECIFICATION HERE \& }; \& \& $parser = new Parse::RecDescent ($grammar) or die "Bad grammar!\en"; \& \& # acquire $text \& \& defined $parser\->startrule($text) or print "Bad text!\en"; .Ve .PP The rule through which parsing is initiated must be explicitly defined in the grammar (i.e. for the above example, the grammar must include a rule of the form: \*(L"startrule: <subrules>\*(R". .PP If the starting rule succeeds, its value (see below) is returned. Failure to generate the original parser or failure to match a text is indicated by returning \f(CW\*(C`undef\*(C'\fR. Note that it's easy to set up grammars that can succeed, but which return a value of 0, \*(L"0\*(R", or "". So don't be tempted to write: .PP .Vb 1 \& $parser\->startrule($text) or print "Bad text!\en"; .Ve .PP Normally, the parser has no effect on the original text. So in the previous example the value of \f(CW$text\fR would be unchanged after having been parsed. .PP If, however, the text to be matched is passed by reference: .PP .Vb 1 \& $parser\->startrule(\e$text) .Ve .PP then any text which was consumed during the match will be removed from the start of \f(CW$text\fR. .SS "Rules" .IX Subsection "Rules" In the grammar from which the parser is built, rules are specified by giving an identifier (which must satisfy /[A\-Za\-z]\ew*/), followed by a colon \fIon the same line\fR, followed by one or more productions, separated by single vertical bars. The layout of the productions is entirely free-format: .PP .Vb 3 \& rule1: production1 \& | production2 | \& production3 | production4 .Ve .PP At any point in the grammar previously defined rules may be extended with additional productions. This is achieved by redeclaring the rule with the new productions. Thus: .PP .Vb 3 \& rule1: a | b | c \& rule2: d | e | f \& rule1: g | h .Ve .PP is exactly equivalent to: .PP .Vb 2 \& rule1: a | b | c | g | h \& rule2: d | e | f .Ve .PP Each production in a rule consists of zero or more items, each of which may be either: the name of another rule to be matched (a \*(L"subrule\*(R"), a pattern or string literal to be matched directly (a \*(L"token\*(R"), a block of Perl code to be executed (an \*(L"action\*(R"), a special instruction to the parser (a \*(L"directive\*(R"), or a standard Perl comment (which is ignored). .PP A rule matches a text if one of its productions matches. A production matches if each of its items match consecutive substrings of the text. The productions of a rule being matched are tried in the same order that they appear in the original grammar, and the first matching production terminates the match attempt (successfully). If all productions are tried and none matches, the match attempt fails. .PP Note that this behaviour is quite different from the \*(L"prefer the longer match\*(R" behaviour of \fIyacc\fR. For example, if \fIyacc\fR were parsing the rule: .PP .Vb 2 \& seq : \*(AqA\*(Aq \*(AqB\*(Aq \& | \*(AqA\*(Aq \*(AqB\*(Aq \*(AqC\*(Aq .Ve .PP upon matching \*(L"\s-1AB\*(R"\s0 it would look ahead to see if a 'C' is next and, if so, will match the second production in preference to the first. In other words, \fIyacc\fR effectively tries all the productions of a rule breadth-first in parallel, and selects the \*(L"best\*(R" match, where \*(L"best\*(R" means longest (note that this is a gross simplification of the true behaviour of \fIyacc\fR but it will do for our purposes). .PP In contrast, \f(CW\*(C`Parse::RecDescent\*(C'\fR tries each production depth-first in sequence, and selects the \*(L"best\*(R" match, where \*(L"best\*(R" means first. This is the fundamental difference between \*(L"bottom-up\*(R" and \*(L"recursive descent\*(R" parsing. .PP Each successfully matched item in a production is assigned a value, which can be accessed in subsequent actions within the same production (or, in some cases, as the return value of a successful subrule call). Unsuccessful items don't have an associated value, since the failure of an item causes the entire surrounding production to immediately fail. The following sections describe the various types of items and their success values. .SS "Subrules" .IX Subsection "Subrules" A subrule which appears in a production is an instruction to the parser to attempt to match the named rule at that point in the text being parsed. If the named subrule is not defined when requested the production containing it immediately fails (unless it was \*(L"autostubbed\*(R" \- see Autostubbing). .PP A rule may (recursively) call itself as a subrule, but \fInot\fR as the left-most item in any of its productions (since such recursions are usually non-terminating). .PP The value associated with a subrule is the value associated with its \&\f(CW$return\fR variable (see \*(L"Actions\*(R" below), or with the last successfully matched item in the subrule match. .PP Subrules may also be specified with a trailing repetition specifier, indicating that they are to be (greedily) matched the specified number of times. The available specifiers are: .PP .Vb 7 \& subrule(?) # Match one\-or\-zero times \& subrule(s) # Match one\-or\-more times \& subrule(s?) # Match zero\-or\-more times \& subrule(N) # Match exactly N times for integer N > 0 \& subrule(N..M) # Match between N and M times \& subrule(..M) # Match between 1 and M times \& subrule(N..) # Match at least N times .Ve .PP Repeated subrules keep matching until either the subrule fails to match, or it has matched the minimal number of times but fails to consume any of the parsed text (this second condition prevents the subrule matching forever in some cases). .PP Since a repeated subrule may match many instances of the subrule itself, the value associated with it is not a simple scalar, but rather a reference to a list of scalars, each of which is the value associated with one of the individual subrule matches. In other words in the rule: .PP .Vb 1 \& program: statement(s) .Ve .PP the value associated with the repeated subrule \*(L"statement(s)\*(R" is a reference to an array containing the values matched by each call to the individual subrule \*(L"statement\*(R". .PP Repetition modifiers may include a separator pattern: .PP .Vb 1 \& program: statement(s /;/) .Ve .PP specifying some sequence of characters to be skipped between each repetition. This is really just a shorthand for the <leftop:...> directive (see below). .SS "Tokens" .IX Subsection "Tokens" If a quote-delimited string or a Perl regex appears in a production, the parser attempts to match that string or pattern at that point in the text. For example: .PP .Vb 1 \& typedef: "typedef" typename identifier \*(Aq;\*(Aq \& \& identifier: /[A\-Za\-z_][A\-Za\-z0\-9_]*/ .Ve .PP As in regular Perl, a single quoted string is uninterpolated, whilst a double-quoted string or a pattern is interpolated (at the time of matching, \fInot\fR when the parser is constructed). Hence, it is possible to define rules in which tokens can be set at run-time: .PP .Vb 1 \& typedef: "$::typedefkeyword" typename identifier \*(Aq;\*(Aq \& \& identifier: /$::identpat/ .Ve .PP Note that, since each rule is implemented inside a special namespace belonging to its parser, it is necessary to explicitly quantify variables from the main package. .PP Regex tokens can be specified using just slashes as delimiters or with the explicit \f(CW\*(C`m<delimiter>......<delimiter>\*(C'\fR syntax: .PP .Vb 1 \& typedef: "typedef" typename identifier \*(Aq;\*(Aq \& \& typename: /[A\-Za\-z_][A\-Za\-z0\-9_]*/ \& \& identifier: m{[A\-Za\-z_][A\-Za\-z0\-9_]*} .Ve .PP A regex of either type can also have any valid trailing parameter(s) (that is, any of [cgimsox]): .PP .Vb 1 \& typedef: "typedef" typename identifier \*(Aq;\*(Aq \& \& identifier: / [a\-z_] # LEADING ALPHA OR UNDERSCORE \& [a\-z0\-9_]* # THEN DIGITS ALSO ALLOWED \& /ix # CASE/SPACE/COMMENT INSENSITIVE .Ve .PP The value associated with any successfully matched token is a string containing the actual text which was matched by the token. .PP It is important to remember that, since each grammar is specified in a Perl string, all instances of the universal escape character '\e' within a grammar must be \*(L"doubled\*(R", so that they interpolate to single '\e's when the string is compiled. For example, to use the grammar: .PP .Vb 3 \& word: /\eS+/ | backslash \& line: prefix word(s) "\en" \& backslash: \*(Aq\e\e\*(Aq .Ve .PP the following code is required: .PP .Vb 1 \& $parser = new Parse::RecDescent (q{ \& \& word: /\e\eS+/ | backslash \& line: prefix word(s) "\e\en" \& backslash: \*(Aq\e\e\e\e\*(Aq \& \& }); .Ve .SS "Anonymous subrules" .IX Subsection "Anonymous subrules" Parentheses introduce a nested scope that is very like a call to an anonymous subrule. Hence they are useful for \*(L"in-lining\*(R" subroutine calls, and other kinds of grouping behaviour. For example, instead of: .PP .Vb 2 \& word: /\eS+/ | backslash \& line: prefix word(s) "\en" .Ve .PP you could write: .PP .Vb 1 \& line: prefix ( /\eS+/ | backslash )(s) "\en" .Ve .PP and get exactly the same effects. .PP Parentheses are also use for collecting unrepeated alternations within a single production. .PP .Vb 1 \& secret_identity: "Mr" ("Incredible"|"Fantastic"|"Sheen") ", Esq." .Ve .SS "Terminal Separators" .IX Subsection "Terminal Separators" For the purpose of matching, each terminal in a production is considered to be preceded by a \*(L"prefix\*(R" \- a pattern which must be matched before a token match is attempted. By default, the prefix is optional whitespace (which always matches, at least trivially), but this default may be reset in any production. .PP The variable \f(CW$Parse::RecDescent::skip\fR stores the universal prefix, which is the default for all terminal matches in all parsers built with \f(CW\*(C`Parse::RecDescent\*(C'\fR. .PP If you want to change the universal prefix using \&\f(CW$Parse::RecDescent::skip\fR, be careful to set it \fIbefore\fR creating the grammar object, because it is applied statically (when a grammar is built) rather than dynamically (when the grammar is used). Alternatively you can provide a global \f(CW\*(C`<skip:...>\*(C'\fR directive in your grammar before any rules (described later). .PP The prefix for an individual production can be altered by using the \f(CW\*(C`<skip:...>\*(C'\fR directive (described later). Setting this directive in the top-level rule is an alternative approach to setting \f(CW$Parse::RecDescent::skip\fR before creating the object, but in this case you don't get the intended skipping behaviour if you directly invoke methods different from the top-level rule. .SS "Actions" .IX Subsection "Actions" An action is a block of Perl code which is to be executed (as the block of a \f(CW\*(C`do\*(C'\fR statement) when the parser reaches that point in a production. The action executes within a special namespace belonging to the active parser, so care must be taken in correctly qualifying variable names (see also \*(L"Start-up Actions\*(R" below). .PP The action is considered to succeed if the final value of the block is defined (that is, if the implied \f(CW\*(C`do\*(C'\fR statement evaluates to a defined value \- \fIeven one which would be treated as \*(L"false\*(R"\fR). Note that the value associated with a successful action is also the final value in the block. .PP An action will \fIfail\fR if its last evaluated value is \f(CW\*(C`undef\*(C'\fR. This is surprisingly easy to accomplish by accident. For instance, here's an infuriating case of an action that makes its production fail, but only when debugging \fIisn't\fR activated: .PP .Vb 4 \& description: name rank serial_number \& { print "Got $item[2] $item[1] ($item[3])\en" \& if $::debugging \& } .Ve .PP If \f(CW$debugging\fR is false, no statement in the block is executed, so the final value is \f(CW\*(C`undef\*(C'\fR, and the entire production fails. The solution is: .PP .Vb 5 \& description: name rank serial_number \& { print "Got $item[2] $item[1] ($item[3])\en" \& if $::debugging; \& 1; \& } .Ve .PP Within an action, a number of useful parse-time variables are available in the special parser namespace (there are other variables also accessible, but meddling with them will probably just break your parser. As a general rule, if you avoid referring to unqualified variables \- especially those starting with an underscore \- inside an action, things should be okay): .ie n .IP "@item and %item" 4 .el .IP "\f(CW@item\fR and \f(CW%item\fR" 4 .IX Item "@item and %item" The array slice \f(CW@item[1..$#item]\fR stores the value associated with each item (that is, each subrule, token, or action) in the current production. The analogy is to \f(CW$1\fR, \f(CW$2\fR, etc. in a \fIyacc\fR grammar. Note that, for obvious reasons, \f(CW@item\fR only contains the values of items \fIbefore\fR the current point in the production. .Sp The first element (\f(CW$item[0]\fR) stores the name of the current rule being matched. .Sp \&\f(CW@item\fR is a standard Perl array, so it can also be indexed with negative numbers, representing the number of items \fIback\fR from the current position in the parse: .Sp .Vb 3 \& stuff: /various/ bits \*(Aqand\*(Aq pieces "then" data \*(Aqend\*(Aq \& { print $item[\-2] } # PRINTS data \& # (EASIER THAN: $item[6]) .Ve .Sp The \f(CW%item\fR hash complements the <@item> array, providing named access to the same item values: .Sp .Vb 3 \& stuff: /various/ bits \*(Aqand\*(Aq pieces "then" data \*(Aqend\*(Aq \& { print $item{data} # PRINTS data \& # (EVEN EASIER THAN USING @item) .Ve .Sp The results of named subrules are stored in the hash under each subrule's name (including the repetition specifier, if any), whilst all other items are stored under a \*(L"named positional\*(R" key that indicates their ordinal position within their item type: _\|_STRING\fIn\fR_\|_, _\|_PATTERN\fIn\fR_\|_, _\|_DIRECTIVE\fIn\fR_\|_, _\|_ACTION\fIn\fR_\|_: .Sp .Vb 6 \& stuff: /various/ bits \*(Aqand\*(Aq pieces "then" data \*(Aqend\*(Aq { save } \& { print $item{_\|_PATTERN1_\|_}, # PRINTS \*(Aqvarious\*(Aq \& $item{_\|_STRING2_\|_}, # PRINTS \*(Aqthen\*(Aq \& $item{_\|_ACTION1_\|_}, # PRINTS RETURN \& # VALUE OF save \& } .Ve .Sp If you want proper \fInamed\fR access to patterns or literals, you need to turn them into separate rules: .Sp .Vb 3 \& stuff: various bits \*(Aqand\*(Aq pieces "then" data \*(Aqend\*(Aq \& { print $item{various} # PRINTS various \& } \& \& various: /various/ .Ve .Sp The special entry \f(CW$item{_\|_RULE_\|_}\fR stores the name of the current rule (i.e. the same value as \f(CW$item[0]\fR. .Sp The advantage of using \f(CW%item\fR, instead of \f(CW@items\fR is that it removes the need to track items positions that may change as a grammar evolves. For example, adding an interim \f(CW\*(C`<skip>\*(C'\fR directive of action can silently ruin a trailing action, by moving an \f(CW@item\fR element \*(L"down\*(R" the array one place. In contrast, the named entry of \f(CW%item\fR is unaffected by such an insertion. .Sp A limitation of the \f(CW%item\fR hash is that it only records the \fIlast\fR value of a particular subrule. For example: .Sp .Vb 2 \& range: \*(Aq(\*(Aq number \*(Aq..\*(Aq number )\*(Aq \& { $return = $item{number} } .Ve .Sp will return only the value corresponding to the \fIsecond\fR match of the \&\f(CW\*(C`number\*(C'\fR subrule. In other words, successive calls to a subrule overwrite the corresponding entry in \f(CW%item\fR. Once again, the solution is to rename each subrule in its own rule: .Sp .Vb 2 \& range: \*(Aq(\*(Aq from_num \*(Aq..\*(Aq to_num \*(Aq)\*(Aq \& { $return = $item{from_num} } \& \& from_num: number \& to_num: number .Ve .ie n .IP "@arg and %arg" 4 .el .IP "\f(CW@arg\fR and \f(CW%arg\fR" 4 .IX Item "@arg and %arg" The array \f(CW@arg\fR and the hash \f(CW%arg\fR store any arguments passed to the rule from some other rule (see \*(L"Subrule argument lists\*(R"). Changes to the elements of either variable do not propagate back to the calling rule (data can be passed back from a subrule via the \f(CW$return\fR variable \- see next item). .ie n .IP "$return" 4 .el .IP "\f(CW$return\fR" 4 .IX Item "$return" If a value is assigned to \f(CW$return\fR within an action, that value is returned if the production containing the action eventually matches successfully. Note that setting \f(CW$return\fR \fIdoesn't\fR cause the current production to succeed. It merely tells it what to return if it \fIdoes\fR succeed. Hence \f(CW$return\fR is analogous to \f(CW$$\fR in a \fIyacc\fR grammar. .Sp If \f(CW$return\fR is not assigned within a production, the value of the last component of the production (namely: \f(CW$item[$#item]\fR) is returned if the production succeeds. .ie n .IP "$commit" 4 .el .IP "\f(CW$commit\fR" 4 .IX Item "$commit" The current state of commitment to the current production (see \*(L"Directives\*(R" below). .ie n .IP "$skip" 4 .el .IP "\f(CW$skip\fR" 4 .IX Item "$skip" The current terminal prefix (see \*(L"Directives\*(R" below). .ie n .IP "$text" 4 .el .IP "\f(CW$text\fR" 4 .IX Item "$text" The remaining (unparsed) text. Changes to \f(CW$text\fR \fIdo not propagate\fR out of unsuccessful productions, but \fIdo\fR survive successful productions. Hence it is possible to dynamically alter the text being parsed \- for example, to provide a \f(CW\*(C`#include\*(C'\fR\-like facility: .Sp .Vb 2 \& hash_include: \*(Aq#include\*(Aq filename \& { $text = ::loadfile($item[2]) . $text } \& \& filename: \*(Aq<\*(Aq /[a\-z0\-9._\-]+/i \*(Aq>\*(Aq { $return = $item[2] } \& | \*(Aq"\*(Aq /[a\-z0\-9._\-]+/i \*(Aq"\*(Aq { $return = $item[2] } .Ve .ie n .IP "$thisline and $prevline" 4 .el .IP "\f(CW$thisline\fR and \f(CW$prevline\fR" 4 .IX Item "$thisline and $prevline" \&\f(CW$thisline\fR stores the current line number within the current parse (starting from 1). \f(CW$prevline\fR stores the line number for the last character which was already successfully parsed (this will be different from \&\f(CW$thisline\fR at the end of each line). .Sp For efficiency, \f(CW$thisline\fR and \f(CW$prevline\fR are actually tied hashes, and only recompute the required line number when the variable's value is used. .Sp Assignment to \f(CW$thisline\fR adjusts the line number calculator, so that it believes that the current line number is the value being assigned. Note that this adjustment will be reflected in all subsequent line numbers calculations. .Sp Modifying the value of the variable \f(CW$text\fR (as in the previous \&\f(CW\*(C`hash_include\*(C'\fR example, for instance) will confuse the line counting mechanism. To prevent this, you should call \&\f(CW\*(C`Parse::RecDescent::LineCounter::resync($thisline)\*(C'\fR \fIimmediately\fR after any assignment to the variable \f(CW$text\fR (or, at least, before the next attempt to use \f(CW$thisline\fR). .Sp Note that if a production fails after assigning to or resync'ing \f(CW$thisline\fR, the parser's line counter mechanism will usually be corrupted. .Sp Also see the entry for \f(CW@itempos\fR. .Sp The line number can be set to values other than 1, by calling the start rule with a second argument. For example: .Sp .Vb 1 \& $parser = new Parse::RecDescent ($grammar); \& \& $parser\->input($text, 10); # START LINE NUMBERS AT 10 .Ve .ie n .IP "$thiscolumn and $prevcolumn" 4 .el .IP "\f(CW$thiscolumn\fR and \f(CW$prevcolumn\fR" 4 .IX Item "$thiscolumn and $prevcolumn" \&\f(CW$thiscolumn\fR stores the current column number within the current line being parsed (starting from 1). \f(CW$prevcolumn\fR stores the column number of the last character which was actually successfully parsed. Usually \&\f(CW\*(C`$prevcolumn == $thiscolumn\-1\*(C'\fR, but not at the end of lines. .Sp For efficiency, \f(CW$thiscolumn\fR and \f(CW$prevcolumn\fR are actually tied hashes, and only recompute the required column number when the variable's value is used. .Sp Assignment to \f(CW$thiscolumn\fR or \f(CW$prevcolumn\fR is a fatal error. .Sp Modifying the value of the variable \f(CW$text\fR (as in the previous \&\f(CW\*(C`hash_include\*(C'\fR example, for instance) may confuse the column counting mechanism. .Sp Note that \f(CW$thiscolumn\fR reports the column number \fIbefore\fR any whitespace that might be skipped before reading a token. Hence if you wish to know where a token started (and ended) use something like this: .Sp .Vb 2 \& rule: token1 token2 startcol token3 endcol token4 \& { print "token3: columns $item[3] to $item[5]"; } \& \& startcol: \*(Aq\*(Aq { $thiscolumn } # NEED THE \*(Aq\*(Aq TO STEP PAST TOKEN SEP \& endcol: { $prevcolumn } .Ve .Sp Also see the entry for \f(CW@itempos\fR. .ie n .IP "$thisoffset and $prevoffset" 4 .el .IP "\f(CW$thisoffset\fR and \f(CW$prevoffset\fR" 4 .IX Item "$thisoffset and $prevoffset" \&\f(CW$thisoffset\fR stores the offset of the current parsing position within the complete text being parsed (starting from 0). \f(CW$prevoffset\fR stores the offset of the last character which was actually successfully parsed. In all cases \f(CW\*(C`$prevoffset == $thisoffset\-1\*(C'\fR. .Sp For efficiency, \f(CW$thisoffset\fR and \f(CW$prevoffset\fR are actually tied hashes, and only recompute the required offset when the variable's value is used. .Sp Assignment to \f(CW$thisoffset\fR or <$prevoffset> is a fatal error. .Sp Modifying the value of the variable \f(CW$text\fR will \fInot\fR affect the offset counting mechanism. .Sp Also see the entry for \f(CW@itempos\fR. .ie n .IP "@itempos" 4 .el .IP "\f(CW@itempos\fR" 4 .IX Item "@itempos" The array \f(CW@itempos\fR stores a hash reference corresponding to each element of \f(CW@item\fR. The elements of the hash provide the following: .Sp .Vb 6 \& $itempos[$n]{offset}{from} # VALUE OF $thisoffset BEFORE $item[$n] \& $itempos[$n]{offset}{to} # VALUE OF $prevoffset AFTER $item[$n] \& $itempos[$n]{line}{from} # VALUE OF $thisline BEFORE $item[$n] \& $itempos[$n]{line}{to} # VALUE OF $prevline AFTER $item[$n] \& $itempos[$n]{column}{from} # VALUE OF $thiscolumn BEFORE $item[$n] \& $itempos[$n]{column}{to} # VALUE OF $prevcolumn AFTER $item[$n] .Ve .Sp Note that the various \f(CW\*(C`$itempos[$n]...{from}\*(C'\fR values record the appropriate value \fIafter\fR any token prefix has been skipped. .Sp Hence, instead of the somewhat tedious and error-prone: .Sp .Vb 9 \& rule: startcol token1 endcol \& startcol token2 endcol \& startcol token3 endcol \& { print "token1: columns $item[1] \& to $item[3] \& token2: columns $item[4] \& to $item[6] \& token3: columns $item[7] \& to $item[9]" } \& \& startcol: \*(Aq\*(Aq { $thiscolumn } # NEED THE \*(Aq\*(Aq TO STEP PAST TOKEN SEP \& endcol: { $prevcolumn } .Ve .Sp it is possible to write: .Sp .Vb 7 \& rule: token1 token2 token3 \& { print "token1: columns $itempos[1]{column}{from} \& to $itempos[1]{column}{to} \& token2: columns $itempos[2]{column}{from} \& to $itempos[2]{column}{to} \& token3: columns $itempos[3]{column}{from} \& to $itempos[3]{column}{to}" } .Ve .Sp Note however that (in the current implementation) the use of \f(CW@itempos\fR anywhere in a grammar implies that item positioning information is collected \fIeverywhere\fR during the parse. Depending on the grammar and the size of the text to be parsed, this may be prohibitively expensive and the explicit use of \f(CW$thisline\fR, \f(CW$thiscolumn\fR, etc. may be a better choice. .ie n .IP "$thisparser" 4 .el .IP "\f(CW$thisparser\fR" 4 .IX Item "$thisparser" A reference to the \f(CW\*(C`Parse::RecDescent\*(C'\fR object through which parsing was initiated. .Sp The value of \f(CW$thisparser\fR propagates down the subrules of a parse but not back up. Hence, you can invoke subrules from another parser for the scope of the current rule as follows: .Sp .Vb 4 \& rule: subrule1 subrule2 \& | { $thisparser = $::otherparser } <reject> \& | subrule3 subrule4 \& | subrule5 .Ve .Sp The result is that the production calls \*(L"subrule1\*(R" and \*(L"subrule2\*(R" of the current parser, and the remaining productions call the named subrules from \f(CW$::otherparser\fR. Note, however that \*(L"Bad Things\*(R" will happen if \&\f(CW\*(C`::otherparser\*(C'\fR isn't a blessed reference and/or doesn't have methods with the same names as the required subrules! .ie n .IP "$thisrule" 4 .el .IP "\f(CW$thisrule\fR" 4 .IX Item "$thisrule" A reference to the \f(CW\*(C`Parse::RecDescent::Rule\*(C'\fR object corresponding to the rule currently being matched. .ie n .IP "$thisprod" 4 .el .IP "\f(CW$thisprod\fR" 4 .IX Item "$thisprod" A reference to the \f(CW\*(C`Parse::RecDescent::Production\*(C'\fR object corresponding to the production currently being matched. .ie n .IP "$score and $score_return" 4 .el .IP "\f(CW$score\fR and \f(CW$score_return\fR" 4 .IX Item "$score and $score_return" \&\f(CW$score\fR stores the best production score to date, as specified by an earlier \f(CW\*(C`<score:...>\*(C'\fR directive. \f(CW$score_return\fR stores the corresponding return value for the successful production. .Sp See \*(L"Scored productions\*(R". .PP \&\fBWarning:\fR the parser relies on the information in the various \f(CW\*(C`this...\*(C'\fR objects in some non-obvious ways. Tinkering with the other members of these objects will probably cause Bad Things to happen, unless you \&\fIreally\fR know what you're doing. The only exception to this advice is that the use of \f(CW\*(C`$this...\->{local}\*(C'\fR is always safe. .SS "Start-up Actions" .IX Subsection "Start-up Actions" Any actions which appear \fIbefore\fR the first rule definition in a grammar are treated as \*(L"start-up\*(R" actions. Each such action is stripped of its outermost brackets and then evaluated (in the parser's special namespace) just before the rules of the grammar are first compiled. .PP The main use of start-up actions is to declare local variables within the parser's special namespace: .PP .Vb 1 \& { my $lastitem = \*(Aq???\*(Aq; } \& \& list: item(s) { $return = $lastitem } \& \& item: book { $lastitem = \*(Aqbook\*(Aq; } \& bell { $lastitem = \*(Aqbell\*(Aq; } \& candle { $lastitem = \*(Aqcandle\*(Aq; } .Ve .PP but start-up actions can be used to execute \fIany\fR valid Perl code within a parser's special namespace. .PP Start-up actions can appear within a grammar extension or replacement (that is, a partial grammar installed via \f(CW\*(C`Parse::RecDescent::Extend()\*(C'\fR or \&\f(CW\*(C`Parse::RecDescent::Replace()\*(C'\fR \- see \*(L"Incremental Parsing\*(R"), and will be executed before the new grammar is installed. Note, however, that a particular start-up action is only ever executed once. .SS "Autoactions" .IX Subsection "Autoactions" It is sometimes desirable to be able to specify a default action to be taken at the end of every production (for example, in order to easily build a parse tree). If the variable \f(CW$::RD_AUTOACTION\fR is defined when \f(CW\*(C`Parse::RecDescent::new()\*(C'\fR is called, the contents of that variable are treated as a specification of an action which is to appended to each production in the corresponding grammar. .PP Alternatively, you can hard-code the autoaction within a grammar, using the \&\f(CW\*(C`<autoaction:...>\*(C'\fR directive. .PP So, for example, to construct a simple parse tree you could write: .PP .Vb 1 \& $::RD_AUTOACTION = q { [@item] }; \& \& parser = Parse::RecDescent\->new(q{ \& expression: and_expr \*(Aq||\*(Aq expression | and_expr \& and_expr: not_expr \*(Aq&&\*(Aq and_expr | not_expr \& not_expr: \*(Aq!\*(Aq brack_expr | brack_expr \& brack_expr: \*(Aq(\*(Aq expression \*(Aq)\*(Aq | identifier \& identifier: /[a\-z]+/i \& }); .Ve .PP or: .PP .Vb 2 \& parser = Parse::RecDescent\->new(q{ \& <autoaction: { [@item] } > \& \& expression: and_expr \*(Aq||\*(Aq expression | and_expr \& and_expr: not_expr \*(Aq&&\*(Aq and_expr | not_expr \& not_expr: \*(Aq!\*(Aq brack_expr | brack_expr \& brack_expr: \*(Aq(\*(Aq expression \*(Aq)\*(Aq | identifier \& identifier: /[a\-z]+/i \& }); .Ve .PP Either of these is equivalent to: .PP .Vb 5 \& parser = new Parse::RecDescent (q{ \& expression: and_expr \*(Aq||\*(Aq expression \& { [@item] } \& | and_expr \& { [@item] } \& \& and_expr: not_expr \*(Aq&&\*(Aq and_expr \& { [@item] } \& | not_expr \& { [@item] } \& \& not_expr: \*(Aq!\*(Aq brack_expr \& { [@item] } \& | brack_expr \& { [@item] } \& \& brack_expr: \*(Aq(\*(Aq expression \*(Aq)\*(Aq \& { [@item] } \& | identifier \& { [@item] } \& \& identifier: /[a\-z]+/i \& { [@item] } \& }); .Ve .PP Alternatively, we could take an object-oriented approach, use different classes for each node (and also eliminating redundant intermediate nodes): .PP .Vb 2 \& $::RD_AUTOACTION = q \& { $#item==1 ? $item[1] : "$item[0]_node"\->new(@item[1..$#item]) }; \& \& parser = Parse::RecDescent\->new(q{ \& expression: and_expr \*(Aq||\*(Aq expression | and_expr \& and_expr: not_expr \*(Aq&&\*(Aq and_expr | not_expr \& not_expr: \*(Aq!\*(Aq brack_expr | brack_expr \& brack_expr: \*(Aq(\*(Aq expression \*(Aq)\*(Aq | identifier \& identifier: /[a\-z]+/i \& }); .Ve .PP or: .PP .Vb 4 \& parser = Parse::RecDescent\->new(q{ \& <autoaction: \& $#item==1 ? $item[1] : "$item[0]_node"\->new(@item[1..$#item]) \& > \& \& expression: and_expr \*(Aq||\*(Aq expression | and_expr \& and_expr: not_expr \*(Aq&&\*(Aq and_expr | not_expr \& not_expr: \*(Aq!\*(Aq brack_expr | brack_expr \& brack_expr: \*(Aq(\*(Aq expression \*(Aq)\*(Aq | identifier \& identifier: /[a\-z]+/i \& }); .Ve .PP which are equivalent to: .PP .Vb 4 \& parser = Parse::RecDescent\->new(q{ \& expression: and_expr \*(Aq||\*(Aq expression \& { "expression_node"\->new(@item[1..3]) } \& | and_expr \& \& and_expr: not_expr \*(Aq&&\*(Aq and_expr \& { "and_expr_node"\->new(@item[1..3]) } \& | not_expr \& \& not_expr: \*(Aq!\*(Aq brack_expr \& { "not_expr_node"\->new(@item[1..2]) } \& | brack_expr \& \& brack_expr: \*(Aq(\*(Aq expression \*(Aq)\*(Aq \& { "brack_expr_node"\->new(@item[1..3]) } \& | identifier \& \& identifier: /[a\-z]+/i \& { "identifer_node"\->new(@item[1]) } \& }); .Ve .PP Note that, if a production already ends in an action, no autoaction is appended to it. For example, in this version: .PP .Vb 2 \& $::RD_AUTOACTION = q \& { $#item==1 ? $item[1] : "$item[0]_node"\->new(@item[1..$#item]) }; \& \& parser = Parse::RecDescent\->new(q{ \& expression: and_expr \*(Aq&&\*(Aq expression | and_expr \& and_expr: not_expr \*(Aq&&\*(Aq and_expr | not_expr \& not_expr: \*(Aq!\*(Aq brack_expr | brack_expr \& brack_expr: \*(Aq(\*(Aq expression \*(Aq)\*(Aq | identifier \& identifier: /[a\-z]+/i \& { \*(Aqterminal_node\*(Aq\->new($item[1]) } \& }); .Ve .PP each \f(CW\*(C`identifier\*(C'\fR match produces a \f(CW\*(C`terminal_node\*(C'\fR object, \fInot\fR an \&\f(CW\*(C`identifier_node\*(C'\fR object. .PP A level 1 warning is issued each time an \*(L"autoaction\*(R" is added to some production. .SS "Autotrees" .IX Subsection "Autotrees" A commonly needed autoaction is one that builds a parse-tree. It is moderately tricky to set up such an action (which must treat terminals differently from non-terminals), so Parse::RecDescent simplifies the process by providing the \&\f(CW\*(C`<autotree>\*(C'\fR directive. .PP If this directive appears at the start of grammar, it causes Parse::RecDescent to insert autoactions at the end of any rule except those which already end in an action. The action inserted depends on whether the production is an intermediate rule (two or more items), or a terminal of the grammar (i.e. a single pattern or string item). .PP So, for example, the following grammar: .PP .Vb 1 \& <autotree> \& \& file : command(s) \& command : get | set | vet \& get : \*(Aqget\*(Aq ident \*(Aq;\*(Aq \& set : \*(Aqset\*(Aq ident \*(Aqto\*(Aq value \*(Aq;\*(Aq \& vet : \*(Aqcheck\*(Aq ident \*(Aqis\*(Aq value \*(Aq;\*(Aq \& ident : /\ew+/ \& value : /\ed+/ .Ve .PP is equivalent to: .PP .Vb 7 \& file : command(s) { bless \e%item, $item[0] } \& command : get { bless \e%item, $item[0] } \& | set { bless \e%item, $item[0] } \& | vet { bless \e%item, $item[0] } \& get : \*(Aqget\*(Aq ident \*(Aq;\*(Aq { bless \e%item, $item[0] } \& set : \*(Aqset\*(Aq ident \*(Aqto\*(Aq value \*(Aq;\*(Aq { bless \e%item, $item[0] } \& vet : \*(Aqcheck\*(Aq ident \*(Aqis\*(Aq value \*(Aq;\*(Aq { bless \e%item, $item[0] } \& \& ident : /\ew+/ { bless {_\|_VALUE_\|_=>$item[1]}, $item[0] } \& value : /\ed+/ { bless {_\|_VALUE_\|_=>$item[1]}, $item[0] } .Ve .PP Note that each node in the tree is blessed into a class of the same name as the rule itself. This makes it easy to build object-oriented processors for the parse-trees that the grammar produces. Note too that the last two rules produce special objects with the single attribute \&'_\|_VALUE_\|_'. This is because they consist solely of a single terminal. .PP This autoaction-ed grammar would then produce a parse tree in a data structure like this: .PP .Vb 10 \& { \& file => { \& command => { \& [ get => { \& identifier => { _\|_VALUE_\|_ => \*(Aqa\*(Aq }, \& }, \& set => { \& identifier => { _\|_VALUE_\|_ => \*(Aqb\*(Aq }, \& value => { _\|_VALUE_\|_ => \*(Aq7\*(Aq }, \& }, \& vet => { \& identifier => { _\|_VALUE_\|_ => \*(Aqb\*(Aq }, \& value => { _\|_VALUE_\|_ => \*(Aq7\*(Aq }, \& }, \& ], \& }, \& } \& } .Ve .PP (except, of course, that each nested hash would also be blessed into the appropriate class). .PP You can also specify a base class for the \f(CW\*(C`<autotree>\*(C'\fR directive. The supplied prefix will be prepended to the rule names when creating tree nodes. The following are equivalent: .PP .Vb 2 \& <autotree:MyBase::Class> \& <autotree:MyBase::Class::> .Ve .PP And will produce a root node blessed into the \f(CW\*(C`MyBase::Class::file\*(C'\fR package in the example above. .SS "Autostubbing" .IX Subsection "Autostubbing" Normally, if a subrule appears in some production, but no rule of that name is ever defined in the grammar, the production which refers to the non-existent subrule fails immediately. This typically occurs as a result of misspellings, and is a sufficiently common occurrence that a warning is generated for such situations. .PP However, when prototyping a grammar it is sometimes useful to be able to use subrules before a proper specification of them is really possible. For example, a grammar might include a section like: .PP .Vb 1 \& function_call: identifier \*(Aq(\*(Aq arg(s?) \*(Aq)\*(Aq \& \& identifier: /[a\-z]\ew*/i .Ve .PP where the possible format of an argument is sufficiently complex that it is not worth specifying in full until the general function call syntax has been debugged. In this situation it is convenient to leave the real rule \f(CW\*(C`arg\*(C'\fR undefined and just slip in a placeholder (or \&\*(L"stub\*(R"): .PP .Vb 1 \& arg: \*(Aqarg\*(Aq .Ve .PP so that the function call syntax can be tested with dummy input such as: .PP .Vb 4 \& f0() \& f1(arg) \& f2(arg arg) \& f3(arg arg arg) .Ve .PP et cetera. .PP Early in prototyping, many such \*(L"stubs\*(R" may be required, so \&\f(CW\*(C`Parse::RecDescent\*(C'\fR provides a means of automating their definition. If the variable \f(CW$::RD_AUTOSTUB\fR is defined when a parser is built, a subrule reference to any non-existent rule (say, \f(CW\*(C`subrule\*(C'\fR), will cause a \*(L"stub\*(R" rule to be automatically defined in the generated parser. If \f(CW\*(C`$::RD_AUTOSTUB eq \*(Aq1\*(Aq\*(C'\fR or is false, a stub rule of the form: .PP .Vb 1 \& subrule: \*(Aqsubrule\*(Aq .Ve .PP will be generated. The special-case for a value of \f(CW\*(Aq1\*(Aq\fR is to allow the use of the \fBperl \-s\fR with \fB\-RD_AUTOSTUB\fR without generating \&\f(CW\*(C`subrule: \*(Aq1\*(Aq\*(C'\fR per below. If \f(CW$::RD_AUTOSTUB\fR is true, a stub rule of the form: .PP .Vb 1 \& subrule: $::RD_AUTOSTUB .Ve .PP will be generated. \f(CW$::RD_AUTOSTUB\fR must contain a valid production item, no checking is performed. No lazy evaluation of \&\f(CW$::RD_AUTOSTUB\fR is performed, it is evaluated at the time the Parser is generated. .PP Hence, with \f(CW$::RD_AUTOSTUB\fR defined, it is possible to only partially specify a grammar, and then \*(L"fake\*(R" matches of the unspecified (sub)rules by just typing in their name, or a literal value that was assigned to \f(CW$::RD_AUTOSTUB\fR. .SS "Look-ahead" .IX Subsection "Look-ahead" If a subrule, token, or action is prefixed by \*(L"...\*(R", then it is treated as a \*(L"look-ahead\*(R" request. That means that the current production can (as usual) only succeed if the specified item is matched, but that the matching \&\fIdoes not consume any of the text being parsed\fR. This is very similar to the \&\f(CW\*(C`/(?=...)/\*(C'\fR look-ahead construct in Perl patterns. Thus, the rule: .PP .Vb 1 \& inner_word: word ...word .Ve .PP will match whatever the subrule \*(L"word\*(R" matches, provided that match is followed by some more text which subrule \*(L"word\*(R" would also match (although this second substring is not actually consumed by \*(L"inner_word\*(R") .PP Likewise, a \*(L"...!\*(R" prefix, causes the following item to succeed (without consuming any text) if and only if it would normally fail. Hence, a rule such as: .PP .Vb 1 \& identifier: ...!keyword ...!\*(Aq_\*(Aq /[A\-Za\-z_]\ew*/ .Ve .PP matches a string of characters which satisfies the pattern \&\f(CW\*(C`/[A\-Za\-z_]\ew*/\*(C'\fR, but only if the same sequence of characters would not match either subrule \*(L"keyword\*(R" or the literal token '_'. .PP Sequences of look-ahead prefixes accumulate, multiplying their positive and/or negative senses. Hence: .PP .Vb 1 \& inner_word: word ...!......!word .Ve .PP is exactly equivalent to the original example above (a warning is issued in cases like these, since they often indicate something left out, or misunderstood). .PP Note that actions can also be treated as look-aheads. In such cases, the state of the parser text (in the local variable \f(CW$text\fR) \&\fIafter\fR the look-ahead action is guaranteed to be identical to its state \fIbefore\fR the action, regardless of how it's changed \fIwithin\fR the action (unless you actually undefine \f(CW$text\fR, in which case you get the disaster you deserve :\-). .SS "Directives" .IX Subsection "Directives" Directives are special pre-defined actions which may be used to alter the behaviour of the parser. There are currently twenty-three directives: \&\f(CW\*(C`<commit>\*(C'\fR, \&\f(CW\*(C`<uncommit>\*(C'\fR, \&\f(CW\*(C`<reject>\*(C'\fR, \&\f(CW\*(C`<score>\*(C'\fR, \&\f(CW\*(C`<autoscore>\*(C'\fR, \&\f(CW\*(C`<skip>\*(C'\fR, \&\f(CW\*(C`<resync>\*(C'\fR, \&\f(CW\*(C`<error>\*(C'\fR, \&\f(CW\*(C`<warn>\*(C'\fR, \&\f(CW\*(C`<hint>\*(C'\fR, \&\f(CW\*(C`<trace_build>\*(C'\fR, \&\f(CW\*(C`<trace_parse>\*(C'\fR, \&\f(CW\*(C`<nocheck>\*(C'\fR, \&\f(CW\*(C`<rulevar>\*(C'\fR, \&\f(CW\*(C`<matchrule>\*(C'\fR, \&\f(CW\*(C`<leftop>\*(C'\fR, \&\f(CW\*(C`<rightop>\*(C'\fR, \&\f(CW\*(C`<defer>\*(C'\fR, \&\f(CW\*(C`<nocheck>\*(C'\fR, \&\f(CW\*(C`<perl_quotelike>\*(C'\fR, \&\f(CW\*(C`<perl_codeblock>\*(C'\fR, \&\f(CW\*(C`<perl_variable>\*(C'\fR, and \f(CW\*(C`<token>\*(C'\fR. .IP "Committing and uncommitting" 4 .IX Item "Committing and uncommitting" The \f(CW\*(C`<commit>\*(C'\fR and \f(CW\*(C`<uncommit>\*(C'\fR directives permit the recursive descent of the parse tree to be pruned (or \*(L"cut\*(R") for efficiency. Within a rule, a \f(CW\*(C`<commit>\*(C'\fR directive instructs the rule to ignore subsequent productions if the current production fails. For example: .Sp .Vb 3 \& command: \*(Aqfind\*(Aq <commit> filename \& | \*(Aqopen\*(Aq <commit> filename \& | \*(Aqmove\*(Aq filename filename .Ve .Sp Clearly, if the leading token 'find' is matched in the first production but that production fails for some other reason, then the remaining productions cannot possibly match. The presence of the \&\f(CW\*(C`<commit>\*(C'\fR causes the \*(L"command\*(R" rule to fail immediately if an invalid \*(L"find\*(R" command is found, and likewise if an invalid \*(L"open\*(R" command is encountered. .Sp It is also possible to revoke a previous commitment. For example: .Sp .Vb 5 \& if_statement: \*(Aqif\*(Aq <commit> condition \& \*(Aqthen\*(Aq block <uncommit> \& \*(Aqelse\*(Aq block \& | \*(Aqif\*(Aq <commit> condition \& \*(Aqthen\*(Aq block .Ve .Sp In this case, a failure to find an \*(L"else\*(R" block in the first production shouldn't preclude trying the second production, but a failure to find a \*(L"condition\*(R" certainly should. .Sp As a special case, any production in which the \fIfirst\fR item is an \&\f(CW\*(C`<uncommit>\*(C'\fR immediately revokes a preceding \f(CW\*(C`<commit>\*(C'\fR (even though the production would not otherwise have been tried). For example, in the rule: .Sp .Vb 5 \& request: \*(Aqexplain\*(Aq expression \& | \*(Aqexplain\*(Aq <commit> keyword \& | \*(Aqsave\*(Aq \& | \*(Aqquit\*(Aq \& | <uncommit> term \*(Aq?\*(Aq .Ve .Sp if the text being matched was \*(L"explain?\*(R", and the first two productions failed, then the \f(CW\*(C`<commit>\*(C'\fR in production two would cause productions three and four to be skipped, but the leading \&\f(CW\*(C`<uncommit>\*(C'\fR in the production five would allow that production to attempt a match. .Sp Note in the preceding example, that the \f(CW\*(C`<commit>\*(C'\fR was only placed in production two. If production one had been: .Sp .Vb 1 \& request: \*(Aqexplain\*(Aq <commit> expression .Ve .Sp then production two would be (inappropriately) skipped if a leading \&\*(L"explain...\*(R" was encountered. .Sp Both \f(CW\*(C`<commit>\*(C'\fR and \f(CW\*(C`<uncommit>\*(C'\fR directives always succeed, and their value is always 1. .IP "Rejecting a production" 4 .IX Item "Rejecting a production" The \f(CW\*(C`<reject>\*(C'\fR directive immediately causes the current production to fail (it is exactly equivalent to, but more obvious than, the action \f(CW\*(C`{undef}\*(C'\fR). A \f(CW\*(C`<reject>\*(C'\fR is useful when it is desirable to get the side effects of the actions in one production, without prejudicing a match by some other production later in the rule. For example, to insert tracing code into the parse: .Sp .Vb 1 \& complex_rule: { print "In complex rule...\en"; } <reject> \& \& complex_rule: simple_rule \*(Aq+\*(Aq \*(Aqi\*(Aq \*(Aq*\*(Aq simple_rule \& | \*(Aqi\*(Aq \*(Aq*\*(Aq simple_rule \& | simple_rule .Ve .Sp It is also possible to specify a conditional rejection, using the form \f(CW\*(C`<reject:\f(CIcondition\f(CW>\*(C'\fR, which only rejects if the specified condition is true. This form of rejection is exactly equivalent to the action \f(CW\*(C`{(\f(CIcondition\f(CW)?undef:1}>\*(C'\fR. For example: .Sp .Vb 4 \& command: save_command \& | restore_command \& | <reject: defined $::tolerant> { exit } \& | <error: Unknown command. Ignored.> .Ve .Sp A \f(CW\*(C`<reject>\*(C'\fR directive never succeeds (and hence has no associated value). A conditional rejection may succeed (if its condition is not satisfied), in which case its value is 1. .Sp As an extra optimization, \f(CW\*(C`Parse::RecDescent\*(C'\fR ignores any production which \fIbegins\fR with an unconditional \f(CW\*(C`<reject>\*(C'\fR directive, since any such production can never successfully match or have any useful side-effects. A level 1 warning is issued in all such cases. .Sp Note that productions beginning with conditional \&\f(CW\*(C`<reject:...>\*(C'\fR directives are \fInever\fR \*(L"optimized away\*(R" in this manner, even if they are always guaranteed to fail (for example: \&\f(CW\*(C`<reject:1>\*(C'\fR) .Sp Due to the way grammars are parsed, there is a minor restriction on the condition of a conditional \f(CW\*(C`<reject:...>\*(C'\fR: it cannot contain any raw '<' or '>' characters. For example: .Sp .Vb 1 \& line: cmd <reject: $thiscolumn > max> data .Ve .Sp results in an error when a parser is built from this grammar (since the grammar parser has no way of knowing whether the first > is a \*(L"less than\*(R" or the end of the \f(CW\*(C`<reject:...>\*(C'\fR. .Sp To overcome this problem, put the condition inside a do{} block: .Sp .Vb 1 \& line: cmd <reject: do{$thiscolumn > max}> data .Ve .Sp Note that the same problem may occur in other directives that take arguments. The same solution will work in all cases. .IP "Skipping between terminals" 4 .IX Item "Skipping between terminals" The \f(CW\*(C`<skip>\*(C'\fR directive enables the terminal prefix used in a production to be changed. For example: .Sp .Vb 1 \& OneLiner: Command <skip:\*(Aq[ \et]*\*(Aq> Arg(s) /;/ .Ve .Sp causes only blanks and tabs to be skipped before terminals in the \&\f(CW\*(C`Arg\*(C'\fR subrule (and any of \fIits\fR subrules>, and also before the final \&\f(CW\*(C`/;/\*(C'\fR terminal. Once the production is complete, the previous terminal prefix is reinstated. Note that this implies that distinct productions of a rule must reset their terminal prefixes individually. .Sp The \f(CW\*(C`<skip>\*(C'\fR directive evaluates to the \fIprevious\fR terminal prefix, so it's easy to reinstate a prefix later in a production: .Sp .Vb 1 \& Command: <skip:","> CSV(s) <skip:$item[1]> Modifier .Ve .Sp The value specified after the colon is interpolated into a pattern, so all of the following are equivalent (though their efficiency increases down the list): .Sp .Vb 1 \& <skip: "$colon|$comma"> # ASSUMING THE VARS HOLD THE OBVIOUS VALUES \& \& <skip: \*(Aq:|,\*(Aq> \& \& <skip: q{[:,]}> \& \& <skip: qr/[:,]/> .Ve .Sp There is no way of directly setting the prefix for an entire rule, except as follows: .Sp .Vb 3 \& Rule: <skip: \*(Aq[ \et]*\*(Aq> Prod1 \& | <skip: \*(Aq[ \et]*\*(Aq> Prod2a Prod2b \& | <skip: \*(Aq[ \et]*\*(Aq> Prod3 .Ve .Sp or, better: .Sp .Vb 6 \& Rule: <skip: \*(Aq[ \et]*\*(Aq> \& ( \& Prod1 \& | Prod2a Prod2b \& | Prod3 \& ) .Ve .Sp The skip pattern is passed down to subrules, so setting the skip for the top-level rule as described above actually sets the prefix for the entire grammar (provided that you only call the method corresponding to the top-level rule itself). Alternatively, or if you have more than one top-level rule in your grammar, you can provide a global \&\f(CW\*(C`<skip>\*(C'\fR directive prior to defining any rules in the grammar. These are the preferred alternatives to setting \&\f(CW$Parse::RecDescent::skip\fR. .Sp Additionally, using \f(CW\*(C`<skip>\*(C'\fR actually allows you to have a completely dynamic skipping behaviour. For example: .Sp .Vb 1 \& Rule_with_dynamic_skip: <skip: $::skip_pattern> Rule .Ve .Sp Then you can set \f(CW$::skip_pattern\fR before invoking \&\f(CW\*(C`Rule_with_dynamic_skip\*(C'\fR and have it skip whatever you specified. .Sp \&\fBNote: Up to release 1.51 of Parse::RecDescent, an entirely different mechanism was used for specifying terminal prefixes. The current method is not backwards-compatible with that early approach. The current approach is stable and will not change again.\fR .Sp \&\fBNote: the global \f(CB\*(C`<skip>\*(C'\fB directive added in 1.967_004 did not interpolate the pattern argument, instead the pattern was placed inside of single quotes and then interpolated. This behavior was changed in 1.967_010 so that all \f(CB\*(C`<skip>\*(C'\fB directives behavior similarly.\fR .IP "Resynchronization" 4 .IX Item "Resynchronization" The \f(CW\*(C`<resync>\*(C'\fR directive provides a visually distinctive means of consuming some of the text being parsed, usually to skip an erroneous input. In its simplest form \f(CW\*(C`<resync>\*(C'\fR simply consumes text up to and including the next newline (\f(CW"\en"\fR) character, succeeding only if the newline is found, in which case it causes its surrounding rule to return zero on success. .Sp In other words, a \f(CW\*(C`<resync>\*(C'\fR is exactly equivalent to the token \&\f(CW\*(C`/[^\en]*\en/\*(C'\fR followed by the action \f(CW\*(C`{\ $return\ =\ 0\ }\*(C'\fR (except that productions beginning with a \f(CW\*(C`<resync>\*(C'\fR are ignored when generating error messages). A typical use might be: .Sp .Vb 1 \& script : command(s) \& \& command: save_command \& | restore_command \& | <resync> # TRY NEXT LINE, IF POSSIBLE .Ve .Sp It is also possible to explicitly specify a resynchronization pattern, using the \f(CW\*(C`<resync:\f(CIpattern\f(CW>\*(C'\fR variant. This version succeeds only if the specified pattern matches (and consumes) the parsed text. In other words, \f(CW\*(C`<resync:\f(CIpattern\f(CW>\*(C'\fR is exactly equivalent to the token \f(CW\*(C`/\f(CIpattern\f(CW/\*(C'\fR (followed by a \f(CW\*(C`{\ $return\ =\ 0\ }\*(C'\fR action). For example, if commands were terminated by newlines or semi-colons: .Sp .Vb 3 \& command: save_command \& | restore_command \& | <resync:[^;\en]*[;\en]> .Ve .Sp The value of a successfully matched \f(CW\*(C`<resync>\*(C'\fR directive (of either type) is the text that it consumed. Note, however, that since the directive also sets \f(CW$return\fR, a production consisting of a lone \&\f(CW\*(C`<resync>\*(C'\fR succeeds but returns the value zero (which a calling rule may find useful to distinguish between \*(L"true\*(R" matches and \*(L"tolerant\*(R" matches). Remember that returning a zero value indicates that the rule \fIsucceeded\fR (since only an \f(CW\*(C`undef\*(C'\fR denotes failure within \f(CW\*(C`Parse::RecDescent\*(C'\fR parsers. .IP "Error handling" 4 .IX Item "Error handling" The \f(CW\*(C`<error>\*(C'\fR directive provides automatic or user-defined generation of error messages during a parse. In its simplest form \&\f(CW\*(C`<error>\*(C'\fR prepares an error message based on the mismatch between the last item expected and the text which cause it to fail. For example, given the rule: .Sp .Vb 3 \& McCoy: curse \*(Aq,\*(Aq name \*(Aq, I\*(Aqm a doctor, not a\*(Aq a_profession \*(Aq!\*(Aq \& | pronoun \*(Aqdead,\*(Aq name \*(Aq!\*(Aq \& | <error> .Ve .Sp the following strings would produce the following messages: .RS 4 .ie n .IP """Amen, Jim!""" 4 .el .IP "``Amen, Jim!''" 4 .IX Item "Amen, Jim!" .Vb 2 \& ERROR (line 1): Invalid McCoy: Expected curse or pronoun \& not found .Ve .ie n .IP """Dammit, Jim, I'm a doctor!""" 4 .el .IP "``Dammit, Jim, I'm a doctor!''" 4 .IX Item "Dammit, Jim, I'm a doctor!" .Vb 2 \& ERROR (line 1): Invalid McCoy: Expected ", I\*(Aqm a doctor, not a" \& but found ", I\*(Aqm a doctor!" instead .Ve .ie n .IP """He's dead,\en""" 4 .el .IP "``He's dead,\en''" 4 .IX Item "He's dead,n" .Vb 1 \& ERROR (line 2): Invalid McCoy: Expected name not found .Ve .ie n .IP """He's alive!""" 4 .el .IP "``He's alive!''" 4 .IX Item "He's alive!" .Vb 2 \& ERROR (line 1): Invalid McCoy: Expected \*(Aqdead,\*(Aq but found \& "alive!" instead .Ve .ie n .IP """Dammit, Jim, I'm a doctor, not a pointy-eared Vulcan!""" 4 .el .IP "``Dammit, Jim, I'm a doctor, not a pointy-eared Vulcan!''" 4 .IX Item "Dammit, Jim, I'm a doctor, not a pointy-eared Vulcan!" .Vb 2 \& ERROR (line 1): Invalid McCoy: Expected a profession but found \& "pointy\-eared Vulcan!" instead .Ve .RE .RS 4 .Sp Note that, when autogenerating error messages, all underscores in any rule name used in a message are replaced by single spaces (for example \&\*(L"a_production\*(R" becomes \*(L"a production\*(R"). Judicious choice of rule names can therefore considerably improve the readability of automatic error messages (as well as the maintainability of the original grammar). .Sp If the automatically generated error is not sufficient, it is possible to provide an explicit message as part of the error directive. For example: .Sp .Vb 3 \& Spock: "Fascinating \*(Aq,\*(Aq (name | \*(AqCaptain\*(Aq) \*(Aq.\*(Aq \& | "Highly illogical, doctor." \& | <error: He never said that!> .Ve .Sp which would result in \fIall\fR failures to parse a \*(L"Spock\*(R" subrule printing the following message: .Sp .Vb 1 \& ERROR (line <N>): Invalid Spock: He never said that! .Ve .Sp The error message is treated as a \*(L"qq{...}\*(R" string and interpolated when the error is generated (\fInot\fR when the directive is specified!). Hence: .Sp .Vb 1 \& <error: Mystical error near "$text"> .Ve .Sp would correctly insert the ambient text string which caused the error. .Sp There are two other forms of error directive: \f(CW\*(C`<error?>\*(C'\fR and \&\f(CW\*(C`<error?:\ msg>\*(C'\fR. These behave just like \f(CW\*(C`<error>\*(C'\fR and \f(CW\*(C`<error:\ msg>\*(C'\fR respectively, except that they are only triggered if the rule is \*(L"committed\*(R" at the time they are encountered. For example: .Sp .Vb 3 \& Scotty: "Ya kenna change the Laws of Phusics," <commit> name \& | name <commit> \*(Aq,\*(Aq \*(Aqshe\*(Aqs goanta blaw!\*(Aq \& | <error?> .Ve .Sp will only generate an error for a string beginning with \*(L"Ya kenna change the Laws o' Phusics,\*(R" or a valid name, but which still fails to match the corresponding production. That is, \f(CW\*(C`$parser\->Scotty("Aye, Cap\*(Aqain")\*(C'\fR will fail silently (since neither production will \*(L"commit\*(R" the rule on that input), whereas \f(CW\*(C`$parser\->Scotty("Mr\ Spock,\ ah\ jest\ kenna\ do\*(Aqut!")\*(C'\fR will fail with the error message: .Sp .Vb 2 \& ERROR (line 1): Invalid Scotty: expected \*(Aqshe\*(Aqs goanta blaw!\*(Aq \& but found \*(AqI jest kenna do\*(Aqut!\*(Aq instead. .Ve .Sp since in that case the second production would commit after matching the leading name. .Sp Note that to allow this behaviour, all \f(CW\*(C`<error>\*(C'\fR directives which are the first item in a production automatically uncommit the rule just long enough to allow their production to be attempted (that is, when their production fails, the commitment is reinstated so that subsequent productions are skipped). .Sp In order to \fIpermanently\fR uncommit the rule before an error message, it is necessary to put an explicit \f(CW\*(C`<uncommit>\*(C'\fR before the \&\f(CW\*(C`<error>\*(C'\fR. For example: .Sp .Vb 5 \& line: \*(AqKirk:\*(Aq <commit> Kirk \& | \*(AqSpock:\*(Aq <commit> Spock \& | \*(AqMcCoy:\*(Aq <commit> McCoy \& | <uncommit> <error?> <reject> \& | <resync> .Ve .Sp Error messages generated by the various \f(CW\*(C`<error...>\*(C'\fR directives are not displayed immediately. Instead, they are \*(L"queued\*(R" in a buffer and are only displayed once parsing ultimately fails. Moreover, \&\f(CW\*(C`<error...>\*(C'\fR directives that cause one production of a rule to fail are automatically removed from the message queue if another production subsequently causes the entire rule to succeed. This means that you can put \&\f(CW\*(C`<error...>\*(C'\fR directives wherever useful diagnosis can be done, and only those associated with actual parser failure will ever be displayed. Also see \*(L"\s-1GOTCHAS\*(R"\s0. .Sp As a general rule, the most useful diagnostics are usually generated either at the very lowest level within the grammar, or at the very highest. A good rule of thumb is to identify those subrules which consist mainly (or entirely) of terminals, and then put an \&\f(CW\*(C`<error...>\*(C'\fR directive at the end of any other rule which calls one or more of those subrules. .Sp There is one other situation in which the output of the various types of error directive is suppressed; namely, when the rule containing them is being parsed as part of a \*(L"look-ahead\*(R" (see \*(L"Look-ahead\*(R"). In this case, the error directive will still cause the rule to fail, but will do so silently. .Sp An unconditional \f(CW\*(C`<error>\*(C'\fR directive always fails (and hence has no associated value). This means that encountering such a directive always causes the production containing it to fail. Hence an \&\f(CW\*(C`<error>\*(C'\fR directive will inevitably be the last (useful) item of a rule (a level 3 warning is issued if a production contains items after an unconditional \&\f(CW\*(C`<error>\*(C'\fR directive). .Sp An \f(CW\*(C`<error?>\*(C'\fR directive will \fIsucceed\fR (that is: fail to fail :\-), if the current rule is uncommitted when the directive is encountered. In that case the directive's associated value is zero. Hence, this type of error directive \fIcan\fR be used before the end of a production. For example: .Sp .Vb 3 \& command: \*(Aqdo\*(Aq <commit> something \& | \*(Aqreport\*(Aq <commit> something \& | <error?: Syntax error> <error: Unknown command> .Ve .Sp \&\fBWarning:\fR The \f(CW\*(C`<error?>\*(C'\fR directive does \fInot\fR mean \*(L"always fail (but do so silently unless committed)\*(R". It actually means "only fail (and report) if committed, otherwise \fIsucceed\fR\*(L". To achieve the \*(R"fail silently if uncommitted" semantics, it is necessary to use: .Sp .Vb 2 \& rule: item <commit> item(s) \& | <error?> <reject> # FAIL SILENTLY UNLESS COMMITTED .Ve .Sp However, because people seem to expect a lone \f(CW\*(C`<error?>\*(C'\fR directive to work like this: .Sp .Vb 3 \& rule: item <commit> item(s) \& | <error?: Error message if committed> \& | <error: Error message if uncommitted> .Ve .Sp Parse::RecDescent automatically appends a \&\f(CW\*(C`<reject>\*(C'\fR directive if the \f(CW\*(C`<error?>\*(C'\fR directive is the only item in a production. A level 2 warning (see below) is issued when this happens. .Sp The level of error reporting during both parser construction and parsing is controlled by the presence or absence of four global variables: \f(CW$::RD_ERRORS\fR, \f(CW$::RD_WARN\fR, \f(CW$::RD_HINT\fR, and <$::RD_TRACE>. If \f(CW$::RD_ERRORS\fR is defined (and, by default, it is) then fatal errors are reported. .Sp Whenever \f(CW$::RD_WARN\fR is defined, certain non-fatal problems are also reported. .Sp Warnings have an associated \*(L"level\*(R": 1, 2, or 3. The higher the level, the more serious the warning. The value of the corresponding global variable (\f(CW$::RD_WARN\fR) determines the \fIlowest\fR level of warning to be displayed. Hence, to see \fIall\fR warnings, set \f(CW$::RD_WARN\fR to 1. To see only the most serious warnings set \f(CW$::RD_WARN\fR to 3. By default \f(CW$::RD_WARN\fR is initialized to 3, ensuring that serious but non-fatal errors are automatically reported. .Sp There is also a grammar directive to turn on warnings from within the grammar: \f(CW\*(C`<warn>\*(C'\fR. It takes an optional argument, which specifies the warning level: \f(CW\*(C`<warn: 2>\*(C'\fR. .Sp See \fI\*(L"\s-1DIAGNOSTICS\*(R"\s0\fR for a list of the various error and warning messages that Parse::RecDescent generates when these two variables are defined. .Sp Defining any of the remaining variables (which are not defined by default) further increases the amount of information reported. Defining \f(CW$::RD_HINT\fR causes the parser generator to offer more detailed analyses and hints on both errors and warnings. Note that setting \f(CW$::RD_HINT\fR at any point automagically sets \f(CW$::RD_WARN\fR to 1. There is also a \f(CW\*(C`<hint>\*(C'\fR directive, which can be hard-coded into a grammar. .Sp Defining \f(CW$::RD_TRACE\fR causes the parser generator and the parser to report their progress to \s-1STDERR\s0 in excruciating detail (although, without hints unless \f(CW$::RD_HINT\fR is separately defined). This detail can be moderated in only one respect: if \f(CW$::RD_TRACE\fR has an integer value (\fIN\fR) greater than 1, only the \fIN\fR characters of the \*(L"current parsing context\*(R" (that is, where in the input string we are at any point in the parse) is reported at any time. .Sp \&\f(CW$::RD_TRACE\fR is mainly useful for debugging a grammar that isn't behaving as you expected it to. To this end, if \f(CW$::RD_TRACE\fR is defined when a parser is built, any actual parser code which is generated is also written to a file named \*(L"\s-1RD_TRACE\*(R"\s0 in the local directory. .Sp There are two directives associated with the \f(CW$::RD_TRACE\fR variable. If a grammar contains a \f(CW\*(C`<trace_build>\*(C'\fR directive anywhere in its specification, \f(CW$::RD_TRACE\fR is turned on during the parser construction phase. If a grammar contains a \f(CW\*(C`<trace_parse>\*(C'\fR directive anywhere in its specification, \f(CW$::RD_TRACE\fR is turned on during any parse the parser performs. .Sp Note that the four variables belong to the \*(L"main\*(R" package, which makes them easier to refer to in the code controlling the parser, and also makes it easy to turn them into command line flags (\*(L"\-RD_ERRORS\*(R", \&\*(L"\-RD_WARN\*(R", \*(L"\-RD_HINT\*(R", \*(L"\-RD_TRACE\*(R") under \fBperl \-s\fR. .Sp The corresponding directives are useful to \*(L"hardwire\*(R" the various debugging features into a particular grammar (rather than having to set and reset external variables). .RE .IP "Redirecting diagnostics" 4 .IX Item "Redirecting diagnostics" The diagnostics provided by the tracing mechanism always go to \s-1STDERR.\s0 If you need them to go elsewhere, localize and reopen \s-1STDERR\s0 prior to the parse. .Sp For example: .Sp .Vb 2 \& { \& local *STDERR = IO::File\->new(">$filename") or die $!; \& \& my $result = $parser\->startrule($text); \& } .Ve .IP "Consistency checks" 4 .IX Item "Consistency checks" Whenever a parser is build, Parse::RecDescent carries out a number of (potentially expensive) consistency checks. These include: verifying that the grammar is not left-recursive and that no rules have been left undefined. .Sp These checks are important safeguards during development, but unnecessary overheads when the grammar is stable and ready to be deployed. So Parse::RecDescent provides a directive to disable them: \f(CW\*(C`<nocheck>\*(C'\fR. .Sp If a grammar contains a \f(CW\*(C`<nocheck>\*(C'\fR directive anywhere in its specification, the extra compile-time checks are by-passed. .IP "Specifying local variables" 4 .IX Item "Specifying local variables" It is occasionally convenient to specify variables which are local to a single rule. This may be achieved by including a \&\f(CW\*(C`<rulevar:...>\*(C'\fR directive anywhere in the rule. For example: .Sp .Vb 1 \& markup: <rulevar: $tag> \& \& markup: tag {($tag=$item[1]) =~ s/^<|>$//g} body[$tag] .Ve .Sp The example \f(CW\*(C`<rulevar: $tag>\*(C'\fR directive causes a \*(L"my\*(R" variable named \&\f(CW$tag\fR to be declared at the start of the subroutine implementing the \&\f(CW\*(C`markup\*(C'\fR rule (that is, \fIbefore\fR the first production, regardless of where in the rule it is specified). .Sp Specifically, any directive of the form: \&\f(CW\*(C`<rulevar:\f(CItext\f(CW>\*(C'\fR causes a line of the form \f(CW\*(C`my \f(CItext\f(CW;\*(C'\fR to be added at the beginning of the rule subroutine, immediately after the definitions of the following local variables: .Sp .Vb 4 \& $thisparser $commit \& $thisrule @item \& $thisline @arg \& $text %arg .Ve .Sp This means that the following \f(CW\*(C`<rulevar>\*(C'\fR directives work as expected: .Sp .Vb 1 \& <rulevar: $count = 0 > \& \& <rulevar: $firstarg = $arg[0] || \*(Aq\*(Aq > \& \& <rulevar: $myItems = \e@item > \& \& <rulevar: @context = ( $thisline, $text, @arg ) > \& \& <rulevar: ($name,$age) = $arg{"name","age"} > .Ve .Sp If a variable that is also visible to subrules is required, it needs to be \f(CW\*(C`local\*(C'\fR'd, not \f(CW\*(C`my\*(C'\fR'd. \f(CW\*(C`rulevar\*(C'\fR defaults to \f(CW\*(C`my\*(C'\fR, but if \f(CW\*(C`local\*(C'\fR is explicitly specified: .Sp .Vb 1 \& <rulevar: local $count = 0 > .Ve .Sp then a \f(CW\*(C`local\*(C'\fR\-ized variable is declared instead, and will be available within subrules. .Sp Note however that, because all such variables are \*(L"my\*(R" variables, their values \fIdo not persist\fR between match attempts on a given rule. To preserve values between match attempts, values can be stored within the \&\*(L"local\*(R" member of the \f(CW$thisrule\fR object: .Sp .Vb 6 \& countedrule: { $thisrule\->{"local"}{"count"}++ } \& <reject> \& | subrule1 \& | subrule2 \& | <reject: $thisrule\->{"local"}{"count"} == 1> \& subrule3 .Ve .Sp When matching a rule, each \f(CW\*(C`<rulevar>\*(C'\fR directive is matched as if it were an unconditional \f(CW\*(C`<reject>\*(C'\fR directive (that is, it causes any production in which it appears to immediately fail to match). For this reason (and to improve readability) it is usual to specify any \&\f(CW\*(C`<rulevar>\*(C'\fR directive in a separate production at the start of the rule (this has the added advantage that it enables \&\f(CW\*(C`Parse::RecDescent\*(C'\fR to optimize away such productions, just as it does for the \f(CW\*(C`<reject>\*(C'\fR directive). .IP "Dynamically matched rules" 4 .IX Item "Dynamically matched rules" Because regexes and double-quoted strings are interpolated, it is relatively easy to specify productions with \*(L"context sensitive\*(R" tokens. For example: .Sp .Vb 1 \& command: keyword body "end $item[1]" .Ve .Sp which ensures that a command block is bounded by a "\fI<keyword>\fR...end \fI<same keyword>\fR" pair. .Sp Building productions in which subrules are context sensitive is also possible, via the \f(CW\*(C`<matchrule:...>\*(C'\fR directive. This directive behaves identically to a subrule item, except that the rule which is invoked to match it is determined by the string specified after the colon. For example, we could rewrite the \f(CW\*(C`command\*(C'\fR rule like this: .Sp .Vb 1 \& command: keyword <matchrule:body> "end $item[1]" .Ve .Sp Whatever appears after the colon in the directive is treated as an interpolated string (that is, as if it appeared in \f(CW\*(C`qq{...}\*(C'\fR operator) and the value of that interpolated string is the name of the subrule to be matched. .Sp Of course, just putting a constant string like \f(CW\*(C`body\*(C'\fR in a \&\f(CW\*(C`<matchrule:...>\*(C'\fR directive is of little interest or benefit. The power of directive is seen when we use a string that interpolates to something interesting. For example: .Sp .Vb 1 \& command: keyword <matchrule:$item[1]_body> "end $item[1]" \& \& keyword: \*(Aqwhile\*(Aq | \*(Aqif\*(Aq | \*(Aqfunction\*(Aq \& \& while_body: condition block \& \& if_body: condition block (\*(Aqelse\*(Aq block)(?) \& \& function_body: arglist block .Ve .Sp Now the \f(CW\*(C`command\*(C'\fR rule selects how to proceed on the basis of the keyword that is found. It is as if \f(CW\*(C`command\*(C'\fR were declared: .Sp .Vb 3 \& command: \*(Aqwhile\*(Aq while_body "end while" \& | \*(Aqif\*(Aq if_body "end if" \& | \*(Aqfunction\*(Aq function_body "end function" .Ve .Sp When a \f(CW\*(C`<matchrule:...>\*(C'\fR directive is used as a repeated subrule, the rule name expression is \*(L"late-bound\*(R". That is, the name of the rule to be called is re-evaluated \fIeach time\fR a match attempt is made. Hence, the following grammar: .Sp .Vb 1 \& { $::species = \*(Aqdogs\*(Aq } \& \& pair: \*(Aqtwo\*(Aq <matchrule:$::species>(s) \& \& dogs: /dogs/ { $::species = \*(Aqcats\*(Aq } \& \& cats: /cats/ .Ve .Sp will match the string \*(L"two dogs cats cats\*(R" completely, whereas it will only match the string \*(L"two dogs dogs dogs\*(R" up to the eighth letter. If the rule name were \*(L"early bound\*(R" (that is, evaluated only the first time the directive is encountered in a production), the reverse behaviour would be expected. .Sp Note that the \f(CW\*(C`matchrule\*(C'\fR directive takes a string that is to be treated as a rule name, \fInot\fR as a rule invocation. That is, it's like a Perl symbolic reference, not an \f(CW\*(C`eval\*(C'\fR. Just as you can say: .Sp .Vb 1 \& $subname = \*(Aqfoo\*(Aq; \& \& # and later... \& \& &{$foo}(@args); .Ve .Sp but not: .Sp .Vb 1 \& $subname = \*(Aqfoo(@args)\*(Aq; \& \& # and later... \& \& &{$foo}; .Ve .Sp likewise you can say: .Sp .Vb 1 \& $rulename = \*(Aqfoo\*(Aq; \& \& # and in the grammar... \& \& <matchrule:$rulename>[@args] .Ve .Sp but not: .Sp .Vb 1 \& $rulename = \*(Aqfoo[@args]\*(Aq; \& \& # and in the grammar... \& \& <matchrule:$rulename> .Ve .IP "Deferred actions" 4 .IX Item "Deferred actions" The \f(CW\*(C`<defer:...>\*(C'\fR directive is used to specify an action to be performed when (and only if!) the current production ultimately succeeds. .Sp Whenever a \f(CW\*(C`<defer:...>\*(C'\fR directive appears, the code it specifies is converted to a closure (an anonymous subroutine reference) which is queued within the active parser object. Note that, because the deferred code is converted to a closure, the values of any \&\*(L"local\*(R" variable (such as \f(CW$text\fR, <@item>, etc.) are preserved until the deferred code is actually executed. .Sp If the parse ultimately succeeds \&\fIand\fR the production in which the \f(CW\*(C`<defer:...>\*(C'\fR directive was evaluated formed part of the successful parse, then the deferred code is executed immediately before the parse returns. If however the production which queued a deferred action fails, or one of the higher-level rules which called that production fails, then the deferred action is removed from the queue, and hence is never executed. .Sp For example, given the grammar: .Sp .Vb 2 \& sentence: noun trans noun \& | noun intrans \& \& noun: \*(Aqthe dog\*(Aq \& { print "$item[1]\et(noun)\en" } \& | \*(Aqthe meat\*(Aq \& { print "$item[1]\et(noun)\en" } \& \& trans: \*(Aqate\*(Aq \& { print "$item[1]\et(transitive)\en" } \& \& intrans: \*(Aqate\*(Aq \& { print "$item[1]\et(intransitive)\en" } \& | \*(Aqbarked\*(Aq \& { print "$item[1]\et(intransitive)\en" } .Ve .Sp then parsing the sentence \f(CW"the dog ate"\fR would produce the output: .Sp .Vb 4 \& the dog (noun) \& ate (transitive) \& the dog (noun) \& ate (intransitive) .Ve .Sp This is because, even though the first production of \f(CW\*(C`sentence\*(C'\fR ultimately fails, its initial subrules \f(CW\*(C`noun\*(C'\fR and \f(CW\*(C`trans\*(C'\fR do match, and hence they execute their associated actions. Then the second production of \f(CW\*(C`sentence\*(C'\fR succeeds, causing the actions of the subrules \f(CW\*(C`noun\*(C'\fR and \f(CW\*(C`intrans\*(C'\fR to be executed as well. .Sp On the other hand, if the actions were replaced by \f(CW\*(C`<defer:...>\*(C'\fR directives: .Sp .Vb 2 \& sentence: noun trans noun \& | noun intrans \& \& noun: \*(Aqthe dog\*(Aq \& <defer: print "$item[1]\et(noun)\en" > \& | \*(Aqthe meat\*(Aq \& <defer: print "$item[1]\et(noun)\en" > \& \& trans: \*(Aqate\*(Aq \& <defer: print "$item[1]\et(transitive)\en" > \& \& intrans: \*(Aqate\*(Aq \& <defer: print "$item[1]\et(intransitive)\en" > \& | \*(Aqbarked\*(Aq \& <defer: print "$item[1]\et(intransitive)\en" > .Ve .Sp the output would be: .Sp .Vb 2 \& the dog (noun) \& ate (intransitive) .Ve .Sp since deferred actions are only executed if they were evaluated in a production which ultimately contributes to the successful parse. .Sp In this case, even though the first production of \f(CW\*(C`sentence\*(C'\fR caused the subrules \f(CW\*(C`noun\*(C'\fR and \f(CW\*(C`trans\*(C'\fR to match, that production ultimately failed and so the deferred actions queued by those subrules were subsequently discarded. The second production then succeeded, causing the entire parse to succeed, and so the deferred actions queued by the (second) match of the \f(CW\*(C`noun\*(C'\fR subrule and the subsequent match of \f(CW\*(C`intrans\*(C'\fR \fIare\fR preserved and eventually executed. .Sp Deferred actions provide a means of improving the performance of a parser, by only executing those actions which are part of the final parse-tree for the input data. .Sp Alternatively, deferred actions can be viewed as a mechanism for building (and executing) a customized subroutine corresponding to the given input data, much in the same way that autoactions (see \*(L"Autoactions\*(R") can be used to build a customized data structure for specific input. .Sp Whether or not the action it specifies is ever executed, a \f(CW\*(C`<defer:...>\*(C'\fR directive always succeeds, returning the number of deferred actions currently queued at that point. .IP "Parsing Perl" 4 .IX Item "Parsing Perl" Parse::RecDescent provides limited support for parsing subsets of Perl, namely: quote-like operators, Perl variables, and complete code blocks. .Sp The \f(CW\*(C`<perl_quotelike>\*(C'\fR directive can be used to parse any Perl quote-like operator: \f(CW\*(Aqa string\*(Aq\fR, \f(CW\*(C`m/a pattern/\*(C'\fR, \f(CW\*(C`tr{ans}{lation}\*(C'\fR, etc. It does this by calling \fIText::Balanced::quotelike()\fR. .Sp If a quote-like operator is found, a reference to an array of eight elements is returned. Those elements are identical to the last eight elements returned by \fIText::Balanced::extract_quotelike()\fR in an array context, namely: .RS 4 .IP "[0]" 4 .IX Item "[0]" the name of the quotelike operator \*(-- 'q', 'qq', 'm', 's', 'tr' \*(-- if the operator was named; otherwise \f(CW\*(C`undef\*(C'\fR, .IP "[1]" 4 .IX Item "[1]" the left delimiter of the first block of the operation, .IP "[2]" 4 .IX Item "[2]" the text of the first block of the operation (that is, the contents of a quote, the regex of a match, or substitution or the target list of a translation), .IP "[3]" 4 .IX Item "[3]" the right delimiter of the first block of the operation, .IP "[4]" 4 .IX Item "[4]" the left delimiter of the second block of the operation if there is one (that is, if it is a \f(CW\*(C`s\*(C'\fR, \f(CW\*(C`tr\*(C'\fR, or \f(CW\*(C`y\*(C'\fR); otherwise \f(CW\*(C`undef\*(C'\fR, .IP "[5]" 4 .IX Item "[5]" the text of the second block of the operation if there is one (that is, the replacement of a substitution or the translation list of a translation); otherwise \f(CW\*(C`undef\*(C'\fR, .IP "[6]" 4 .IX Item "[6]" the right delimiter of the second block of the operation (if any); otherwise \f(CW\*(C`undef\*(C'\fR, .IP "[7]" 4 .IX Item "[7]" the trailing modifiers on the operation (if any); otherwise \f(CW\*(C`undef\*(C'\fR. .RE .RS 4 .Sp If a quote-like expression is not found, the directive fails with the usual \&\f(CW\*(C`undef\*(C'\fR value. .Sp The \f(CW\*(C`<perl_variable>\*(C'\fR directive can be used to parse any Perl variable: \f(CW$scalar\fR, \f(CW@array\fR, \f(CW%hash\fR, \f(CW$ref\fR\->{field}[$index], etc. It does this by calling \fIText::Balanced::extract_variable()\fR. .Sp If the directive matches text representing a valid Perl variable specification, it returns that text. Otherwise it fails with the usual \&\f(CW\*(C`undef\*(C'\fR value. .Sp The \f(CW\*(C`<perl_codeblock>\*(C'\fR directive can be used to parse curly-brace-delimited block of Perl code, such as: { \f(CW$a\fR = 1; f() =~ m/pat/; }. It does this by calling \fIText::Balanced::extract_codeblock()\fR. .Sp If the directive matches text representing a valid Perl code block, it returns that text. Otherwise it fails with the usual \f(CW\*(C`undef\*(C'\fR value. .Sp You can also tell it what kind of brackets to use as the outermost delimiters. For example: .Sp .Vb 1 \& arglist: <perl_codeblock ()> .Ve .Sp causes an arglist to match a perl code block whose outermost delimiters are \f(CW\*(C`(...)\*(C'\fR (rather than the default \f(CW\*(C`{...}\*(C'\fR). .RE .IP "Constructing tokens" 4 .IX Item "Constructing tokens" Eventually, Parse::RecDescent will be able to parse tokenized input, as well as ordinary strings. In preparation for this joyous day, the \&\f(CW\*(C`<token:...>\*(C'\fR directive has been provided. This directive creates a token which will be suitable for input to a Parse::RecDescent parser (when it eventually supports tokenized input). .Sp The text of the token is the value of the immediately preceding item in the production. A \&\f(CW\*(C`<token:...>\*(C'\fR directive always succeeds with a return value which is the hash reference that is the new token. It also sets the return value for the production to that hash ref. .Sp The \f(CW\*(C`<token:...>\*(C'\fR directive makes it easy to build a Parse::RecDescent\-compatible lexer in Parse::RecDescent: .Sp .Vb 3 \& my $lexer = new Parse::RecDescent q \& { \& lex: token(s) \& \& token: /a\eb/ <token:INDEF> \& | /the\eb/ <token:DEF> \& | /fly\eb/ <token:NOUN,VERB> \& | /[a\-z]+/i { lc $item[1] } <token:ALPHA> \& | <error: Unknown token> \& \& }; .Ve .Sp which will eventually be able to be used with a regular Parse::RecDescent grammar: .Sp .Vb 3 \& my $parser = new Parse::RecDescent q \& { \& startrule: subrule1 subrule 2 \& \& # ETC... \& }; .Ve .Sp either with a pre-lexing phase: .Sp .Vb 1 \& $parser\->startrule( $lexer\->lex($data) ); .Ve .Sp or with a lex-on-demand approach: .Sp .Vb 1 \& $parser\->startrule( sub{$lexer\->token(\e$data)} ); .Ve .Sp But at present, only the \f(CW\*(C`<token:...>\*(C'\fR directive is actually implemented. The rest is vapourware. .IP "Specifying operations" 4 .IX Item "Specifying operations" One of the commonest requirements when building a parser is to specify binary operators. Unfortunately, in a normal grammar, the rules for such things are awkward: .Sp .Vb 2 \& disjunction: conjunction (\*(Aqor\*(Aq conjunction)(s?) \& { $return = [ $item[1], @{$item[2]} ] } \& \& conjunction: atom (\*(Aqand\*(Aq atom)(s?) \& { $return = [ $item[1], @{$item[2]} ] } .Ve .Sp or inefficient: .Sp .Vb 4 \& disjunction: conjunction \*(Aqor\*(Aq disjunction \& { $return = [ $item[1], @{$item[2]} ] } \& | conjunction \& { $return = [ $item[1] ] } \& \& conjunction: atom \*(Aqand\*(Aq conjunction \& { $return = [ $item[1], @{$item[2]} ] } \& | atom \& { $return = [ $item[1] ] } .Ve .Sp and either way is ugly and hard to get right. .Sp The \f(CW\*(C`<leftop:...>\*(C'\fR and \f(CW\*(C`<rightop:...>\*(C'\fR directives provide an easier way of specifying such operations. Using \f(CW\*(C`<leftop:...>\*(C'\fR the above examples become: .Sp .Vb 2 \& disjunction: <leftop: conjunction \*(Aqor\*(Aq conjunction> \& conjunction: <leftop: atom \*(Aqand\*(Aq atom> .Ve .Sp The \f(CW\*(C`<leftop:...>\*(C'\fR directive specifies a left-associative binary operator. It is specified around three other grammar elements (typically subrules or terminals), which match the left operand, the operator itself, and the right operand respectively. .Sp A \f(CW\*(C`<leftop:...>\*(C'\fR directive such as: .Sp .Vb 1 \& disjunction: <leftop: conjunction \*(Aqor\*(Aq conjunction> .Ve .Sp is converted to the following: .Sp .Vb 2 \& disjunction: ( conjunction (\*(Aqor\*(Aq conjunction)(s?) \& { $return = [ $item[1], @{$item[2]} ] } ) .Ve .Sp In other words, a \f(CW\*(C`<leftop:...>\*(C'\fR directive matches the left operand followed by zero or more repetitions of both the operator and the right operand. It then flattens the matched items into an anonymous array which becomes the (single) value of the entire \f(CW\*(C`<leftop:...>\*(C'\fR directive. .Sp For example, an \f(CW\*(C`<leftop:...>\*(C'\fR directive such as: .Sp .Vb 1 \& output: <leftop: ident \*(Aq<<\*(Aq expr > .Ve .Sp when given a string such as: .Sp .Vb 1 \& cout << var << "str" << 3 .Ve .Sp would match, and \f(CW$item[1]\fR would be set to: .Sp .Vb 1 \& [ \*(Aqcout\*(Aq, \*(Aqvar\*(Aq, \*(Aq"str"\*(Aq, \*(Aq3\*(Aq ] .Ve .Sp In other words: .Sp .Vb 1 \& output: <leftop: ident \*(Aq<<\*(Aq expr > .Ve .Sp is equivalent to a left-associative operator: .Sp .Vb 5 \& output: ident { $return = [$item[1]] } \& | ident \*(Aq<<\*(Aq expr { $return = [@item[1,3]] } \& | ident \*(Aq<<\*(Aq expr \*(Aq<<\*(Aq expr { $return = [@item[1,3,5]] } \& | ident \*(Aq<<\*(Aq expr \*(Aq<<\*(Aq expr \*(Aq<<\*(Aq expr { $return = [@item[1,3,5,7]] } \& # ...etc... .Ve .Sp Similarly, the \f(CW\*(C`<rightop:...>\*(C'\fR directive takes a left operand, an operator, and a right operand: .Sp .Vb 1 \& assign: <rightop: var \*(Aq=\*(Aq expr > .Ve .Sp and converts them to: .Sp .Vb 2 \& assign: ( (var \*(Aq=\*(Aq {$return=$item[1]})(s?) expr \& { $return = [ @{$item[1]}, $item[2] ] } ) .Ve .Sp which is equivalent to a right-associative operator: .Sp .Vb 5 \& assign: expr { $return = [$item[1]] } \& | var \*(Aq=\*(Aq expr { $return = [@item[1,3]] } \& | var \*(Aq=\*(Aq var \*(Aq=\*(Aq expr { $return = [@item[1,3,5]] } \& | var \*(Aq=\*(Aq var \*(Aq=\*(Aq var \*(Aq=\*(Aq expr { $return = [@item[1,3,5,7]] } \& # ...etc... .Ve .Sp Note that for both the \f(CW\*(C`<leftop:...>\*(C'\fR and \f(CW\*(C`<rightop:...>\*(C'\fR directives, the directive does not normally return the operator itself, just a list of the operands involved. This is particularly handy for specifying lists: .Sp .Vb 2 \& list: \*(Aq(\*(Aq <leftop: list_item \*(Aq,\*(Aq list_item> \*(Aq)\*(Aq \& { $return = $item[2] } .Ve .Sp There is, however, a problem: sometimes the operator is itself significant. For example, in a Perl list a comma and a \f(CW\*(C`=>\*(C'\fR are both valid separators, but the \f(CW\*(C`=>\*(C'\fR has additional stringification semantics. Hence it's important to know which was used in each case. .Sp To solve this problem the \&\f(CW\*(C`<leftop:...>\*(C'\fR and \f(CW\*(C`<rightop:...>\*(C'\fR directives \&\fIdo\fR return the operator(s) as well, under two circumstances. The first case is where the operator is specified as a subrule. In that instance, whatever the operator matches is returned (on the assumption that if the operator is important enough to have its own subrule, then it's important enough to return). .Sp The second case is where the operator is specified as a regular expression. In that case, if the first bracketed subpattern of the regular expression matches, that matching value is returned (this is analogous to the behaviour of the Perl \f(CW\*(C`split\*(C'\fR function, except that only the first subpattern is returned). .Sp In other words, given the input: .Sp .Vb 1 \& ( a=>1, b=>2 ) .Ve .Sp the specifications: .Sp .Vb 1 \& list: \*(Aq(\*(Aq <leftop: list_item separator list_item> \*(Aq)\*(Aq \& \& separator: \*(Aq,\*(Aq | \*(Aq=>\*(Aq .Ve .Sp or: .Sp .Vb 1 \& list: \*(Aq(\*(Aq <leftop: list_item /(,|=>)/ list_item> \*(Aq)\*(Aq .Ve .Sp cause the list separators to be interleaved with the operands in the anonymous array in \f(CW$item[2]\fR: .Sp .Vb 1 \& [ \*(Aqa\*(Aq, \*(Aq=>\*(Aq, \*(Aq1\*(Aq, \*(Aq,\*(Aq, \*(Aqb\*(Aq, \*(Aq=>\*(Aq, \*(Aq2\*(Aq ] .Ve .Sp But the following version: .Sp .Vb 1 \& list: \*(Aq(\*(Aq <leftop: list_item /,|=>/ list_item> \*(Aq)\*(Aq .Ve .Sp returns only the operators: .Sp .Vb 1 \& [ \*(Aqa\*(Aq, \*(Aq1\*(Aq, \*(Aqb\*(Aq, \*(Aq2\*(Aq ] .Ve .Sp Of course, none of the above specifications handle the case of an empty list, since the \f(CW\*(C`<leftop:...>\*(C'\fR and \f(CW\*(C`<rightop:...>\*(C'\fR directives require at least a single right or left operand to match. To specify that the operator can match \*(L"trivially\*(R", it's necessary to add a \f(CW\*(C`(s?)\*(C'\fR qualifier to the directive: .Sp .Vb 1 \& list: \*(Aq(\*(Aq <leftop: list_item /(,|=>)/ list_item>(s?) \*(Aq)\*(Aq .Ve .Sp Note that in almost all the above examples, the first and third arguments of the \f(CW\*(C`<leftop:...>\*(C'\fR directive were the same subrule. That is because \&\f(CW\*(C`<leftop:...>\*(C'\fR's are frequently used to specify \*(L"separated\*(R" lists of the same type of item. To make such lists easier to specify, the following syntax: .Sp .Vb 1 \& list: element(s /,/) .Ve .Sp is exactly equivalent to: .Sp .Vb 1 \& list: <leftop: element /,/ element> .Ve .Sp Note that the separator must be specified as a raw pattern (i.e. not a string or subrule). .IP "Scored productions" 4 .IX Item "Scored productions" By default, Parse::RecDescent grammar rules always accept the first production that matches the input. But if two or more productions may potentially match the same input, choosing the first that does so may not be optimal. .Sp For example, if you were parsing the sentence \*(L"time flies like an arrow\*(R", you might use a rule like this: .Sp .Vb 3 \& sentence: verb noun preposition article noun { [@item] } \& | adjective noun verb article noun { [@item] } \& | noun verb preposition article noun { [@item] } .Ve .Sp Each of these productions matches the sentence, but the third one is the most likely interpretation. However, if the sentence had been \&\*(L"fruit flies like a banana\*(R", then the second production is probably the right match. .Sp To cater for such situations, the \f(CW\*(C`<score:...>\*(C'\fR can be used. The directive is equivalent to an unconditional \f(CW\*(C`<reject>\*(C'\fR, except that it allows you to specify a \*(L"score\*(R" for the current production. If that score is numerically greater than the best score of any preceding production, the current production is cached for later consideration. If no later production matches, then the cached production is treated as having matched, and the value of the item immediately before its \f(CW\*(C`<score:...>\*(C'\fR directive is returned as the result. .Sp In other words, by putting a \f(CW\*(C`<score:...>\*(C'\fR directive at the end of each production, you can select which production matches using criteria other than specification order. For example: .Sp .Vb 3 \& sentence: verb noun preposition article noun { [@item] } <score: sensible(@item)> \& | adjective noun verb article noun { [@item] } <score: sensible(@item)> \& | noun verb preposition article noun { [@item] } <score: sensible(@item)> .Ve .Sp Now, when each production reaches its respective \f(CW\*(C`<score:...>\*(C'\fR directive, the subroutine \f(CW\*(C`sensible\*(C'\fR will be called to evaluate the matched items (somehow). Once all productions have been tried, the one which \f(CW\*(C`sensible\*(C'\fR scored most highly will be the one that is accepted as a match for the rule. .Sp The variable \f(CW$score\fR always holds the current best score of any production, and the variable \f(CW$score_return\fR holds the corresponding return value. .Sp As another example, the following grammar matches lines that may be separated by commas, colons, or semi-colons. This can be tricky if a colon-separated line also contains commas, or vice versa. The grammar resolves the ambiguity by selecting the rule that results in the fewest fields: .Sp .Vb 3 \& line: seplist[sep=>\*(Aq,\*(Aq] <score: \-@{$item[1]}> \& | seplist[sep=>\*(Aq:\*(Aq] <score: \-@{$item[1]}> \& | seplist[sep=>" "] <score: \-@{$item[1]}> \& \& seplist: <skip:""> <leftop: /[^$arg{sep}]*/ "$arg{sep}" /[^$arg{sep}]*/> .Ve .Sp Note the use of negation within the \f(CW\*(C`<score:...>\*(C'\fR directive to ensure that the seplist with the most items gets the lowest score. .Sp As the above examples indicate, it is often the case that all productions in a rule use exactly the same \f(CW\*(C`<score:...>\*(C'\fR directive. It is tedious to have to repeat this identical directive in every production, so Parse::RecDescent also provides the \f(CW\*(C`<autoscore:...>\*(C'\fR directive. .Sp If an \f(CW\*(C`<autoscore:...>\*(C'\fR directive appears in any production of a rule, the code it specifies is used as the scoring code for every production of that rule, except productions that already end with an explicit \f(CW\*(C`<score:...>\*(C'\fR directive. Thus the rules above could be rewritten: .Sp .Vb 4 \& line: <autoscore: \-@{$item[1]}> \& line: seplist[sep=>\*(Aq,\*(Aq] \& | seplist[sep=>\*(Aq:\*(Aq] \& | seplist[sep=>" "] \& \& \& sentence: <autoscore: sensible(@item)> \& | verb noun preposition article noun { [@item] } \& | adjective noun verb article noun { [@item] } \& | noun verb preposition article noun { [@item] } .Ve .Sp Note that the \f(CW\*(C`<autoscore:...>\*(C'\fR directive itself acts as an unconditional \f(CW\*(C`<reject>\*(C'\fR, and (like the \f(CW\*(C`<rulevar:...>\*(C'\fR directive) is pruned at compile-time wherever possible. .IP "Dispensing with grammar checks" 4 .IX Item "Dispensing with grammar checks" During the compilation phase of parser construction, Parse::RecDescent performs a small number of checks on the grammar it's given. Specifically it checks that the grammar is not left-recursive, that there are no \*(L"insatiable\*(R" constructs of the form: .Sp .Vb 1 \& rule: subrule(s) subrule .Ve .Sp and that there are no rules missing (i.e. referred to, but never defined). .Sp These checks are important during development, but can slow down parser construction in stable code. So Parse::RecDescent provides the <nocheck> directive to turn them off. The directive can only appear before the first rule definition, and switches off checking throughout the rest of the current grammar. .Sp Typically, this directive would be added when a parser has been thoroughly tested and is ready for release. .SS "Subrule argument lists" .IX Subsection "Subrule argument lists" It is occasionally useful to pass data to a subrule which is being invoked. For example, consider the following grammar fragment: .PP .Vb 1 \& classdecl: keyword decl \& \& keyword: \*(Aqstruct\*(Aq | \*(Aqclass\*(Aq; \& \& decl: # WHATEVER .Ve .PP The \f(CW\*(C`decl\*(C'\fR rule might wish to know which of the two keywords was used (since it may affect some aspect of the way the subsequent declaration is interpreted). \f(CW\*(C`Parse::RecDescent\*(C'\fR allows the grammar designer to pass data into a rule, by placing that data in an \fIargument list\fR (that is, in square brackets) immediately after any subrule item in a production. Hence, we could pass the keyword to \f(CW\*(C`decl\*(C'\fR as follows: .PP .Vb 1 \& classdecl: keyword decl[ $item[1] ] \& \& keyword: \*(Aqstruct\*(Aq | \*(Aqclass\*(Aq; \& \& decl: # WHATEVER .Ve .PP The argument list can consist of any number (including zero!) of comma-separated Perl expressions. In other words, it looks exactly like a Perl anonymous array reference. For example, we could pass the keyword, the name of the surrounding rule, and the literal 'keyword' to \f(CW\*(C`decl\*(C'\fR like so: .PP .Vb 1 \& classdecl: keyword decl[$item[1],$item[0],\*(Aqkeyword\*(Aq] \& \& keyword: \*(Aqstruct\*(Aq | \*(Aqclass\*(Aq; \& \& decl: # WHATEVER .Ve .PP Within the rule to which the data is passed (\f(CW\*(C`decl\*(C'\fR in the above examples) that data is available as the elements of a local variable \f(CW@arg\fR. Hence \&\f(CW\*(C`decl\*(C'\fR might report its intentions as follows: .PP .Vb 1 \& classdecl: keyword decl[$item[1],$item[0],\*(Aqkeyword\*(Aq] \& \& keyword: \*(Aqstruct\*(Aq | \*(Aqclass\*(Aq; \& \& decl: { print "Declaring $arg[0] (a $arg[2])\en"; \& print "(this rule called by $arg[1])" } .Ve .PP Subrule argument lists can also be interpreted as hashes, simply by using the local variable \f(CW%arg\fR instead of \f(CW@arg\fR. Hence we could rewrite the previous example: .PP .Vb 3 \& classdecl: keyword decl[keyword => $item[1], \& caller => $item[0], \& type => \*(Aqkeyword\*(Aq] \& \& keyword: \*(Aqstruct\*(Aq | \*(Aqclass\*(Aq; \& \& decl: { print "Declaring $arg{keyword} (a $arg{type})\en"; \& print "(this rule called by $arg{caller})" } .Ve .PP Both \f(CW@arg\fR and \f(CW%arg\fR are always available, so the grammar designer may choose whichever convention (or combination of conventions) suits best. .PP Subrule argument lists are also useful for creating \*(L"rule templates\*(R" (especially when used in conjunction with the \f(CW\*(C`<matchrule:...>\*(C'\fR directive). For example, the subrule: .PP .Vb 4 \& list: <matchrule:$arg{rule}> /$arg{sep}/ list[%arg] \& { $return = [ $item[1], @{$item[3]} ] } \& | <matchrule:$arg{rule}> \& { $return = [ $item[1]] } .Ve .PP is a handy template for the common problem of matching a separated list. For example: .PP .Vb 1 \& function: \*(Aqfunc\*(Aq name \*(Aq(\*(Aq list[rule=>\*(Aqparam\*(Aq,sep=>\*(Aq;\*(Aq] \*(Aq)\*(Aq \& \& param: list[rule=>\*(Aqname\*(Aq,sep=>\*(Aq,\*(Aq] \*(Aq:\*(Aq typename \& \& name: /\ew+/ \& \& typename: name .Ve .PP When a subrule argument list is used with a repeated subrule, the argument list goes \fIbefore\fR the repetition specifier: .PP .Vb 1 \& list: /some|many/ thing[ $item[1] ](s) .Ve .PP The argument list is \*(L"late bound\*(R". That is, it is re-evaluated for every repetition of the repeated subrule. This means that each repeated attempt to match the subrule may be passed a completely different set of arguments if the value of the expression in the argument list changes between attempts. So, for example, the grammar: .PP .Vb 1 \& { $::species = \*(Aqdogs\*(Aq } \& \& pair: \*(Aqtwo\*(Aq animal[$::species](s) \& \& animal: /$arg[0]/ { $::species = \*(Aqcats\*(Aq } .Ve .PP will match the string \*(L"two dogs cats cats\*(R" completely, whereas it will only match the string \*(L"two dogs dogs dogs\*(R" up to the eighth letter. If the value of the argument list were \*(L"early bound\*(R" (that is, evaluated only the first time a repeated subrule match is attempted), one would expect the matching behaviours to be reversed. .PP Of course, it is possible to effectively \*(L"early bind\*(R" such argument lists by passing them a value which does not change on each repetition. For example: .PP .Vb 1 \& { $::species = \*(Aqdogs\*(Aq } \& \& pair: \*(Aqtwo\*(Aq { $::species } animal[$item[2]](s) \& \& animal: /$arg[0]/ { $::species = \*(Aqcats\*(Aq } .Ve .PP Arguments can also be passed to the start rule, simply by appending them to the argument list with which the start rule is called (\fIafter\fR the \&\*(L"line number\*(R" parameter). For example, given: .PP .Vb 1 \& $parser = new Parse::RecDescent ( $grammar ); \& \& $parser\->data($text, 1, "str", 2, \e@arr); \& \& # ^^^^^ ^ ^^^^^^^^^^^^^^^ \& # | | | \& # TEXT TO BE PARSED | | \& # STARTING LINE NUMBER | \& # ELEMENTS OF @arg WHICH IS PASSED TO RULE data .Ve .PP then within the productions of the rule \f(CW\*(C`data\*(C'\fR, the array \f(CW@arg\fR will contain \&\f(CW\*(C`("str", 2, \e@arr)\*(C'\fR. .SS "Alternations" .IX Subsection "Alternations" Alternations are implicit (unnamed) rules defined as part of a production. An alternation is defined as a series of '|'\-separated productions inside a pair of round brackets. For example: .PP .Vb 1 \& character: \*(Aqthe\*(Aq ( good | bad | ugly ) /dude/ .Ve .PP Every alternation implicitly defines a new subrule, whose automatically-generated name indicates its origin: \&\*(L"_alternation_<I>_of_production_<P>_of_rule<R>\*(R" for the appropriate values of <I>, <P>, and <R>. A call to this implicit subrule is then inserted in place of the brackets. Hence the above example is merely a convenient short-hand for: .PP .Vb 3 \& character: \*(Aqthe\*(Aq \& _alternation_1_of_production_1_of_rule_character \& /dude/ \& \& _alternation_1_of_production_1_of_rule_character: \& good | bad | ugly .Ve .PP Since alternations are parsed by recursively calling the parser generator, any type(s) of item can appear in an alternation. For example: .PP .Vb 5 \& character: \*(Aqthe\*(Aq ( \*(Aqhigh\*(Aq "plains" # Silent, with poncho \& | /no[\- ]name/ # Silent, no poncho \& | vengeance_seeking # Poncho\-optional \& | <error> \& ) drifter .Ve .PP In this case, if an error occurred, the automatically generated message would be: .PP .Vb 3 \& ERROR (line <N>): Invalid implicit subrule: Expected \& \*(Aqhigh\*(Aq or /no[\- ]name/ or generic, \& but found "pacifist" instead .Ve .PP Since every alternation actually has a name, it's even possible to extend or replace them: .PP .Vb 4 \& parser\->Replace( \& "_alternation_1_of_production_1_of_rule_character: \& \*(Aqgeneric Eastwood\*(Aq" \& ); .Ve .PP More importantly, since alternations are a form of subrule, they can be given repetition specifiers: .PP .Vb 1 \& character: \*(Aqthe\*(Aq ( good | bad | ugly )(?) /dude/ .Ve .SS "Incremental Parsing" .IX Subsection "Incremental Parsing" \&\f(CW\*(C`Parse::RecDescent\*(C'\fR provides two methods \- \f(CW\*(C`Extend\*(C'\fR and \f(CW\*(C`Replace\*(C'\fR \- which can be used to alter the grammar matched by a parser. Both methods take the same argument as \f(CW\*(C`Parse::RecDescent::new\*(C'\fR, namely a grammar specification string .PP \&\f(CW\*(C`Parse::RecDescent::Extend\*(C'\fR interprets the grammar specification and adds any productions it finds to the end of the rules for which they are specified. For example: .PP .Vb 2 \& $add = "name: \*(AqJimmy\-Bob\*(Aq | \*(AqBobby\-Jim\*(Aq\endesc: colour /necks?/"; \& parser\->Extend($add); .Ve .PP adds two productions to the rule \*(L"name\*(R" (creating it if necessary) and one production to the rule \*(L"desc\*(R". .PP \&\f(CW\*(C`Parse::RecDescent::Replace\*(C'\fR is identical, except that it first resets are rule specified in the additional grammar, removing any existing productions. Hence after: .PP .Vb 2 \& $add = "name: \*(AqJimmy\-Bob\*(Aq | \*(AqBobby\-Jim\*(Aq\endesc: colour /necks?/"; \& parser\->Replace($add); .Ve .PP there are \fIonly\fR valid \*(L"name\*(R"s and the one possible description. .PP A more interesting use of the \f(CW\*(C`Extend\*(C'\fR and \f(CW\*(C`Replace\*(C'\fR methods is to call them inside the action of an executing parser. For example: .PP .Vb 3 \& typedef: \*(Aqtypedef\*(Aq type_name identifier \*(Aq;\*(Aq \& { $thisparser\->Extend("type_name: \*(Aq$item[3]\*(Aq") } \& | <error> \& \& identifier: ...!type_name /[A\-Za\-z_]w*/ .Ve .PP which automatically prevents type names from being typedef'd, or: .PP .Vb 6 \& command: \*(Aqmap\*(Aq key_name \*(Aqto\*(Aq abort_key \& { $thisparser\->Replace("abort_key: \*(Aq$item[2]\*(Aq") } \& | \*(Aqmap\*(Aq key_name \*(Aqto\*(Aq key_name \& { map_key($item[2],$item[4]) } \& | abort_key \& { exit if confirm("abort?") } \& \& abort_key: \*(Aqq\*(Aq \& \& key_name: ...!abort_key /[A\-Za\-z]/ .Ve .PP which allows the user to change the abort key binding, but not to unbind it. .PP The careful use of such constructs makes it possible to reconfigure a a running parser, eliminating the need for semantic feedback by providing syntactic feedback instead. However, as currently implemented, \&\f(CW\*(C`Replace()\*(C'\fR and \f(CW\*(C`Extend()\*(C'\fR have to regenerate and re\-\f(CW\*(C`eval\*(C'\fR the entire parser whenever they are called. This makes them quite slow for large grammars. .PP In such cases, the judicious use of an interpolated regex is likely to be far more efficient: .PP .Vb 3 \& typedef: \*(Aqtypedef\*(Aq type_name/ identifier \*(Aq;\*(Aq \& { $thisparser\->{local}{type_name} .= "|$item[3]" } \& | <error> \& \& identifier: ...!type_name /[A\-Za\-z_]w*/ \& \& type_name: /$thisparser\->{local}{type_name}/ .Ve .SS "Precompiling parsers" .IX Subsection "Precompiling parsers" Normally Parse::RecDescent builds a parser from a grammar at run-time. That approach simplifies the design and implementation of parsing code, but has the disadvantage that it slows the parsing process down \- you have to wait for Parse::RecDescent to build the parser every time the program runs. Long or complex grammars can be particularly slow to build, leading to unacceptable delays at start-up. .PP To overcome this, the module provides a way of \*(L"pre-building\*(R" a parser object and saving it in a separate module. That module can then be used to create clones of the original parser. .PP A grammar may be precompiled using the \f(CW\*(C`Precompile\*(C'\fR class method. For example, to precompile a grammar stored in the scalar \f(CW$grammar\fR, and produce a class named PreGrammar in a module file named PreGrammar.pm, you could use: .PP .Vb 1 \& use Parse::RecDescent; \& \& Parse::RecDescent\->Precompile([$options_hashref], $grammar, "PreGrammar", ["RuntimeClass"]); .Ve .PP The first required argument is the grammar string, the second is the name of the class to be built. The name of the module file is generated automatically by appending \*(L".pm\*(R" to the last element of the class name. Thus .PP .Vb 1 \& Parse::RecDescent\->Precompile($grammar, "My::New::Parser"); .Ve .PP would produce a module file named Parser.pm. .PP After the class name, you may specify the name of the runtime_class called by the Precompiled parser. See \*(L"Precompiled runtimes\*(R" for more details. .PP An optional hash reference may be supplied as the first argument to \&\f(CW\*(C`Precompile\*(C'\fR. This argument is currently \s-1EXPERIMENTAL,\s0 and may change in a future release of Parse::RecDescent. The only supported option is currently \f(CW\*(C`\-standalone\*(C'\fR, see \*(L"Standalone precompiled parsers\*(R". .PP It is somewhat tedious to have to write a small Perl program just to generate a precompiled grammar class, so Parse::RecDescent has some special magic that allows you to do the job directly from the command-line. .PP If your grammar is specified in a file named \fIgrammar\fR, you can generate a class named Yet::Another::Grammar like so: .PP .Vb 1 \& > perl \-MParse::RecDescent \- grammar Yet::Another::Grammar [Runtime::Class] .Ve .PP This would produce a file named \fIGrammar.pm\fR containing the full definition of a class called Yet::Another::Grammar. Of course, to use that class, you would need to put the \fIGrammar.pm\fR file in a directory named \fIYet/Another\fR, somewhere in your Perl include path. .PP Having created the new class, it's very easy to use it to build a parser. You simply \f(CW\*(C`use\*(C'\fR the new module, and then call its \&\f(CW\*(C`new\*(C'\fR method to create a parser object. For example: .PP .Vb 2 \& use Yet::Another::Grammar; \& my $parser = Yet::Another::Grammar\->new(); .Ve .PP The effect of these two lines is exactly the same as: .PP .Vb 1 \& use Parse::RecDescent; \& \& open GRAMMAR_FILE, "grammar" or die; \& local $/; \& my $grammar = <GRAMMAR_FILE>; \& \& my $parser = Parse::RecDescent\->new($grammar); .Ve .PP only considerably faster. .PP Note however that the parsers produced by either approach are exactly the same, so whilst precompilation has an effect on \fIset-up\fR speed, it has no effect on \fIparsing\fR speed. RecDescent 2.0 will address that problem. .PP \fIStandalone precompiled parsers\fR .IX Subsection "Standalone precompiled parsers" .PP Until version 1.967003 of Parse::RecDescent, parser modules built with \&\f(CW\*(C`Precompile\*(C'\fR were dependent on Parse::RecDescent. Future Parse::RecDescent releases with different internal implementations would break pre-existing precompiled parsers. .PP Version 1.967_005 added the ability for Parse::RecDescent to include itself in the resulting .pm file if you pass the boolean option \&\f(CW\*(C`\-standalone\*(C'\fR to \f(CW\*(C`Precompile\*(C'\fR: .PP .Vb 2 \& Parse::RecDescent\->Precompile({ \-standalone => 1, }, \& $grammar, "My::New::Parser"); .Ve .PP Parse::RecDescent is included as \f(CW$class::_Runtime\fR in order to avoid conflicts between an installed version of Parse::RecDescent and other precompiled, standalone parser made with Parse::RecDescent. The name of this class may be changed with the \f(CW\*(C`\-runtime_class\*(C'\fR option to Precompile. This renaming is experimental, and is subject to change in future versions. .PP Precompiled parsers remain dependent on Parse::RecDescent by default, as this feature is still considered experimental. In the future, standalone parsers will become the default. .PP \fIPrecompiled runtimes\fR .IX Subsection "Precompiled runtimes" .PP Standalone precompiled parsers each include a copy of Parse::RecDescent. For users who have a family of related precompiled parsers, this is very inefficient. \f(CW\*(C`Precompile\*(C'\fR now supports an experimental \f(CW\*(C`\-runtime_class\*(C'\fR option. To build a precompiled parser with a different runtime name, call: .PP .Vb 5 \& Parse::RecDescent\->Precompile({ \& \-standalone => 1, \& \-runtime_class => "My::Runtime", \& }, \& $grammar, "My::New::Parser"); .Ve .PP The resulting standalone parser will contain a copy of Parse::RecDescent, renamed to \*(L"My::Runtime\*(R". .PP To build a set of parsers that \f(CW\*(C`use\*(C'\fR a custom-named runtime, without including that runtime in the output, simply build those parsers with \&\f(CW\*(C`\-runtime_class\*(C'\fR and without \f(CW\*(C`\-standalone\*(C'\fR: .PP .Vb 4 \& Parse::RecDescent\->Precompile({ \& \-runtime_class => "My::Runtime", \& }, \& $grammar, "My::New::Parser"); .Ve .PP The runtime itself must be generated as well, so that it may be \&\f(CW\*(C`use\*(C'\fRd by My::New::Parser. To generate the runtime file, use one of the two folling calls: .PP .Vb 1 \& Parse::RecDescent\->PrecompiledRuntime("My::Runtime"); \& \& Parse::RecDescent\->Precompile({ \& \-standalone => 1, \& \-runtime_class => "My::Runtime", \& }, \& \*(Aq\*(Aq, # empty grammar \& "My::Runtime"); .Ve .SH "GOTCHAS" .IX Header "GOTCHAS" This section describes common mistakes that grammar writers seem to make on a regular basis. .SS "1. Expecting an error to always invalidate a parse" .IX Subsection "1. Expecting an error to always invalidate a parse" A common mistake when using error messages is to write the grammar like this: .PP .Vb 1 \& file: line(s) \& \& line: line_type_1 \& | line_type_2 \& | line_type_3 \& | <error> .Ve .PP The expectation seems to be that any line that is not of type 1, 2 or 3 will invoke the \f(CW\*(C`<error>\*(C'\fR directive and thereby cause the parse to fail. .PP Unfortunately, that only happens if the error occurs in the very first line. The first rule states that a \f(CW\*(C`file\*(C'\fR is matched by one or more lines, so if even a single line succeeds, the first rule is completely satisfied and the parse as a whole succeeds. That means that any error messages generated by subsequent failures in the \f(CW\*(C`line\*(C'\fR rule are quietly ignored. .PP Typically what's really needed is this: .PP .Vb 1 \& file: line(s) eofile { $return = $item[1] } \& \& line: line_type_1 \& | line_type_2 \& | line_type_3 \& | <error> \& \& eofile: /^\eZ/ .Ve .PP The addition of the \f(CW\*(C`eofile\*(C'\fR subrule to the first production means that a file only matches a series of successful \f(CW\*(C`line\*(C'\fR matches \fIthat consume the complete input text\fR. If any input text remains after the lines are matched, there must have been an error in the last \f(CW\*(C`line\*(C'\fR. In that case the \f(CW\*(C`eofile\*(C'\fR rule will fail, causing the entire \f(CW\*(C`file\*(C'\fR rule to fail too. .PP Note too that \f(CW\*(C`eofile\*(C'\fR must match \f(CW\*(C`/^\eZ/\*(C'\fR (end-of-text), \fInot\fR \&\f(CW\*(C`/^\ecZ/\*(C'\fR or \f(CW\*(C`/^\ecD/\*(C'\fR (end-of-file). .PP And don't forget the action at the end of the production. If you just write: .PP .Vb 1 \& file: line(s) eofile .Ve .PP then the value returned by the \f(CW\*(C`file\*(C'\fR rule will be the value of its last item: \f(CW\*(C`eofile\*(C'\fR. Since \f(CW\*(C`eofile\*(C'\fR always returns an empty string on success, that will cause the \f(CW\*(C`file\*(C'\fR rule to return that empty string. Apart from returning the wrong value, returning an empty string will trip up code such as: .PP .Vb 1 \& $parser\->file($filetext) || die; .Ve .PP (since "" is false). .PP Remember that Parse::RecDescent returns undef on failure, so the only safe test for failure is: .PP .Vb 1 \& defined($parser\->file($filetext)) || die; .Ve .ie n .SS "2. Using a ""return"" in an action" .el .SS "2. Using a \f(CWreturn\fP in an action" .IX Subsection "2. Using a return in an action" An action is like a \f(CW\*(C`do\*(C'\fR block inside the subroutine implementing the surrounding rule. So if you put a \f(CW\*(C`return\*(C'\fR statement in an action: .PP .Vb 3 \& range: \*(Aq(\*(Aq start \*(Aq..\*(Aq end )\*(Aq \& { return $item{end} } \& /\es+/ .Ve .PP that subroutine will immediately return, without checking the rest of the items in the current production (e.g. the \f(CW\*(C`/\es+/\*(C'\fR) and without setting up the necessary data structures to tell the parser that the rule has succeeded. .PP The correct way to set a return value in an action is to set the \f(CW$return\fR variable: .PP .Vb 3 \& range: \*(Aq(\*(Aq start \*(Aq..\*(Aq end )\*(Aq \& { $return = $item{end} } \& /\es+/ .Ve .ie n .SS "2. Setting $Parse::RecDescent::skip at parse time" .el .SS "2. Setting \f(CW$Parse::RecDescent::skip\fP at parse time" .IX Subsection "2. Setting $Parse::RecDescent::skip at parse time" If you want to change the default skipping behaviour (see \&\*(L"Terminal Separators\*(R" and the \f(CW\*(C`<skip:...>\*(C'\fR directive) by setting \&\f(CW$Parse::RecDescent::skip\fR you have to remember to set this variable \&\fIbefore\fR creating the grammar object. .PP For example, you might want to skip all Perl-like comments with this regular expression: .PP .Vb 6 \& my $skip_spaces_and_comments = qr/ \& (?mxs: \& \es+ # either spaces \& | \e# .*?$ # or a dash and whatever up to the end of line \& )* # repeated at will (in whatever order) \& /; .Ve .PP And then: .PP .Vb 1 \& my $parser1 = Parse::RecDescent\->new($grammar); \& \& $Parse::RecDescent::skip = $skip_spaces_and_comments; \& \& my $parser2 = Parse::RecDescent\->new($grammar); \& \& $parser1\->parse($text); # this does not cope with comments \& $parser2\->parse($text); # this skips comments correctly .Ve .PP The two parsers behave differently, because any skipping behaviour specified via \f(CW$Parse::RecDescent::skip\fR is hard-coded when the grammar object is built, not at parse time. .SH "DIAGNOSTICS" .IX Header "DIAGNOSTICS" Diagnostics are intended to be self-explanatory (particularly if you use \fB\-RD_HINT\fR (under \fBperl \-s\fR) or define \f(CW$::RD_HINT\fR inside the program). .PP \&\f(CW\*(C`Parse::RecDescent\*(C'\fR currently diagnoses the following: .IP "\(bu" 4 Invalid regular expressions used as pattern terminals (fatal error). .IP "\(bu" 4 Invalid Perl code in code blocks (fatal error). .IP "\(bu" 4 Lookahead used in the wrong place or in a nonsensical way (fatal error). .IP "\(bu" 4 \&\*(L"Obvious\*(R" cases of left-recursion (fatal error). .IP "\(bu" 4 Missing or extra components in a \f(CW\*(C`<leftop>\*(C'\fR or \f(CW\*(C`<rightop>\*(C'\fR directive. .IP "\(bu" 4 Unrecognisable components in the grammar specification (fatal error). .IP "\(bu" 4 \&\*(L"Orphaned\*(R" rule components specified before the first rule (fatal error) or after an \f(CW\*(C`<error>\*(C'\fR directive (level 3 warning). .IP "\(bu" 4 Missing rule definitions (this only generates a level 3 warning, since you may be providing them later via \f(CW\*(C`Parse::RecDescent::Extend()\*(C'\fR). .IP "\(bu" 4 Instances where greedy repetition behaviour will almost certainly cause the failure of a production (a level 3 warning \- see \&\*(L"ON-GOING \s-1ISSUES AND FUTURE DIRECTIONS\*(R"\s0 below). .IP "\(bu" 4 Attempts to define rules named 'Replace' or 'Extend', which cannot be called directly through the parser object because of the predefined meaning of \f(CW\*(C`Parse::RecDescent::Replace\*(C'\fR and \&\f(CW\*(C`Parse::RecDescent::Extend\*(C'\fR. (Only a level 2 warning is generated, since such rules \fIcan\fR still be used as subrules). .IP "\(bu" 4 Productions which consist of a single \f(CW\*(C`<error?>\*(C'\fR directive, and which therefore may succeed unexpectedly (a level 2 warning, since this might conceivably be the desired effect). .IP "\(bu" 4 Multiple consecutive lookahead specifiers (a level 1 warning only, since their effects simply accumulate). .IP "\(bu" 4 Productions which start with a \f(CW\*(C`<reject>\*(C'\fR or \f(CW\*(C`<rulevar:...>\*(C'\fR directive. Such productions are optimized away (a level 1 warning). .IP "\(bu" 4 Rules which are autogenerated under \f(CW$::AUTOSTUB\fR (a level 1 warning). .SH "AUTHOR" .IX Header "AUTHOR" Damian Conway (damian@conway.org) Jeremy T. Braun (JTBRAUN@CPAN.org) [current maintainer] .SH "BUGS AND IRRITATIONS" .IX Header "BUGS AND IRRITATIONS" There are undoubtedly serious bugs lurking somewhere in this much code :\-) Bug reports, test cases and other feedback are most welcome. .PP Ongoing annoyances include: .IP "\(bu" 4 There's no support for parsing directly from an input stream. If and when the Perl Gods give us regular expressions on streams, this should be trivial (ahem!) to implement. .IP "\(bu" 4 The parser generator can get confused if actions aren't properly closed or if they contain particularly nasty Perl syntax errors (especially unmatched curly brackets). .IP "\(bu" 4 The generator only detects the most obvious form of left recursion (potential recursion on the first subrule in a rule). More subtle forms of left recursion (for example, through the second item in a rule after a \*(L"zero\*(R" match of a preceding \*(L"zero-or-more\*(R" repetition, or after a match of a subrule with an empty production) are not found. .IP "\(bu" 4 Instead of complaining about left-recursion, the generator should silently transform the grammar to remove it. Don't expect this feature any time soon as it would require a more sophisticated approach to parser generation than is currently used. .IP "\(bu" 4 The generated parsers don't always run as fast as might be wished. .IP "\(bu" 4 The meta-parser should be bootstrapped using \f(CW\*(C`Parse::RecDescent\*(C'\fR :\-) .SH "ON-GOING ISSUES AND FUTURE DIRECTIONS" .IX Header "ON-GOING ISSUES AND FUTURE DIRECTIONS" .IP "1." 4 Repetitions are \*(L"incorrigibly greedy\*(R" in that they will eat everything they can and won't backtrack if that behaviour causes a production to fail needlessly. So, for example: .Sp .Vb 1 \& rule: subrule(s) subrule .Ve .Sp will \fInever\fR succeed, because the repetition will eat all the subrules it finds, leaving none to match the second item. Such constructions are relatively rare (and \f(CW\*(C`Parse::RecDescent::new\*(C'\fR generates a warning whenever they occur) so this may not be a problem, especially since the insatiable behaviour can be overcome \*(L"manually\*(R" by writing: .Sp .Vb 1 \& rule: penultimate_subrule(s) subrule \& \& penultimate_subrule: subrule ...subrule .Ve .Sp The issue is that this construction is exactly twice as expensive as the original, whereas backtracking would add only 1/\fIN\fR to the cost (for matching \fIN\fR repetitions of \f(CW\*(C`subrule\*(C'\fR). I would welcome feedback on the need for backtracking; particularly on cases where the lack of it makes parsing performance problematical. .IP "2." 4 Having opened that can of worms, it's also necessary to consider whether there is a need for non-greedy repetition specifiers. Again, it's possible (at some cost) to manually provide the required functionality: .Sp .Vb 1 \& rule: nongreedy_subrule(s) othersubrule \& \& nongreedy_subrule: subrule ...!othersubrule .Ve .Sp Overall, the issue is whether the benefit of this extra functionality outweighs the drawbacks of further complicating the (currently minimalist) grammar specification syntax, and (worse) introducing more overhead into the generated parsers. .IP "3." 4 An \f(CW\*(C`<autocommit>\*(C'\fR directive would be nice. That is, it would be useful to be able to say: .Sp .Vb 7 \& command: <autocommit> \& command: \*(Aqfind\*(Aq name \& | \*(Aqfind\*(Aq address \& | \*(Aqdo\*(Aq command \*(Aqat\*(Aq time \*(Aqif\*(Aq condition \& | \*(Aqdo\*(Aq command \*(Aqat\*(Aq time \& | \*(Aqdo\*(Aq command \& | unusual_command .Ve .Sp and have the generator work out that this should be \*(L"pruned\*(R" thus: .Sp .Vb 9 \& command: \*(Aqfind\*(Aq name \& | \*(Aqfind\*(Aq <commit> address \& | \*(Aqdo\*(Aq <commit> command <uncommit> \& \*(Aqat\*(Aq time \& \*(Aqif\*(Aq <commit> condition \& | \*(Aqdo\*(Aq <commit> command <uncommit> \& \*(Aqat\*(Aq <commit> time \& | \*(Aqdo\*(Aq <commit> command \& | unusual_command .Ve .Sp There are several issues here. Firstly, should the \&\f(CW\*(C`<autocommit>\*(C'\fR automatically install an \f(CW\*(C`<uncommit>\*(C'\fR at the start of the last production (on the grounds that the \*(L"command\*(R" rule doesn't know whether an \*(L"unusual_command\*(R" might start with \*(L"find\*(R" or \*(L"do\*(R") or should the \*(L"unusual_command\*(R" subgraph be analysed (to see if it \fImight\fR be viable after a \*(L"find\*(R" or \*(L"do\*(R")? .Sp The second issue is how regular expressions should be treated. The simplest approach would be simply to uncommit before them (on the grounds that they \&\fImight\fR match). Better efficiency would be obtained by analyzing all preceding literal tokens to determine whether the pattern would match them. .Sp Overall, the issues are: can such automated \*(L"pruning\*(R" approach a hand-tuned version sufficiently closely to warrant the extra set-up expense, and (more importantly) is the problem important enough to even warrant the non-trivial effort of building an automated solution? .SH "SUPPORT" .IX Header "SUPPORT" .SS "Source Code Repository" .IX Subsection "Source Code Repository" <http://github.com/jtbraun/Parse\-RecDescent> .SS "Mailing List" .IX Subsection "Mailing List" Visit <http://www.perlfoundation.org/perl5/index.cgi?parse_recdescent> to sign up for the mailing list. .PP <http://www.PerlMonks.org> is also a good place to ask questions. Previous posts about Parse::RecDescent can typically be found with this search: <http://perlmonks.org/index.pl?node=recdescent>. .SS "\s-1FAQ\s0" .IX Subsection "FAQ" Visit Parse::RecDescent::FAQ for answers to frequently (and not so frequently) asked questions about Parse::RecDescent. .SS "View/Report Bugs" .IX Subsection "View/Report Bugs" To view the current bug list or report a new issue visit <https://rt.cpan.org/Public/Dist/Display.html?Name=Parse\-RecDescent>. .SH "SEE ALSO" .IX Header "SEE ALSO" Regexp::Grammars provides Parse::RecDescent style parsing using native Perl 5.10 regular expressions. .SH "LICENCE AND COPYRIGHT" .IX Header "LICENCE AND COPYRIGHT" Copyright (c) 1997\-2007, Damian Conway \f(CW\*(C`<DCONWAY@CPAN.org>\*(C'\fR. All rights reserved. .PP This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic. .SH "DISCLAIMER OF WARRANTY" .IX Header "DISCLAIMER OF WARRANTY" \&\s-1BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE \*(L"AS IS\*(R" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.\s0 .PP \&\s-1IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE \s0(\s-1INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE\s0), \s-1EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\s0