home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / RecDescent.pod < prev    next >
Encoding:
Text File  |  2003-06-10  |  103.8 KB  |  2,824 lines

  1. =head1 NAME
  2.  
  3. Parse::RecDescent - Generate Recursive-Descent Parsers
  4.  
  5. =head1 VERSION
  6.  
  7. This document describes version 1.94 of Parse::RecDescent,
  8. released April  9, 2003.
  9.  
  10. =head1 SYNOPSIS
  11.  
  12.  use Parse::RecDescent;
  13.  
  14.  # Generate a parser from the specification in $grammar:
  15.  
  16.      $parser = new Parse::RecDescent ($grammar);
  17.  
  18.  # Generate a parser from the specification in $othergrammar
  19.  
  20.      $anotherparser = new Parse::RecDescent ($othergrammar);
  21.  
  22.  
  23.  # Parse $text using rule 'startrule' (which must be
  24.  # defined in $grammar):
  25.  
  26.     $parser->startrule($text);
  27.  
  28.  
  29.  # Parse $text using rule 'otherrule' (which must also
  30.  # be defined in $grammar):
  31.  
  32.      $parser->otherrule($text);
  33.  
  34.  
  35.  # Change the universal token prefix pattern
  36.  # (the default is: '\s*'):
  37.  
  38.     $Parse::RecDescent::skip = '[ \t]+';
  39.  
  40.  
  41.  # Replace productions of existing rules (or create new ones)
  42.  # with the productions defined in $newgrammar:
  43.  
  44.     $parser->Replace($newgrammar);
  45.  
  46.  
  47.  # Extend existing rules (or create new ones)
  48.  # by adding extra productions defined in $moregrammar:
  49.  
  50.     $parser->Extend($moregrammar);
  51.  
  52.  
  53.  # Global flags (useful as command line arguments under -s):
  54.  
  55.     $::RD_ERRORS       # unless undefined, report fatal errors
  56.     $::RD_WARN       # unless undefined, also report non-fatal problems
  57.     $::RD_HINT       # if defined, also suggestion remedies
  58.     $::RD_TRACE       # if defined, also trace parsers' behaviour
  59.     $::RD_AUTOSTUB       # if defined, generates "stubs" for undefined rules
  60.     $::RD_AUTOACTION   # if defined, appends specified action to productions
  61.  
  62.  
  63. =head1 DESCRIPTION
  64.  
  65. =head2 Overview
  66.  
  67. Parse::RecDescent incrementally generates top-down recursive-descent text
  68. parsers from simple I<yacc>-like grammar specifications. It provides:
  69.  
  70. =over 4
  71.  
  72. =item *
  73.  
  74. Regular expressions or literal strings as terminals (tokens),
  75.  
  76. =item *
  77.  
  78. Multiple (non-contiguous) productions for any rule,
  79.  
  80. =item *
  81.  
  82. Repeated and optional subrules within productions,
  83.  
  84. =item *
  85.  
  86. Full access to Perl within actions specified as part of the grammar,
  87.  
  88. =item *
  89.  
  90. Simple automated error reporting during parser generation and parsing,
  91.  
  92. =item *
  93.  
  94. The ability to commit to, uncommit to, or reject particular
  95. productions during a parse,
  96.  
  97. =item *
  98.  
  99. The ability to pass data up and down the parse tree ("down" via subrule
  100. argument lists, "up" via subrule return values)
  101.  
  102. =item *
  103.  
  104. Incremental extension of the parsing grammar (even during a parse),
  105.  
  106. =item *
  107.  
  108. Precompilation of parser objects,
  109.  
  110. =item *
  111.  
  112. User-definable reduce-reduce conflict resolution via
  113. "scoring" of matching productions.
  114.  
  115. =back
  116.  
  117. =head2 Using C<Parse::RecDescent>
  118.  
  119. Parser objects are created by calling C<Parse::RecDescent::new>, passing in a
  120. grammar specification (see the following subsections). If the grammar is
  121. correct, C<new> returns a blessed reference which can then be used to initiate
  122. parsing through any rule specified in the original grammar. A typical sequence
  123. looks like this:
  124.  
  125.     $grammar = q {
  126.             # GRAMMAR SPECIFICATION HERE
  127.              };
  128.  
  129.     $parser = new Parse::RecDescent ($grammar) or die "Bad grammar!\n";
  130.  
  131.     # acquire $text
  132.  
  133.     defined $parser->startrule($text) or print "Bad text!\n";
  134.  
  135. The rule through which parsing is initiated must be explicitly defined
  136. in the grammar (i.e. for the above example, the grammar must include a
  137. rule of the form: "startrule: <subrules>".
  138.  
  139. If the starting rule succeeds, its value (see below)
  140. is returned. Failure to generate the original parser or failure to match a text
  141. is indicated by returning C<undef>. Note that it's easy to set up grammars
  142. that can succeed, but which return a value of 0, "0", or "".  So don't be
  143. tempted to write:
  144.  
  145.     $parser->startrule($text) or print "Bad text!\n";
  146.  
  147. Normally, the parser has no effect on the original text. So in the
  148. previous example the value of $text would be unchanged after having
  149. been parsed.
  150.  
  151. If, however, the text to be matched is passed by reference:
  152.  
  153.     $parser->startrule(\$text)
  154.  
  155. then any text which was consumed during the match will be removed from the
  156. start of $text.
  157.  
  158.  
  159. =head2 Rules
  160.  
  161. In the grammar from which the parser is built, rules are specified by
  162. giving an identifier (which must satisfy /[A-Za-z]\w*/), followed by a
  163. colon I<on the same line>, followed by one or more productions,
  164. separated by single vertical bars. The layout of the productions
  165. is entirely free-format:
  166.  
  167.     rule1:    production1
  168.          |  production2 |
  169.         production3 | production4
  170.  
  171. At any point in the grammar previously defined rules may be extended with
  172. additional productions. This is achieved by redeclaring the rule with the new
  173. productions. Thus:
  174.  
  175.     rule1: a | b | c
  176.     rule2: d | e | f
  177.     rule1: g | h
  178.  
  179. is exactly equivalent to:
  180.  
  181.     rule1: a | b | c | g | h
  182.     rule2: d | e | f
  183.  
  184. Each production in a rule consists of zero or more items, each of which
  185. may be either: the name of another rule to be matched (a "subrule"),
  186. a pattern or string literal to be matched directly (a "token"), a
  187. block of Perl code to be executed (an "action"), a special instruction
  188. to the parser (a "directive"), or a standard Perl comment (which is
  189. ignored).
  190.  
  191. A rule matches a text if one of its productions matches. A production
  192. matches if each of its items match consecutive substrings of the
  193. text. The productions of a rule being matched are tried in the same
  194. order that they appear in the original grammar, and the first matching
  195. production terminates the match attempt (successfully). If all
  196. productions are tried and none matches, the match attempt fails.
  197.  
  198. Note that this behaviour is quite different from the "prefer the longer match"
  199. behaviour of I<yacc>. For example, if I<yacc> were parsing the rule:
  200.  
  201.     seq : 'A' 'B'
  202.         | 'A' 'B' 'C'
  203.  
  204. upon matching "AB" it would look ahead to see if a 'C' is next and, if
  205. so, will match the second production in preference to the first. In
  206. other words, I<yacc> effectively tries all the productions of a rule
  207. breadth-first in parallel, and selects the "best" match, where "best"
  208. means longest (note that this is a gross simplification of the true
  209. behaviour of I<yacc> but it will do for our purposes).
  210.  
  211. In contrast, C<Parse::RecDescent> tries each production depth-first in
  212. sequence, and selects the "best" match, where "best" means first. This is
  213. the fundamental difference between "bottom-up" and "recursive descent"
  214. parsing.
  215.  
  216. Each successfully matched item in a production is assigned a value,
  217. which can be accessed in subsequent actions within the same
  218. production (or, in some cases, as the return value of a successful
  219. subrule call). Unsuccessful items don't have an associated value,
  220. since the failure of an item causes the entire surrounding production
  221. to immediately fail. The following sections describe the various types
  222. of items and their success values.
  223.  
  224.  
  225. =head2 Subrules
  226.  
  227. A subrule which appears in a production is an instruction to the parser to
  228. attempt to match the named rule at that point in the text being
  229. parsed. If the named subrule is not defined when requested the
  230. production containing it immediately fails (unless it was "autostubbed" - see
  231. L<Autostubbing>).
  232.  
  233. A rule may (recursively) call itself as a subrule, but I<not> as the
  234. left-most item in any of its productions (since such recursions are usually
  235. non-terminating).
  236.  
  237. The value associated with a subrule is the value associated with its
  238. C<$return> variable (see L<"Actions"> below), or with the last successfully
  239. matched item in the subrule match.
  240.  
  241. Subrules may also be specified with a trailing repetition specifier,
  242. indicating that they are to be (greedily) matched the specified number
  243. of times. The available specifiers are:
  244.  
  245.         subrule(?)    # Match one-or-zero times
  246.         subrule(s)    # Match one-or-more times
  247.         subrule(s?)    # Match zero-or-more times
  248.         subrule(N)    # Match exactly N times for integer N > 0
  249.         subrule(N..M)    # Match between N and M times
  250.         subrule(..M)    # Match between 1 and M times
  251.         subrule(N..)    # Match at least N times
  252.  
  253. Repeated subrules keep matching until either the subrule fails to
  254. match, or it has matched the minimal number of times but fails to
  255. consume any of the parsed text (this second condition prevents the
  256. subrule matching forever in some cases).
  257.  
  258. Since a repeated subrule may match many instances of the subrule itself, the
  259. value associated with it is not a simple scalar, but rather a reference to a
  260. list of scalars, each of which is the value associated with one of the
  261. individual subrule matches. In other words in the rule:
  262.  
  263.         program: statement(s)
  264.  
  265. the value associated with the repeated subrule "statement(s)" is a reference
  266. to an array containing the values matched by each call to the individual
  267. subrule "statement".
  268.  
  269. Repetition modifieres may include a separator pattern:
  270.  
  271.         program: statement(s /;/)
  272.  
  273. specifying some sequence of characters to be skipped between each repetition.
  274. This is really just a shorthand for the E<lt>leftop:...E<gt> directive
  275. (see below).
  276.  
  277. =head2 Tokens
  278.  
  279. If a quote-delimited string or a Perl regex appears in a production,
  280. the parser attempts to match that string or pattern at that point in
  281. the text. For example:
  282.  
  283.         typedef: "typedef" typename identifier ';'
  284.  
  285.         identifier: /[A-Za-z_][A-Za-z0-9_]*/
  286.  
  287. As in regular Perl, a single quoted string is uninterpolated, whilst
  288. a double-quoted string or a pattern is interpolated (at the time
  289. of matching, I<not> when the parser is constructed). Hence, it is
  290. possible to define rules in which tokens can be set at run-time:
  291.  
  292.         typedef: "$::typedefkeyword" typename identifier ';'
  293.  
  294.         identifier: /$::identpat/
  295.  
  296. Note that, since each rule is implemented inside a special namespace
  297. belonging to its parser, it is necessary to explicitly quantify
  298. variables from the main package.
  299.  
  300. Regex tokens can be specified using just slashes as delimiters
  301. or with the explicit C<mE<lt>delimiterE<gt>......E<lt>delimiterE<gt>> syntax:
  302.  
  303.         typedef: "typedef" typename identifier ';'
  304.  
  305.         typename: /[A-Za-z_][A-Za-z0-9_]*/
  306.  
  307.         identifier: m{[A-Za-z_][A-Za-z0-9_]*}
  308.  
  309. A regex of either type can also have any valid trailing parameter(s)
  310. (that is, any of [cgimsox]):
  311.  
  312.         typedef: "typedef" typename identifier ';'
  313.  
  314.         identifier: / [a-z_]         # LEADING ALPHA OR UNDERSCORE
  315.                   [a-z0-9_]*    # THEN DIGITS ALSO ALLOWED
  316.                 /ix            # CASE/SPACE/COMMENT INSENSITIVE
  317.  
  318. The value associated with any successfully matched token is a string
  319. containing the actual text which was matched by the token.
  320.  
  321. It is important to remember that, since each grammar is specified in a
  322. Perl string, all instances of the universal escape character '\' within
  323. a grammar must be "doubled", so that they interpolate to single '\'s when
  324. the string is compiled. For example, to use the grammar:
  325.  
  326.         word:        /\S+/ | backslash
  327.         line:        prefix word(s) "\n"
  328.         backslash:  '\\'
  329.  
  330. the following code is required:
  331.  
  332.         $parser = new Parse::RecDescent (q{
  333.  
  334.             word:        /\\S+/ | backslash
  335.             line:        prefix word(s) "\\n"
  336.             backslash:  '\\\\'
  337.  
  338.         });
  339.  
  340.  
  341. =head2 Terminal Separators
  342.  
  343. For the purpose of matching, each terminal in a production is considered
  344. to be preceded by a "prefix" - a pattern which must be
  345. matched before a token match is attempted. By default, the
  346. prefix is optional whitespace (which always matches, at
  347. least trivially), but this default may be reset in any production.
  348.  
  349. The variable C<$Parse::RecDescent::skip> stores the universal
  350. prefix, which is the default for all terminal matches in all parsers
  351. built with C<Parse::RecDescent>.
  352.  
  353. The prefix for an individual production can be altered
  354. by using the C<E<lt>skip:...E<gt>> directive (see below).
  355.  
  356.  
  357. =head2 Actions
  358.  
  359. An action is a block of Perl code which is to be executed (as the
  360. block of a C<do> statement) when the parser reaches that point in a
  361. production. The action executes within a special namespace belonging to
  362. the active parser, so care must be taken in correctly qualifying variable
  363. names (see also L<Start-up Actions> below).
  364.  
  365. The action is considered to succeed if the final value of the block
  366. is defined (that is, if the implied C<do> statement evaluates to a
  367. defined value - I<even one which would be treated as "false">). Note
  368. that the value associated with a successful action is also the final
  369. value in the block.
  370.  
  371. An action will I<fail> if its last evaluated value is C<undef>. This is
  372. surprisingly easy to accomplish by accident. For instance, here's an
  373. infuriating case of an action that makes its production fail, but only
  374. when debugging I<isn't> activated:
  375.  
  376.     description: name rank serial_number
  377.             { print "Got $item[2] $item[1] ($item[3])\n"
  378.                 if $::debugging
  379.             }
  380.  
  381. If C<$debugging> is false, no statement in the block is executed, so
  382. the final value is C<undef>, and the entire production fails. The solution is:
  383.  
  384.     description: name rank serial_number
  385.             { print "Got $item[2] $item[1] ($item[3])\n"
  386.                 if $::debugging;
  387.               1;
  388.             }
  389.  
  390. Within an action, a number of useful parse-time variables are
  391. available in the special parser namespace (there are other variables
  392. also accessible, but meddling with them will probably just break your
  393. parser. As a general rule, if you avoid referring to unqualified
  394. variables - especially those starting with an underscore - inside an action,
  395. things should be okay):
  396.  
  397. =over 4
  398.  
  399. =item C<@item> and C<%item>
  400.  
  401. The array slice C<@item[1..$#item]> stores the value associated with each item
  402. (that is, each subrule, token, or action) in the current production. The
  403. analogy is to C<$1>, C<$2>, etc. in a I<yacc> grammar.
  404. Note that, for obvious reasons, C<@item> only contains the
  405. values of items I<before> the current point in the production.
  406.  
  407. The first element (C<$item[0]>) stores the name of the current rule
  408. being matched.
  409.  
  410. C<@item> is a standard Perl array, so it can also be indexed with negative
  411. numbers, representing the number of items I<back> from the current position in
  412. the parse:
  413.  
  414.     stuff: /various/ bits 'and' pieces "then" data 'end'
  415.             { print $item[-2] }  # PRINTS data
  416.                          # (EASIER THAN: $item[6])
  417.  
  418. The C<%item> hash complements the <@item> array, providing named
  419. access to the same item values:
  420.  
  421.     stuff: /various/ bits 'and' pieces "then" data 'end'
  422.             { print $item{data}  # PRINTS data
  423.                          # (EVEN EASIER THAN USING @item)
  424.  
  425.  
  426. The results of named subrules are stored in the hash under each
  427. subrule's name (including the repetition specifier, if any),
  428. whilst all other items are stored under a "named
  429. positional" key that indictates their ordinal position within their item
  430. type: __STRINGI<n>__, __PATTERNI<n>__, __DIRECTIVEI<n>__, __ACTIONI<n>__:
  431.  
  432.         stuff: /various/ bits 'and' pieces "then" data 'end' { save }
  433.                         { print $item{__PATTERN1__}, # PRINTS 'various'
  434.                                 $item{__STRING2__},  # PRINTS 'then'
  435.                                 $item{__ACTION1__},  # PRINTS RETURN
  436.                              # VALUE OF save
  437.                         }
  438.  
  439.  
  440. If you want proper I<named> access to patterns or literals, you need to turn
  441. them into separate rules:
  442.  
  443.         stuff: various bits 'and' pieces "then" data 'end'
  444.                         { print $item{various}  # PRINTS various
  445.                         }
  446.  
  447.         various: /various/
  448.  
  449.  
  450. The special entry C<$item{__RULE__}> stores the name of the current
  451. rule (i.e. the same value as C<$item[0]>.
  452.  
  453. The advantage of using C<%item>, instead of C<@items> is that it
  454. removes the need to track items positions that may change as a grammar
  455. evolves. For example, adding an interim C<E<lt>skipE<gt>> directive
  456. of action can silently ruin a trailing action, by moving an C<@item>
  457. element "down" the array one place. In contrast, the named entry
  458. of C<%item> is unaffected by such an insertion.
  459.  
  460. A limitation of the C<%item> hash is that it only records the I<last>
  461. value of a particular subrule. For example:
  462.  
  463.         range: '(' number '..' number )'
  464.                         { $return = $item{number} }
  465.  
  466. will return only the value corresponding to the I<second> match of the
  467. C<number> subrule. In other words, successive calls to a subrule
  468. overwrite the corresponding entry in C<%item>. Once again, the
  469. solution is to rename each subrule in its own rule:
  470.  
  471.         range: '(' from_num '..' to_num )'
  472.                         { $return = $item{from_num} }
  473.  
  474.         from_num: number
  475.         to_num:   number
  476.  
  477.  
  478.  
  479. =item C<@arg> and C<%arg>
  480.  
  481. The array C<@arg> and the hash C<%arg> store any arguments passed to
  482. the rule from some other rule (see L<"Subrule argument lists>). Changes
  483. to the elements of either variable do not propagate back to the calling
  484. rule (data can be passed back from a subrule via the C<$return>
  485. variable - see next item).
  486.  
  487.  
  488. =item C<$return>
  489.  
  490. If a value is assigned to C<$return> within an action, that value is
  491. returned if the production containing the action eventually matches
  492. successfully. Note that setting C<$return> I<doesn't> cause the current
  493. production to succeed. It merely tells it what to return if it I<does> succeed.
  494. Hence C<$return> is analogous to C<$$> in a I<yacc> grammar.
  495.  
  496. If C<$return> is not assigned within a production, the value of the
  497. last component of the production (namely: C<$item[$#item]>) is
  498. returned if the production succeeds.
  499.  
  500.  
  501. =item C<$commit>
  502.  
  503. The current state of commitment to the current production (see L<"Directives">
  504. below).
  505.  
  506. =item C<$skip>
  507.  
  508. The current terminal prefix (see L<"Directives"> below).
  509.  
  510. =item C<$text>
  511.  
  512. The remaining (unparsed) text. Changes to C<$text> I<do not
  513. propagate> out of unsuccessful productions, but I<do> survive
  514. successful productions. Hence it is possible to dynamically alter the
  515. text being parsed - for example, to provide a C<#include>-like facility:
  516.  
  517.         hash_include: '#include' filename
  518.                                 { $text = ::loadfile($item[2]) . $text }
  519.  
  520.         filename: '<' /[a-z0-9._-]+/i '>'  { $return = $item[2] }
  521.                 | '"' /[a-z0-9._-]+/i '"'  { $return = $item[2] }
  522.  
  523.  
  524. =item C<$thisline> and C<$prevline>
  525.  
  526. C<$thisline> stores the current line number within the current parse
  527. (starting from 1). C<$prevline> stores the line number for the last
  528. character which was already successfully parsed (this will be different from
  529. C<$thisline> at the end of each line).
  530.  
  531. For efficiency, C<$thisline> and C<$prevline> are actually tied
  532. hashes, and only recompute the required line number when the variable's
  533. value is used.
  534.  
  535. Assignment to C<$thisline> adjusts the line number calculator, so that
  536. it believes that the current line number is the value being assigned. Note
  537. that this adjustment will be reflected in all subsequent line numbers
  538. calculations.
  539.  
  540. Modifying the value of the variable C<$text> (as in the previous
  541. C<hash_include> example, for instance) will confuse the line
  542. counting mechanism. To prevent this, you should call
  543. C<Parse::RecDescent::LineCounter::resync($thisline)> I<immediately>
  544. after any assignment to the variable C<$text> (or, at least, before the
  545. next attempt to use C<$thisline>).
  546.  
  547. Note that if a production fails after assigning to or
  548. resync'ing C<$thisline>, the parser's line counter mechanism will
  549. usually be corrupted.
  550.  
  551. Also see the entry for C<@itempos>.
  552.  
  553. The line number can be set to values other than 1, by calling the start
  554. rule with a second argument. For example:
  555.  
  556.         $parser = new Parse::RecDescent ($grammar);
  557.  
  558.         $parser->input($text, 10);      # START LINE NUMBERS AT 10
  559.  
  560.  
  561. =item C<$thiscolumn> and C<$prevcolumn>
  562.  
  563. C<$thiscolumn> stores the current column number within the current line
  564. being parsed (starting from 1). C<$prevcolumn> stores the column number
  565. of the last character which was actually successfully parsed. Usually
  566. C<$prevcolumn == $thiscolumn-1>, but not at the end of lines.
  567.  
  568. For efficiency, C<$thiscolumn> and C<$prevcolumn> are
  569. actually tied hashes, and only recompute the required column number
  570. when the variable's value is used.
  571.  
  572. Assignment to C<$thiscolumn> or C<$prevcolumn> is a fatal error.
  573.  
  574. Modifying the value of the variable C<$text> (as in the previous
  575. C<hash_include> example, for instance) may confuse the column
  576. counting mechanism.
  577.  
  578. Note that C<$thiscolumn> reports the column number I<before> any
  579. whitespace that might be skipped before reading a token. Hence
  580. if you wish to know where a token started (and ended) use something like this:
  581.  
  582.         rule: token1 token2 startcol token3 endcol token4
  583.                         { print "token3: columns $item[3] to $item[5]"; }
  584.  
  585.         startcol: '' { $thiscolumn }    # NEED THE '' TO STEP PAST TOKEN SEP
  586.         endcol:      { $prevcolumn }
  587.  
  588. Also see the entry for C<@itempos>.
  589.  
  590. =item C<$thisoffset> and C<$prevoffset>
  591.  
  592. C<$thisoffset> stores the offset of the current parsing position
  593. within the complete text
  594. being parsed (starting from 0). C<$prevoffset> stores the offset
  595. of the last character which was actually successfully parsed. In all
  596. cases C<$prevoffset == $thisoffset-1>.
  597.  
  598. For efficiency, C<$thisoffset> and C<$prevoffset> are
  599. actually tied hashes, and only recompute the required offset
  600. when the variable's value is used.
  601.  
  602. Assignment to C<$thisoffset> or <$prevoffset> is a fatal error.
  603.  
  604. Modifying the value of the variable C<$text> will I<not> affect the
  605. offset counting mechanism.
  606.  
  607. Also see the entry for C<@itempos>.
  608.  
  609. =item C<@itempos>
  610.  
  611. The array C<@itempos> stores a hash reference corresponding to
  612. each element of C<@item>. The elements of the hash provide the
  613. following:
  614.  
  615.         $itempos[$n]{offset}{from}      # VALUE OF $thisoffset BEFORE $item[$n]
  616.         $itempos[$n]{offset}{to}        # VALUE OF $prevoffset AFTER $item[$n]
  617.         $itempos[$n]{line}{from}        # VALUE OF $thisline BEFORE $item[$n]
  618.         $itempos[$n]{line}{to}          # VALUE OF $prevline AFTER $item[$n]
  619.         $itempos[$n]{column}{from}      # VALUE OF $thiscolumn BEFORE $item[$n]
  620.         $itempos[$n]{column}{to}        # VALUE OF $prevcolumn AFTER $item[$n]
  621.  
  622. Note that the various C<$itempos[$n]...{from}> values record the
  623. appropriate value I<after> any token prefix has been skipped.
  624.  
  625. Hence, instead of the somewhat tedious and error-prone:
  626.  
  627.         rule: startcol token1 endcol
  628.               startcol token2 endcol
  629.               startcol token3 endcol
  630.                         { print "token1: columns $item[1]
  631.                                               to $item[3]
  632.                                  token2: columns $item[4]
  633.                                               to $item[6]
  634.                                  token3: columns $item[7]
  635.                                               to $item[9]" }
  636.  
  637.         startcol: '' { $thiscolumn }    # NEED THE '' TO STEP PAST TOKEN SEP
  638.         endcol:      { $prevcolumn }
  639.  
  640. it is possible to write:
  641.  
  642.         rule: token1 token2 token3
  643.                         { print "token1: columns $itempos[1]{column}{from}
  644.                                               to $itempos[1]{column}{to}
  645.                                  token2: columns $itempos[2]{column}{from}
  646.                                               to $itempos[2]{column}{to}
  647.                                  token3: columns $itempos[3]{column}{from}
  648.                                               to $itempos[3]{column}{to}" }
  649.  
  650. Note however that (in the current implementation) the use of C<@itempos>
  651. anywhere in a grammar implies that item positioning information is
  652. collected I<everywhere> during the parse. Depending on the grammar
  653. and the size of the text to be parsed, this may be prohibitively
  654. expensive and the explicit use of C<$thisline>, C<$thiscolumn>, etc. may
  655. be a better choice.
  656.  
  657.  
  658. =item C<$thisparser>
  659.  
  660. A reference to the S<C<Parse::RecDescent>> object through which
  661. parsing was initiated.
  662.  
  663. The value of C<$thisparser> propagates down the subrules of a parse
  664. but not back up. Hence, you can invoke subrules from another parser
  665. for the scope of the current rule as follows:
  666.  
  667.         rule: subrule1 subrule2
  668.             | { $thisparser = $::otherparser } <reject>
  669.             | subrule3 subrule4
  670.             | subrule5
  671.  
  672. The result is that the production calls "subrule1" and "subrule2" of
  673. the current parser, and the remaining productions call the named subrules
  674. from C<$::otherparser>. Note, however that "Bad Things" will happen if
  675. C<::otherparser> isn't a blessed reference and/or doesn't have methods
  676. with the same names as the required subrules!
  677.  
  678. =item C<$thisrule>
  679.  
  680. A reference to the S<C<Parse::RecDescent::Rule>> object corresponding to the
  681. rule currently being matched.
  682.  
  683. =item C<$thisprod>
  684.  
  685. A reference to the S<C<Parse::RecDescent::Production>> object
  686. corresponding to the production currently being matched.
  687.  
  688. =item C<$score> and C<$score_return>
  689.  
  690. $score stores the best production score to date, as specified by
  691. an earlier C<E<lt>score:...E<gt>> directive. $score_return stores
  692. the corresponding return value for the successful production.
  693.  
  694. See L<Scored productions>.
  695.  
  696. =back
  697.  
  698. B<Warning:> the parser relies on the information in the various C<this...>
  699. objects in some non-obvious ways. Tinkering with the other members of
  700. these objects will probably cause Bad Things to happen, unless you
  701. I<really> know what you're doing. The only exception to this advice is
  702. that the use of C<$this...-E<gt>{local}> is always safe.
  703.  
  704.  
  705. =head2 Start-up Actions
  706.  
  707. Any actions which appear I<before> the first rule definition in a
  708. grammar are treated as "start-up" actions. Each such action is
  709. stripped of its outermost brackets and then evaluated (in the parser's
  710. special namespace) just before the rules of the grammar are first
  711. compiled.
  712.  
  713. The main use of start-up actions is to declare local variables within the
  714. parser's special namespace:
  715.  
  716.         { my $lastitem = '???'; }
  717.  
  718.         list: item(s)   { $return = $lastitem }
  719.  
  720.         item: book      { $lastitem = 'book'; }
  721.               bell      { $lastitem = 'bell'; }
  722.               candle    { $lastitem = 'candle'; }
  723.  
  724. but start-up actions can be used to execute I<any> valid Perl code
  725. within a parser's special namespace.
  726.  
  727. Start-up actions can appear within a grammar extension or replacement
  728. (that is, a partial grammar installed via C<Parse::RecDescent::Extend()> or
  729. C<Parse::RecDescent::Replace()> - see L<Incremental Parsing>), and will be
  730. executed before the new grammar is installed. Note, however, that a
  731. particular start-up action is only ever executed once.
  732.  
  733.  
  734. =head2 Autoactions
  735.  
  736. It is sometimes desirable to be able to specify a default action to be
  737. taken at the end of every production (for example, in order to easily
  738. build a parse tree). If the variable C<$::RD_AUTOACTION> is defined
  739. when C<Parse::RecDescent::new()> is called, the contents of that
  740. variable are treated as a specification of an action which is to appended
  741. to each production in the corresponding grammar. So, for example, to construct
  742. a simple parse tree:
  743.  
  744.     $::RD_AUTOACTION = q { [@item] };
  745.  
  746.     parser = new Parse::RecDescent (q{
  747.         expression: and_expr '||' expression | and_expr
  748.         and_expr:   not_expr '&&' and_expr   | not_expr
  749.         not_expr:   '!' brack_expr           | brack_expr
  750.         brack_expr: '(' expression ')'       | identifier
  751.         identifier: /[a-z]+/i
  752.         });
  753.  
  754. which is equivalent to:
  755.  
  756.     parser = new Parse::RecDescent (q{
  757.         expression: and_expr '||' expression
  758.                         { [@item] }
  759.                   | and_expr
  760.                         { [@item] }
  761.  
  762.         and_expr:   not_expr '&&' and_expr
  763.                         { [@item] }
  764.                 |   not_expr
  765.                         { [@item] }
  766.  
  767.         not_expr:   '!' brack_expr
  768.                         { [@item] }
  769.                 |   brack_expr
  770.                         { [@item] }
  771.  
  772.         brack_expr: '(' expression ')'
  773.                         { [@item] }
  774.                   | identifier
  775.                         { [@item] }
  776.  
  777.         identifier: /[a-z]+/i
  778.                         { [@item] }
  779.         });
  780.  
  781. Alternatively, we could take an object-oriented approach, use different
  782. classes for each node (and also eliminating redundant intermediate nodes):
  783.  
  784.     $::RD_AUTOACTION = q
  785.       { $#item==1 ? $item[1] : new ${"$item[0]_node"} (@item[1..$#item]) };
  786.  
  787.     parser = new Parse::RecDescent (q{
  788.         expression: and_expr '||' expression | and_expr
  789.         and_expr:   not_expr '&&' and_expr   | not_expr
  790.         not_expr:   '!' brack_expr           | brack_expr
  791.         brack_expr: '(' expression ')'       | identifier
  792.         identifier: /[a-z]+/i
  793.         });
  794.  
  795. which is equivalent to:
  796.  
  797.     parser = new Parse::RecDescent (q{
  798.         expression: and_expr '||' expression
  799.                         { new expression_node (@item[1..3]) }
  800.                   | and_expr
  801.  
  802.         and_expr:   not_expr '&&' and_expr
  803.                         { new and_expr_node (@item[1..3]) }
  804.                 |   not_expr
  805.  
  806.         not_expr:   '!' brack_expr
  807.                         { new not_expr_node (@item[1..2]) }
  808.                 |   brack_expr
  809.  
  810.         brack_expr: '(' expression ')'
  811.                         { new brack_expr_node (@item[1..3]) }
  812.                   | identifier
  813.  
  814.         identifier: /[a-z]+/i
  815.                         { new identifer_node (@item[1]) }
  816.         });
  817.  
  818. Note that, if a production already ends in an action, no autoaction is appended
  819. to it. For example, in this version:
  820.  
  821.     $::RD_AUTOACTION = q
  822.       { $#item==1 ? $item[1] : new ${"$item[0]_node"} (@item[1..$#item]) };
  823.  
  824.     parser = new Parse::RecDescent (q{
  825.         expression: and_expr '&&' expression | and_expr
  826.         and_expr:   not_expr '&&' and_expr   | not_expr
  827.         not_expr:   '!' brack_expr           | brack_expr
  828.         brack_expr: '(' expression ')'       | identifier
  829.         identifier: /[a-z]+/i
  830.                         { new terminal_node($item[1]) }
  831.         });
  832.  
  833. each C<identifier> match produces a C<terminal_node> object, I<not> an
  834. C<identifier_node> object.
  835.  
  836. A level 1 warning is issued each time an "autoaction" is added to
  837. some production.
  838.  
  839.  
  840. =head2 Autotrees
  841.  
  842. A commonly needed autoaction is one that builds a parse-tree. It is moderately
  843. tricky to set up such an action (which must treat terminals differently from
  844. non-terminals), so Parse::RecDescent simplifies the process by providing the
  845. C<E<lt>autotreeE<gt>> directive.
  846.  
  847. If this directive appears at the start of grammar, it causes
  848. Parse::RecDescent to insert autoactions at the end of any rule except
  849. those which already end in an action. The action inserted depends on whether
  850. the production is an intermediate rule (two or more items), or a terminal
  851. of the grammar (i.e. a single pattern or string item).
  852.  
  853. So, for example, the following grammar:
  854.  
  855.         <autotree>
  856.  
  857.         file    : command(s)
  858.         command : get | set | vet
  859.         get     : 'get' ident ';'
  860.         set     : 'set' ident 'to' value ';'
  861.         vet     : 'check' ident 'is' value ';'
  862.         ident   : /\w+/
  863.         value   : /\d+/
  864.  
  865. is equivalent to:
  866.  
  867.         file    : command(s)                    { bless \%item, $item[0] }
  868.         command : get                           { bless \%item, $item[0] }
  869.                 | set                           { bless \%item, $item[0] }
  870.                 | vet                           { bless \%item, $item[0] }
  871.         get     : 'get' ident ';'               { bless \%item, $item[0] }
  872.         set     : 'set' ident 'to' value ';'    { bless \%item, $item[0] }
  873.         vet     : 'check' ident 'is' value ';'  { bless \%item, $item[0] }
  874.  
  875.         ident   : /\w+/          { bless {__VALUE__=>$item[1]}, $item[0] }
  876.         value   : /\d+/          { bless {__VALUE__=>$item[1]}, $item[0] }
  877.  
  878. Note that each node in the tree is blessed into a class of the same name
  879. as the rule itself. This makes it easy to build object-oriented
  880. processors for the parse-trees that the grammar produces. Note too that
  881. the last two rules produce special objects with the single attribute
  882. '__VALUE__'. This is because they consist solely of a single terminal.
  883.  
  884. This autoaction-ed grammar would then produce a parse tree in a data
  885. structure like this:
  886.  
  887.         {
  888.           file => {
  889.                     command => {
  890.                                  [ get => {
  891.                                             identifier => { __VALUE__ => 'a' },
  892.                                           },
  893.                                    set => {
  894.                                             identifier => { __VALUE__ => 'b' },
  895.                                             value      => { __VALUE__ => '7' },
  896.                                           },
  897.                                    vet => {
  898.                                             identifier => { __VALUE__ => 'b' },
  899.                                             value      => { __VALUE__ => '7' },
  900.                                           },
  901.                                   ],
  902.                                },
  903.                   }
  904.         }
  905.  
  906. (except, of course, that each nested hash would also be blessed into
  907. the appropriate class).
  908.  
  909.  
  910. =head2 Autostubbing
  911.  
  912. Normally, if a subrule appears in some production, but no rule of that
  913. name is ever defined in the grammar, the production which refers to the
  914. non-existent subrule fails immediately. This typically occurs as a
  915. result of misspellings, and is a sufficiently common occurance that a
  916. warning is generated for such situations.
  917.  
  918. However, when prototyping a grammar it is sometimes useful to be
  919. able to use subrules before a proper specification of them is
  920. really possible.  For example, a grammar might include a section like:
  921.  
  922.         function_call: identifier '(' arg(s?) ')'
  923.  
  924.         identifier: /[a-z]\w*/i
  925.  
  926. where the possible format of an argument is sufficiently complex that
  927. it is not worth specifying in full until the general function call
  928. syntax has been debugged. In this situation it is convenient to leave
  929. the real rule C<arg> undefined and just slip in a placeholder (or
  930. "stub"):
  931.  
  932.         arg: 'arg'
  933.  
  934. so that the function call syntax can be tested with dummy input such as:
  935.  
  936.         f0()
  937.         f1(arg)
  938.         f2(arg arg)
  939.         f3(arg arg arg)
  940.  
  941. et cetera.
  942.  
  943. Early in prototyping, many such "stubs" may be required, so
  944. C<Parse::RecDescent> provides a means of automating their definition.
  945. If the variable C<$::RD_AUTOSTUB> is defined when a parser is built,
  946. a subrule reference to any non-existent rule (say, C<sr>),
  947. causes a "stub" rule of the form:
  948.  
  949.         sr: 'sr'
  950.  
  951. to be automatically defined in the generated parser.
  952. A level 1 warning is issued for each such "autostubbed" rule.
  953.  
  954. Hence, with C<$::AUTOSTUB> defined, it is possible to only partially
  955. specify a grammar, and then "fake" matches of the unspecified
  956. (sub)rules by just typing in their name.
  957.  
  958.  
  959.  
  960. =head2 Look-ahead
  961.  
  962. If a subrule, token, or action is prefixed by "...", then it is
  963. treated as a "look-ahead" request. That means that the current production can
  964. (as usual) only succeed if the specified item is matched, but that the matching
  965. I<does not consume any of the text being parsed>. This is very similar to the
  966. C</(?=...)/> look-ahead construct in Perl patterns. Thus, the rule:
  967.  
  968.         inner_word: word ...word
  969.  
  970. will match whatever the subrule "word" matches, provided that match is followed
  971. by some more text which subrule "word" would also match (although this
  972. second substring is not actually consumed by "inner_word")
  973.  
  974. Likewise, a "...!" prefix, causes the following item to succeed (without
  975. consuming any text) if and only if it would normally fail. Hence, a
  976. rule such as:
  977.  
  978.         identifier: ...!keyword ...!'_' /[A-Za-z_]\w*/
  979.  
  980. matches a string of characters which satisfies the pattern
  981. C</[A-Za-z_]\w*/>, but only if the same sequence of characters would
  982. not match either subrule "keyword" or the literal token '_'.
  983.  
  984. Sequences of look-ahead prefixes accumulate, multiplying their positive and/or
  985. negative senses. Hence:
  986.  
  987.         inner_word: word ...!......!word
  988.  
  989. is exactly equivalent the the original example above (a warning is issued in
  990. cases like these, since they often indicate something left out, or
  991. misunderstood).
  992.  
  993. Note that actions can also be treated as look-aheads. In such cases,
  994. the state of the parser text (in the local variable C<$text>)
  995. I<after> the look-ahead action is guaranteed to be identical to its
  996. state I<before> the action, regardless of how it's changed I<within>
  997. the action (unless you actually undefine C<$text>, in which case you
  998. get the disaster you deserve :-).
  999.  
  1000.  
  1001. =head2 Directives
  1002.  
  1003. Directives are special pre-defined actions which may be used to alter
  1004. the behaviour of the parser. There are currently eighteen directives:
  1005. C<E<lt>commitE<gt>>,
  1006. C<E<lt>uncommitE<gt>>,
  1007. C<E<lt>rejectE<gt>>,
  1008. C<E<lt>scoreE<gt>>,
  1009. C<E<lt>autoscoreE<gt>>,
  1010. C<E<lt>skipE<gt>>,
  1011. C<E<lt>resyncE<gt>>,
  1012. C<E<lt>errorE<gt>>,
  1013. C<E<lt>rulevarE<gt>>,
  1014. C<E<lt>matchruleE<gt>>,
  1015. C<E<lt>leftopE<gt>>,
  1016. C<E<lt>rightopE<gt>>,
  1017. C<E<lt>deferE<gt>>,
  1018. C<E<lt>nocheckE<gt>>,
  1019. C<E<lt>perl_quotelikeE<gt>>,
  1020. C<E<lt>perl_codeblockE<gt>>,
  1021. C<E<lt>perl_variableE<gt>>,
  1022. and C<E<lt>tokenE<gt>>.
  1023.  
  1024. =over 4
  1025.  
  1026. =item Committing and uncommitting
  1027.  
  1028. The C<E<lt>commitE<gt>> and C<E<lt>uncommitE<gt>> directives permit the recursive
  1029. descent of the parse tree to be pruned (or "cut") for efficiency.
  1030. Within a rule, a C<E<lt>commitE<gt>> directive instructs the rule to ignore subsequent
  1031. productions if the current production fails. For example:
  1032.  
  1033.         command: 'find' <commit> filename
  1034.                | 'open' <commit> filename
  1035.                | 'move' filename filename
  1036.  
  1037. Clearly, if the leading token 'find' is matched in the first production but that
  1038. production fails for some other reason, then the remaining
  1039. productions cannot possibly match. The presence of the
  1040. C<E<lt>commitE<gt>> causes the "command" rule to fail immediately if
  1041. an invalid "find" command is found, and likewise if an invalid "open"
  1042. command is encountered.
  1043.  
  1044. It is also possible to revoke a previous commitment. For example:
  1045.  
  1046.         if_statement: 'if' <commit> condition
  1047.                                 'then' block <uncommit>
  1048.                                 'else' block
  1049.                     | 'if' <commit> condition
  1050.                                 'then' block
  1051.  
  1052. In this case, a failure to find an "else" block in the first
  1053. production shouldn't preclude trying the second production, but a
  1054. failure to find a "condition" certainly should.
  1055.  
  1056. As a special case, any production in which the I<first> item is an
  1057. C<E<lt>uncommitE<gt>> immediately revokes a preceding C<E<lt>commitE<gt>>
  1058. (even though the production would not otherwise have been tried). For
  1059. example, in the rule:
  1060.  
  1061.         request: 'explain' expression
  1062.                | 'explain' <commit> keyword
  1063.                | 'save'
  1064.                | 'quit'
  1065.                | <uncommit> term '?'
  1066.  
  1067. if the text being matched was "explain?", and the first two
  1068. productions failed, then the C<E<lt>commitE<gt>> in production two would cause
  1069. productions three and four to be skipped, but the leading
  1070. C<E<lt>uncommitE<gt>> in the production five would allow that production to
  1071. attempt a match.
  1072.  
  1073. Note in the preceding example, that the C<E<lt>commitE<gt>> was only placed
  1074. in production two. If production one had been:
  1075.  
  1076.         request: 'explain' <commit> expression
  1077.  
  1078. then production two would be (inappropriately) skipped if a leading
  1079. "explain..." was encountered.
  1080.  
  1081. Both C<E<lt>commitE<gt>> and C<E<lt>uncommitE<gt>> directives always succeed, and their value
  1082. is always 1.
  1083.  
  1084.  
  1085. =item Rejecting a production
  1086.  
  1087. The C<E<lt>rejectE<gt>> directive immediately causes the current production
  1088. to fail (it is exactly equivalent to, but more obvious than, the
  1089. action C<{undef}>). A C<E<lt>rejectE<gt>> is useful when it is desirable to get
  1090. the side effects of the actions in one production, without prejudicing a match
  1091. by some other production later in the rule. For example, to insert
  1092. tracing code into the parse:
  1093.  
  1094.         complex_rule: { print "In complex rule...\n"; } <reject>
  1095.  
  1096.         complex_rule: simple_rule '+' 'i' '*' simple_rule
  1097.                     | 'i' '*' simple_rule
  1098.                     | simple_rule
  1099.  
  1100.  
  1101. It is also possible to specify a conditional rejection, using the
  1102. form C<E<lt>reject:I<condition>E<gt>>, which only rejects if the
  1103. specified condition is true. This form of rejection is exactly
  1104. equivalent to the action C<{(I<condition>)?undef:1}E<gt>>.
  1105. For example:
  1106.  
  1107.         command: save_command
  1108.                | restore_command
  1109.                | <reject: defined $::tolerant> { exit }
  1110.                | <error: Unknown command. Ignored.>
  1111.  
  1112. A C<E<lt>rejectE<gt>> directive never succeeds (and hence has no
  1113. associated value). A conditional rejection may succeed (if its
  1114. condition is not satisfied), in which case its value is 1.
  1115.  
  1116. As an extra optimization, C<Parse::RecDescent> ignores any production
  1117. which I<begins> with an unconditional C<E<lt>rejectE<gt>> directive,
  1118. since any such production can never successfully match or have any
  1119. useful side-effects. A level 1 warning is issued in all such cases.
  1120.  
  1121. Note that productions beginning with conditional
  1122. C<E<lt>reject:...E<gt>> directives are I<never> "optimized away" in
  1123. this manner, even if they are always guaranteed to fail (for example:
  1124. C<E<lt>reject:1E<gt>>)
  1125.  
  1126. Due to the way grammars are parsed, there is a minor restriction on the
  1127. condition of a conditional C<E<lt>reject:...E<gt>>: it cannot
  1128. contain any raw '<' or '>' characters. For example:
  1129.  
  1130.         line: cmd <reject: $thiscolumn > max> data
  1131.  
  1132. results in an error when a parser is built from this grammar (since the
  1133. grammar parser has no way of knowing whether the first > is a "less than"
  1134. or the end of the C<E<lt>reject:...E<gt>>.
  1135.  
  1136. To overcome this problem, put the condition inside a do{} block:
  1137.  
  1138.         line: cmd <reject: do{$thiscolumn > max}> data
  1139.  
  1140. Note that the same problem may occur in other directives that take
  1141. arguments. The same solution will work in all cases.
  1142.  
  1143. =item Skipping between terminals
  1144.  
  1145. The C<E<lt>skipE<gt>> directive enables the terminal prefix used in
  1146. a production to be changed. For example:
  1147.  
  1148.         OneLiner: Command <skip:'[ \t]*'> Arg(s) /;/
  1149.  
  1150. causes only blanks and tabs to be skipped before terminals in the C<Arg>
  1151. subrule (and any of I<its> subrules>, and also before the final C</;/> terminal.
  1152. Once the production is complete, the previous terminal prefix is
  1153. reinstated. Note that this implies that distinct productions of a rule
  1154. must reset their terminal prefixes individually.
  1155.  
  1156. The C<E<lt>skipE<gt>> directive evaluates to the I<previous> terminal prefix,
  1157. so it's easy to reinstate a prefix later in a production:
  1158.  
  1159.         Command: <skip:","> CSV(s) <skip:$item[1]> Modifier
  1160.  
  1161. The value specified after the colon is interpolated into a pattern, so all of
  1162. the following are equivalent (though their efficiency increases down the list):
  1163.  
  1164.         <skip: "$colon|$comma">   # ASSUMING THE VARS HOLD THE OBVIOUS VALUES
  1165.  
  1166.         <skip: ':|,'>
  1167.  
  1168.         <skip: q{[:,]}>
  1169.  
  1170.         <skip: qr/[:,]/>
  1171.  
  1172. There is no way of directly setting the prefix for
  1173. an entire rule, except as follows:
  1174.  
  1175.         Rule: <skip: '[ \t]*'> Prod1
  1176.             | <skip: '[ \t]*'> Prod2a Prod2b
  1177.             | <skip: '[ \t]*'> Prod3
  1178.  
  1179. or, better:
  1180.  
  1181.         Rule: <skip: '[ \t]*'>
  1182.             (
  1183.                 Prod1
  1184.               | Prod2a Prod2b
  1185.               | Prod3
  1186.             )
  1187.  
  1188.  
  1189. B<Note: Up to release 1.51 of Parse::RecDescent, an entirely different
  1190. mechanism was used for specifying terminal prefixes. The current method
  1191. is not backwards-compatible with that early approach. The current approach
  1192. is stable and will not to change again.>
  1193.  
  1194.  
  1195. =item Resynchronization
  1196.  
  1197. The C<E<lt>resyncE<gt>> directive provides a visually distinctive
  1198. means of consuming some of the text being parsed, usually to skip an
  1199. erroneous input. In its simplest form C<E<lt>resyncE<gt>> simply
  1200. consumes text up to and including the next newline (C<"\n">)
  1201. character, succeeding only if the newline is found, in which case it
  1202. causes its surrounding rule to return zero on success.
  1203.  
  1204. In other words, a C<E<lt>resyncE<gt>> is exactly equivalent to the token
  1205. C</[^\n]*\n/> followed by the action S<C<{ $return = 0 }>> (except that
  1206. productions beginning with a C<E<lt>resyncE<gt>> are ignored when generating
  1207. error messages). A typical use might be:
  1208.  
  1209.         script : command(s)
  1210.  
  1211.         command: save_command
  1212.                | restore_command
  1213.                | <resync> # TRY NEXT LINE, IF POSSIBLE
  1214.  
  1215. It is also possible to explicitly specify a resynchronization
  1216. pattern, using the C<E<lt>resync:I<pattern>E<gt>> variant. This version
  1217. succeeds only if the specified pattern matches (and consumes) the
  1218. parsed text. In other words, C<E<lt>resync:I<pattern>E<gt>> is exactly
  1219. equivalent to the token C</I<pattern>/> (followed by a S<C<{ $return = 0 }>>
  1220. action). For example, if commands were terminated by newlines or semi-colons:
  1221.  
  1222.         command: save_command
  1223.                | restore_command
  1224.                | <resync:[^;\n]*[;\n]>
  1225.  
  1226. The value of a successfully matched C<E<lt>resyncE<gt>> directive (of either
  1227. type) is the text that it consumed. Note, however, that since the
  1228. directive also sets C<$return>, a production consisting of a lone
  1229. C<E<lt>resyncE<gt>> succeeds but returns the value zero (which a calling rule
  1230. may find useful to distinguish between "true" matches and "tolerant" matches).
  1231. Remember that returning a zero value indicates that the rule I<succeeded> (since
  1232. only an C<undef> denotes failure within C<Parse::RecDescent> parsers.
  1233.  
  1234.  
  1235. =item Error handling
  1236.  
  1237. The C<E<lt>errorE<gt>> directive provides automatic or user-defined
  1238. generation of error messages during a parse. In its simplest form
  1239. C<E<lt>errorE<gt>> prepares an error message based on
  1240. the mismatch between the last item expected and the text which cause
  1241. it to fail. For example, given the rule:
  1242.  
  1243.         McCoy: curse ',' name ', I'm a doctor, not a' a_profession '!'
  1244.              | pronoun 'dead,' name '!'
  1245.              | <error>
  1246.  
  1247. the following strings would produce the following messages:
  1248.  
  1249. =over 4
  1250.  
  1251. =item "Amen, Jim!"
  1252.  
  1253.        ERROR (line 1): Invalid McCoy: Expected curse or pronoun
  1254.                        not found
  1255.  
  1256. =item "Dammit, Jim, I'm a doctor!"
  1257.  
  1258.        ERROR (line 1): Invalid McCoy: Expected ", I'm a doctor, not a"
  1259.                        but found ", I'm a doctor!" instead
  1260.  
  1261. =item "He's dead,\n"
  1262.  
  1263.        ERROR (line 2): Invalid McCoy: Expected name not found
  1264.  
  1265. =item "He's alive!"
  1266.  
  1267.        ERROR (line 1): Invalid McCoy: Expected 'dead,' but found
  1268.                        "alive!" instead
  1269.  
  1270. =item "Dammit, Jim, I'm a doctor, not a pointy-eared Vulcan!"
  1271.  
  1272.        ERROR (line 1): Invalid McCoy: Expected a profession but found
  1273.                        "pointy-eared Vulcan!" instead
  1274.  
  1275.  
  1276. =back
  1277.  
  1278. Note that, when autogenerating error messages, all underscores in any
  1279. rule name used in a message are replaced by single spaces (for example
  1280. "a_production" becomes "a production"). Judicious choice of rule
  1281. names can therefore considerably improve the readability of automatic
  1282. error messages (as well as the maintainability of the original
  1283. grammar).
  1284.  
  1285. If the automatically generated error is not sufficient, it is possible to
  1286. provide an explicit message as part of the error directive. For example:
  1287.  
  1288.         Spock: "Fascinating ',' (name | 'Captain') '.'
  1289.              | "Highly illogical, doctor."
  1290.              | <error: He never said that!>
  1291.  
  1292. which would result in I<all> failures to parse a "Spock" subrule printing the
  1293. following message:
  1294.  
  1295.        ERROR (line <N>): Invalid Spock:  He never said that!
  1296.  
  1297. The error message is treated as a "qq{...}" string and interpolated
  1298. when the error is generated (I<not> when the directive is specified!).
  1299. Hence:
  1300.  
  1301.         <error: Mystical error near "$text">
  1302.  
  1303. would correctly insert the ambient text string which caused the error.
  1304.  
  1305. There are two other forms of error directive: C<E<lt>error?E<gt>> and
  1306. S<C<E<lt>error?: msgE<gt>>>. These behave just like C<E<lt>errorE<gt>>
  1307. and S<C<E<lt>error: msgE<gt>>> respectively, except that they are
  1308. only triggered if the rule is "committed" at the time they are
  1309. encountered. For example:
  1310.  
  1311.         Scotty: "Ya kenna change the Laws of Phusics," <commit> name
  1312.               | name <commit> ',' 'she's goanta blaw!'
  1313.               | <error?>
  1314.  
  1315. will only generate an error for a string beginning with "Ya kenna
  1316. change the Laws o' Phusics," or a valid name, but which still fails to match the
  1317. corresponding production. That is, C<$parser-E<gt>Scotty("Aye, Cap'ain")> will
  1318. fail silently (since neither production will "commit" the rule on that
  1319. input), whereas S<C<$parser-E<gt>Scotty("Mr Spock, ah jest kenna do'ut!")>>
  1320. will fail with the error message:
  1321.  
  1322.        ERROR (line 1): Invalid Scotty: expected 'she's goanta blaw!'
  1323.                        but found 'I jest kenna do'ut!' instead.
  1324.  
  1325. since in that case the second production would commit after matching
  1326. the leading name.
  1327.  
  1328. Note that to allow this behaviour, all C<E<lt>errorE<gt>> directives which are
  1329. the first item in a production automatically uncommit the rule just
  1330. long enough to allow their production to be attempted (that is, when
  1331. their production fails, the commitment is reinstated so that
  1332. subsequent productions are skipped).
  1333.  
  1334. In order to I<permanently> uncommit the rule before an error message,
  1335. it is necessary to put an explicit C<E<lt>uncommitE<gt>> before the
  1336. C<E<lt>errorE<gt>>. For example:
  1337.  
  1338.         line: 'Kirk:'  <commit> Kirk
  1339.             | 'Spock:' <commit> Spock
  1340.             | 'McCoy:' <commit> McCoy
  1341.             | <uncommit> <error?> <reject>
  1342.             | <resync>
  1343.  
  1344.  
  1345. Error messages generated by the various C<E<lt>error...E<gt>> directives
  1346. are not displayed immediately. Instead, they are "queued" in a buffer and
  1347. are only displayed once parsing ultimately fails. Moreover,
  1348. C<E<lt>error...E<gt>> directives that cause one production of a rule
  1349. to fail are automatically removed from the message queue
  1350. if another production subsequently causes the entire rule to succeed.
  1351. This means that you can put
  1352. C<E<lt>error...E<gt>> directives wherever useful diagnosis can be done,
  1353. and only those associated with actual parser failure will ever be
  1354. displayed. Also see L<"Gotchas">.
  1355.  
  1356. As a general rule, the most useful diagnostics are usually generated
  1357. either at the very lowest level within the grammar, or at the very
  1358. highest. A good rule of thumb is to identify those subrules which
  1359. consist mainly (or entirely) of terminals, and then put an
  1360. C<E<lt>error...E<gt>> directive at the end of any other rule which calls
  1361. one or more of those subrules.
  1362.  
  1363. There is one other situation in which the output of the various types of
  1364. error directive is suppressed; namely, when the rule containing them
  1365. is being parsed as part of a "look-ahead" (see L<"Look-ahead">). In this
  1366. case, the error directive will still cause the rule to fail, but will do
  1367. so silently.
  1368.  
  1369. An unconditional C<E<lt>errorE<gt>> directive always fails (and hence has no
  1370. associated value). This means that encountering such a directive
  1371. always causes the production containing it to fail. Hence an
  1372. C<E<lt>errorE<gt>> directive will inevitably be the last (useful) item of a
  1373. rule (a level 3 warning is issued if a production contains items after an unconditional
  1374. C<E<lt>errorE<gt>> directive).
  1375.  
  1376. An C<E<lt>error?E<gt>> directive will I<succeed> (that is: fail to fail :-), if
  1377. the current rule is uncommitted when the directive is encountered. In
  1378. that case the directive's associated value is zero. Hence, this type
  1379. of error directive I<can> be used before the end of a
  1380. production. For example:
  1381.  
  1382.         command: 'do' <commit> something
  1383.                | 'report' <commit> something
  1384.                | <error?: Syntax error> <error: Unknown command>
  1385.  
  1386.  
  1387. B<Warning:> The C<E<lt>error?E<gt>> directive does I<not> mean "always fail (but
  1388. do so silently unless committed)". It actually means "only fail (and report) if
  1389. committed, otherwise I<succeed>". To achieve the "fail silently if uncommitted"
  1390. semantics, it is necessary to use:
  1391.  
  1392.         rule: item <commit> item(s)
  1393.             | <error?> <reject>      # FAIL SILENTLY UNLESS COMMITTED
  1394.  
  1395. However, because people seem to expect a lone C<E<lt>error?E<gt>> directive
  1396. to work like this:
  1397.  
  1398.         rule: item <commit> item(s)
  1399.             | <error?: Error message if committed>
  1400.             | <error:  Error message if uncommitted>
  1401.  
  1402. Parse::RecDescent automatically appends a
  1403. C<E<lt>rejectE<gt>> directive if the C<E<lt>error?E<gt>> directive
  1404. is the only item in a production. A level 2 warning (see below)
  1405. is issued when this happens.
  1406.  
  1407. The level of error reporting during both parser construction and
  1408. parsing is controlled by the presence or absence of four global
  1409. variables: C<$::RD_ERRORS>, C<$::RD_WARN>, C<$::RD_HINT>, and
  1410. <$::RD_TRACE>. If C<$::RD_ERRORS> is defined (and, by default, it is)
  1411. then fatal errors are reported.
  1412.  
  1413. Whenever C<$::RD_WARN> is defined, certain non-fatal problems are also reported.
  1414. Warnings have an associated "level": 1, 2, or 3. The higher the level,
  1415. the more serious the warning. The value of the corresponding global
  1416. variable (C<$::RD_WARN>) determines the I<lowest> level of warning to
  1417. be displayed. Hence, to see I<all> warnings, set C<$::RD_WARN> to 1.
  1418. To see only the most serious warnings set C<$::RD_WARN> to 3.
  1419. By default C<$::RD_WARN> is initialized to 3, ensuring that serious but
  1420. non-fatal errors are automatically reported.
  1421.  
  1422. See F<"DIAGNOSTICS"> for a list of the varous error and warning messages
  1423. that Parse::RecDescent generates when these two variables are defined.
  1424.  
  1425. Defining any of the remaining variables (which are not defined by
  1426. default) further increases the amount of information reported.
  1427. Defining C<$::RD_HINT> causes the parser generator to offer
  1428. more detailed analyses and hints on both errors and warnings.
  1429. Note that setting C<$::RD_HINT> at any point automagically
  1430. sets C<$::RD_WARN> to 1.
  1431.  
  1432. Defining C<$::RD_TRACE> causes the parser generator and the parser to
  1433. report their progress to STDERR in excruciating detail (although, without hints
  1434. unless $::RD_HINT is separately defined). This detail
  1435. can be moderated in only one respect: if C<$::RD_TRACE> has an
  1436. integer value (I<N>) greater than 1, only the I<N> characters of
  1437. the "current parsing context" (that is, where in the input string we
  1438. are at any point in the parse) is reported at any time.
  1439.    > 
  1440. C<$::RD_TRACE> is mainly useful for debugging a grammar that isn't
  1441. behaving as you expected it to. To this end, if C<$::RD_TRACE> is
  1442. defined when a parser is built, any actual parser code which is
  1443. generated is also written to a file named "RD_TRACE" in the local
  1444. directory.
  1445.  
  1446. Note that the four variables belong to the "main" package, which
  1447. makes them easier to refer to in the code controlling the parser, and
  1448. also makes it easy to turn them into command line flags ("-RD_ERRORS",
  1449. "-RD_WARN", "-RD_HINT", "-RD_TRACE") under B<perl -s>.
  1450.  
  1451. =item Specifying local variables
  1452.  
  1453. It is occasionally convenient to specify variables which are local
  1454. to a single rule. This may be achieved by including a
  1455. C<E<lt>rulevar:...E<gt>> directive anywhere in the rule. For example:
  1456.  
  1457.         markup: <rulevar: $tag>
  1458.  
  1459.         markup: tag {($tag=$item[1]) =~ s/^<|>$//g} body[$tag]
  1460.  
  1461. The example C<E<lt>rulevar: $tagE<gt>> directive causes a "my" variable named
  1462. C<$tag> to be declared at the start of the subroutine implementing the
  1463. C<markup> rule (that is, I<before> the first production, regardless of
  1464. where in the rule it is specified).
  1465.  
  1466. Specifically, any directive of the form:
  1467. C<E<lt>rulevar:I<text>E<gt>> causes a line of the form C<my I<text>;>
  1468. to be added at the beginning of the rule subroutine, immediately after
  1469. the definitions of the following local variables:
  1470.  
  1471.         $thisparser     $commit
  1472.         $thisrule       @item
  1473.         $thisline       @arg
  1474.         $text           %arg
  1475.  
  1476. This means that the following C<E<lt>rulevarE<gt>> directives work
  1477. as expected:
  1478.  
  1479.         <rulevar: $count = 0 >
  1480.  
  1481.         <rulevar: $firstarg = $arg[0] || '' >
  1482.  
  1483.         <rulevar: $myItems = \@item >
  1484.  
  1485.         <rulevar: @context = ( $thisline, $text, @arg ) >
  1486.  
  1487.         <rulevar: ($name,$age) = $arg{"name","age"} >
  1488.  
  1489. If a variable that is also visible to subrules is required, it needs
  1490. to be C<local>'d, not C<my>'d. C<rulevar> defaults to C<my>, but if C<local>
  1491. is explicitly specified:
  1492.  
  1493.         <rulevar: local $count = 0 >
  1494.  
  1495. then a C<local>-ized variable is declared instead, and will be available
  1496. within subrules.
  1497.  
  1498. Note however that, because all such variables are "my" variables, their
  1499. values I<do not persist> between match attempts on a given rule. To
  1500. preserve values between match attempts, values can be stored within the
  1501. "local" member of the C<$thisrule> object:
  1502.  
  1503.         countedrule: { $thisrule->{"local"}{"count"}++ }
  1504.                      <reject>
  1505.                    | subrule1
  1506.                    | subrule2
  1507.                    | <reject: $thisrule->{"local"}{"count"} == 1>
  1508.                      subrule3
  1509.  
  1510.  
  1511. When matching a rule, each C<E<lt>rulevarE<gt>> directive is matched as
  1512. if it were an unconditional C<E<lt>rejectE<gt>> directive (that is, it
  1513. causes any production in which it appears to immediately fail to match).
  1514. For this reason (and to improve readability) it is usual to specify any
  1515. C<E<lt>rulevarE<gt>> directive in a separate production at the start of
  1516. the rule (this has the added advantage that it enables
  1517. C<Parse::RecDescent> to optimize away such productions, just as it does
  1518. for the C<E<lt>rejectE<gt>> directive).
  1519.  
  1520.  
  1521. =item Dynamically matched rules
  1522.  
  1523. Because regexes and double-quoted strings are interpolated, it is relatively
  1524. easy to specify productions with "context sensitive" tokens. For example:
  1525.  
  1526.         command:  keyword  body  "end $item[1]"
  1527.  
  1528. which ensures that a command block is bounded by a
  1529. "I<E<lt>keywordE<gt>>...end I<E<lt>same keywordE<gt>>" pair.
  1530.  
  1531. Building productions in which subrules are context sensitive is also possible,
  1532. via the C<E<lt>matchrule:...E<gt>> directive. This directive behaves
  1533. identically to a subrule item, except that the rule which is invoked to match
  1534. it is determined by the string specified after the colon. For example, we could
  1535. rewrite the C<command> rule like this:
  1536.  
  1537.         command:  keyword  <matchrule:body>  "end $item[1]"
  1538.  
  1539. Whatever appears after the colon in the directive is treated as an interpolated
  1540. string (that is, as if it appeared in C<qq{...}> operator) and the value of
  1541. that interpolated string is the name of the subrule to be matched.
  1542.  
  1543. Of course, just putting a constant string like C<body> in a
  1544. C<E<lt>matchrule:...E<gt>> directive is of little interest or benefit.
  1545. The power of directive is seen when we use a string that interpolates
  1546. to something interesting. For example:
  1547.  
  1548.         command:        keyword <matchrule:$item[1]_body> "end $item[1]"
  1549.  
  1550.         keyword:        'while' | 'if' | 'function'
  1551.  
  1552.         while_body:     condition block
  1553.  
  1554.         if_body:        condition block ('else' block)(?)
  1555.  
  1556.         function_body:  arglist block
  1557.  
  1558. Now the C<command> rule selects how to proceed on the basis of the keyword
  1559. that is found. It is as if C<command> were declared:
  1560.  
  1561.         command:        'while'    while_body    "end while"
  1562.                |        'if'       if_body       "end if"
  1563.                |        'function' function_body "end function"
  1564.  
  1565.  
  1566. When a C<E<lt>matchrule:...E<gt>> directive is used as a repeated
  1567. subrule, the rule name expression is "late-bound". That is, the name of
  1568. the rule to be called is re-evaluated I<each time> a match attempt is
  1569. made. Hence, the following grammar:
  1570.  
  1571.         { $::species = 'dogs' }
  1572.  
  1573.         pair:   'two' <matchrule:$::species>(s)
  1574.  
  1575.         dogs:   /dogs/ { $::species = 'cats' }
  1576.  
  1577.         cats:   /cats/
  1578.  
  1579. will match the string "two dogs cats cats" completely, whereas it will
  1580. only match the string "two dogs dogs dogs" up to the eighth letter. If
  1581. the rule name were "early bound" (that is, evaluated only the first
  1582. time the directive is encountered in a production), the reverse
  1583. behaviour would be expected.
  1584.  
  1585. Note that the C<matchrule> directive takes a string that is to be treated
  1586. as a rule name, I<not> as a rule invocation. That is,
  1587. it's like a Perl symbolic reference, not an C<eval>. Just as you can say:
  1588.  
  1589.         $subname = 'foo';
  1590.  
  1591.     # and later...
  1592.  
  1593.         &{$foo}(@args);
  1594.  
  1595. but not:
  1596.  
  1597.         $subname = 'foo(@args)';
  1598.  
  1599.     # and later...
  1600.  
  1601.         &{$foo};
  1602.  
  1603. likewise you can say:
  1604.  
  1605.     $rulename = 'foo';
  1606.  
  1607.     # and in the grammar...
  1608.  
  1609.     <matchrule:$rulename>[@args]
  1610.  
  1611. but not:
  1612.  
  1613.     $rulename = 'foo[@args]';
  1614.  
  1615.     # and in the grammar...
  1616.  
  1617.     <matchrule:$rulename>
  1618.  
  1619.  
  1620. =item Deferred actions
  1621.  
  1622. The C<E<lt>defer:...E<gt>> directive is used to specify an action to be
  1623. performed when (and only if!) the current production ultimately succeeds.
  1624.  
  1625. Whenever a C<E<lt>defer:...E<gt>> directive appears, the code it specifies
  1626. is converted to a closure (an anonymous subroutine reference) which is
  1627. queued within the active parser object. Note that,
  1628. because the deferred code is converted to a closure, the values of any
  1629. "local" variable (such as C<$text>, <@item>, etc.) are preserved
  1630. until the deferred code is actually executed.
  1631.  
  1632. If the parse ultimately succeeds
  1633. I<and> the production in which the C<E<lt>defer:...E<gt>> directive was
  1634. evaluated formed part of the successful parse, then the deferred code is
  1635. executed immediately before the parse returns. If however the production
  1636. which queued a deferred action fails, or one of the higher-level
  1637. rules which called that production fails, then the deferred action is
  1638. removed from the queue, and hence is never executed.
  1639.  
  1640. For example, given the grammar:
  1641.  
  1642.         sentence: noun trans noun
  1643.                 | noun intrans
  1644.  
  1645.         noun:     'the dog'
  1646.                         { print "$item[1]\t(noun)\n" }
  1647.             |     'the meat'
  1648.                         { print "$item[1]\t(noun)\n" }
  1649.  
  1650.         trans:    'ate'
  1651.                         { print "$item[1]\t(transitive)\n" }
  1652.  
  1653.         intrans:  'ate'
  1654.                         { print "$item[1]\t(intransitive)\n" }
  1655.                |  'barked'
  1656.                         { print "$item[1]\t(intransitive)\n" }
  1657.  
  1658. then parsing the sentence C<"the dog ate"> would produce the output:
  1659.  
  1660.         the dog  (noun)
  1661.         ate      (transitive)
  1662.         the dog  (noun)
  1663.         ate      (intransitive)
  1664.  
  1665. This is because, even though the first production of C<sentence>
  1666. ultimately fails, its initial subrules C<noun> and C<trans> do match,
  1667. and hence they execute their associated actions.
  1668. Then the second production of C<sentence> succeeds, causing the
  1669. actions of the subrules C<noun> and C<intrans> to be executed as well.
  1670.  
  1671. On the other hand, if the actions were replaced by C<E<lt>defer:...E<gt>>
  1672. directives:
  1673.  
  1674.         sentence: noun trans noun
  1675.                 | noun intrans
  1676.  
  1677.         noun:     'the dog'
  1678.                         <defer: print "$item[1]\t(noun)\n" >
  1679.             |     'the meat'
  1680.                         <defer: print "$item[1]\t(noun)\n" >
  1681.  
  1682.         trans:    'ate'
  1683.                         <defer: print "$item[1]\t(transitive)\n" >
  1684.  
  1685.         intrans:  'ate'
  1686.                         <defer: print "$item[1]\t(intransitive)\n" >
  1687.                |  'barked'
  1688.                         <defer: print "$item[1]\t(intransitive)\n" >
  1689.  
  1690. the output would be:
  1691.  
  1692.         the dog  (noun)
  1693.         ate      (intransitive)
  1694.  
  1695. since deferred actions are only executed if they were evaluated in
  1696. a production which ultimately contributes to the successful parse.
  1697.  
  1698. In this case, even though the first production of C<sentence> caused
  1699. the subrules C<noun> and C<trans> to match, that production ultimately
  1700. failed and so the deferred actions queued by those subrules were subsequently
  1701. disgarded. The second production then succeeded, causing the entire
  1702. parse to succeed, and so the deferred actions queued by the (second) match of
  1703. the C<noun> subrule and the subsequent match of C<intrans> I<are> preserved and
  1704. eventually executed.
  1705.  
  1706. Deferred actions provide a means of improving the performance of a parser,
  1707. by only executing those actions which are part of the final parse-tree
  1708. for the input data.
  1709.  
  1710. Alternatively, deferred actions can be viewed as a mechanism for building
  1711. (and executing) a
  1712. customized subroutine corresponding to the given input data, much in the
  1713. same way that autoactions (see L<"Autoactions">) can be used to build a
  1714. customized data structure for specific input.
  1715.  
  1716. Whether or not the action it specifies is ever executed,
  1717. a C<E<lt>defer:...E<gt>> directive always succeeds, returning the
  1718. number of deferred actions currently queued at that point.
  1719.  
  1720.  
  1721. =item Parsing Perl
  1722.  
  1723. Parse::RecDescent provides limited support for parsing subsets of Perl,
  1724. namely: quote-like operators, Perl variables, and complete code blocks.
  1725.  
  1726. The C<E<lt>perl_quotelikeE<gt>> directive can be used to parse any Perl
  1727. quote-like operator: C<'a string'>, C<m/a pattern/>, C<tr{ans}{lation}>,
  1728. etc.  It does this by calling Text::Balanced::quotelike().
  1729.  
  1730. If a quote-like operator is found, a reference to an array of eight elements
  1731. is returned. Those elements are identical to the last eight elements returned
  1732. by Text::Balanced::extract_quotelike() in an array context, namely:
  1733.  
  1734. =over 4
  1735.  
  1736. =item [0]
  1737.  
  1738. the name of the quotelike operator -- 'q', 'qq', 'm', 's', 'tr' -- if the
  1739. operator was named; otherwise C<undef>,
  1740.  
  1741. =item [1]
  1742.  
  1743. the left delimiter of the first block of the operation,
  1744.  
  1745. =item [2]
  1746.  
  1747. the text of the first block of the operation
  1748. (that is, the contents of
  1749. a quote, the regex of a match, or substitution or the target list of a
  1750. translation),
  1751.  
  1752. =item [3]
  1753.  
  1754. the right delimiter of the first block of the operation,
  1755.  
  1756. =item [4]
  1757.  
  1758. the left delimiter of the second block of the operation if there is one
  1759. (that is, if it is a C<s>, C<tr>, or C<y>); otherwise C<undef>,
  1760.  
  1761. =item [5]
  1762.  
  1763. the text of the second block of the operation if there is one
  1764. (that is, the replacement of a substitution or the translation list
  1765. of a translation); otherwise C<undef>,
  1766.  
  1767. =item [6]
  1768.  
  1769. the right delimiter of the second block of the operation (if any);
  1770. otherwise C<undef>,
  1771.  
  1772. =item [7]
  1773.  
  1774. the trailing modifiers on the operation (if any); otherwise C<undef>.
  1775.  
  1776. =back
  1777.  
  1778. If a quote-like expression is not found, the directive fails with the usual
  1779. C<undef> value.
  1780.  
  1781. The C<E<lt>perl_variableE<gt>> directive can be used to parse any Perl
  1782. variable: $scalar, @array, %hash, $ref->{field}[$index], etc.
  1783. It does this by calling Text::Balanced::extract_variable().
  1784.  
  1785. If the directive matches text representing a valid Perl variable
  1786. specification, it returns that text. Otherwise it fails with the usual
  1787. C<undef> value.
  1788.  
  1789. The C<E<lt>perl_codeblockE<gt>> directive can be used to parse curly-brace-delimited block of Perl code, such as: { $a = 1; f() =~ m/pat/; }.
  1790. It does this by calling Text::Balanced::extract_codeblock().
  1791.  
  1792. If the directive matches text representing a valid Perl code block,
  1793. it returns that text. Otherwise it fails with the usual C<undef> value.
  1794.  
  1795. You can also tell it what kind of brackets to use as the outermost
  1796. delimiters. For example:
  1797.  
  1798.     arglist: <perl_codeblock ()>
  1799.  
  1800. causes an arglist to match a perl code block whose outermost delimiters
  1801. are C<(...)> (rather than the default C<{...}>).
  1802.  
  1803.  
  1804. =item Constructing tokens
  1805.  
  1806. Eventually, Parse::RecDescent will be able to parse tokenized input, as
  1807. well as ordinary strings. In preparation for this joyous day, the
  1808. C<E<lt>token:...E<gt>> directive has been provided.
  1809. This directive creates a token which will be suitable for
  1810. input to a Parse::RecDescent parser (when it eventually supports
  1811. tokenized input).
  1812.  
  1813. The text of the token is the value of the
  1814. immediately preceding item in the production. A
  1815. C<E<lt>token:...E<gt>> directive always succeeds with a return
  1816. value which is the hash reference that is the new token. It also
  1817. sets the return value for the production to that hash ref.
  1818.  
  1819. The C<E<lt>token:...E<gt>> directive makes it easy to build
  1820. a Parse::RecDescent-compatible lexer in Parse::RecDescent:
  1821.  
  1822.         my $lexer = new Parse::RecDescent q
  1823.         {
  1824.                 lex:    token(s)
  1825.  
  1826.                 token:  /a\b/                      <token:INDEF>
  1827.                      |  /the\b/                    <token:DEF>
  1828.                      |  /fly\b/                    <token:NOUN,VERB>
  1829.                      |  /[a-z]+/i { lc $item[1] }  <token:ALPHA>
  1830.                      |  <error: Unknown token>
  1831.  
  1832.         };
  1833.  
  1834. which will eventually be able to be used with a regular Parse::RecDescent
  1835. grammar:
  1836.  
  1837.         my $parser = new Parse::RecDescent q
  1838.         {
  1839.                 startrule: subrule1 subrule 2
  1840.  
  1841.                 # ETC...
  1842.         };
  1843.  
  1844. either with a pre-lexing phase:
  1845.  
  1846.         $parser->startrule( $lexer->lex($data) );
  1847.  
  1848. or with a lex-on-demand approach:
  1849.  
  1850.         $parser->startrule( sub{$lexer->token(\$data)} );
  1851.  
  1852. But at present, only the C<E<lt>token:...E<gt>> directive is
  1853. actually implemented. The rest is vapourware.
  1854.  
  1855. =item Specifying operations
  1856.  
  1857. One of the commonest requirements when building a parser is to specify
  1858. binary operators. Unfortunately, in a normal grammar, the rules for
  1859. such things are awkward:
  1860.  
  1861.         disjunction:    conjunction ('or' conjunction)(s?)
  1862.                                 { $return = [ $item[1], @{$item[2]} ] }
  1863.  
  1864.         conjunction:    atom ('and' atom)(s?)
  1865.                                 { $return = [ $item[1], @{$item[2]} ] }
  1866.  
  1867. or inefficient:
  1868.  
  1869.         disjunction:    conjunction 'or' disjunction
  1870.                                 { $return = [ $item[1], @{$item[2]} ] }
  1871.                    |    conjunction
  1872.                                 { $return = [ $item[1] ] }
  1873.  
  1874.         conjunction:    atom 'and' conjunction
  1875.                                 { $return = [ $item[1], @{$item[2]} ] }
  1876.                    |    atom
  1877.                                 { $return = [ $item[1] ] }
  1878.  
  1879. and either way is ugly and hard to get right.
  1880.  
  1881. The C<E<lt>leftop:...E<gt>> and C<E<lt>rightop:...E<gt>> directives provide an
  1882. easier way of specifying such operations. Using C<E<lt>leftop:...E<gt>> the
  1883. above examples become:
  1884.  
  1885.         disjunction:    <leftop: conjunction 'or' conjunction>
  1886.         conjunction:    <leftop: atom 'and' atom>
  1887.  
  1888. The C<E<lt>leftop:...E<gt>> directive specifies a left-associative binary operator.
  1889. It is specified around three other grammar elements
  1890. (typically subrules or terminals), which match the left operand,
  1891. the operator itself, and the right operand respectively.
  1892.  
  1893. A C<E<lt>leftop:...E<gt>> directive such as:
  1894.  
  1895.         disjunction:    <leftop: conjunction 'or' conjunction>
  1896.  
  1897. is converted to the following:
  1898.  
  1899.         disjunction:    ( conjunction ('or' conjunction)(s?)
  1900.                                 { $return = [ $item[1], @{$item[2]} ] } )
  1901.  
  1902. In other words, a C<E<lt>leftop:...E<gt>> directive matches the left operand followed by zero
  1903. or more repetitions of both the operator and the right operand. It then
  1904. flattens the matched items into an anonymous array which becomes the
  1905. (single) value of the entire C<E<lt>leftop:...E<gt>> directive.
  1906.  
  1907. For example, an C<E<lt>leftop:...E<gt>> directive such as:
  1908.  
  1909.         output:  <leftop: ident '<<' expr >
  1910.  
  1911. when given a string such as:
  1912.  
  1913.         cout << var << "str" << 3
  1914.  
  1915. would match, and C<$item[1]> would be set to:
  1916.  
  1917.         [ 'cout', 'var', '"str"', '3' ]
  1918.  
  1919. In other words:
  1920.  
  1921.         output:  <leftop: ident '<<' expr >
  1922.  
  1923. is equivalent to a left-associative operator:
  1924.  
  1925.         output:  ident                                  { $return = [$item[1]]       }
  1926.               |  ident '<<' expr                        { $return = [@item[1,3]]     }
  1927.               |  ident '<<' expr '<<' expr              { $return = [@item[1,3,5]]   }
  1928.               |  ident '<<' expr '<<' expr '<<' expr    { $return = [@item[1,3,5,7]] }
  1929.               #  ...etc...
  1930.  
  1931.  
  1932. Similarly, the C<E<lt>rightop:...E<gt>> directive takes a left operand, an operator, and a right operand:
  1933.  
  1934.         assign:  <rightop: var '=' expr >
  1935.  
  1936. and converts them to:
  1937.  
  1938.         assign:  ( (var '=' {$return=$item[1]})(s?) expr
  1939.                                 { $return = [ @{$item[1]}, $item[2] ] } )
  1940.  
  1941. which is equivalent to a right-associative operator:
  1942.  
  1943.         assign:  var                            { $return = [$item[1]]       }
  1944.               |  var '=' expr                   { $return = [@item[1,3]]     }
  1945.               |  var '=' var '=' expr           { $return = [@item[1,3,5]]   }
  1946.               |  var '=' var '=' var '=' expr   { $return = [@item[1,3,5,7]] }
  1947.               #  ...etc...
  1948.  
  1949.  
  1950. Note that for both the C<E<lt>leftop:...E<gt>> and C<E<lt>rightop:...E<gt>> directives, the directive does not normally
  1951. return the operator itself, just a list of the operands involved. This is
  1952. particularly handy for specifying lists:
  1953.  
  1954.         list: '(' <leftop: list_item ',' list_item> ')'
  1955.                         { $return = $item[2] }
  1956.  
  1957. There is, however, a problem: sometimes the operator is itself significant.
  1958. For example, in a Perl list a comma and a C<=E<gt>> are both
  1959. valid separators, but the C<=E<gt>> has additional stringification semantics.
  1960. Hence it's important to know which was used in each case.
  1961.  
  1962. To solve this problem the
  1963. C<E<lt>leftop:...E<gt>> and C<E<lt>rightop:...E<gt>> directives
  1964. I<do> return the operator(s) as well, under two circumstances.
  1965. The first case is where the operator is specified as a subrule. In that instance,
  1966. whatever the operator matches is returned (on the assumption that if the operator
  1967. is important enough to have its own subrule, then it's important enough to return).
  1968.  
  1969. The second case is where the operator is specified as a regular
  1970. expression. In that case, if the first bracketed subpattern of the
  1971. regular expression matches, that matching value is returned (this is analogous to
  1972. the behaviour of the Perl C<split> function, except that only the first subpattern
  1973. is returned).
  1974.  
  1975. In other words, given the input:
  1976.  
  1977.         ( a=>1, b=>2 )
  1978.  
  1979. the specifications:
  1980.  
  1981.         list:      '('  <leftop: list_item separator list_item>  ')'
  1982.  
  1983.         separator: ',' | '=>'
  1984.  
  1985. or:
  1986.  
  1987.         list:      '('  <leftop: list_item /(,|=>)/ list_item>  ')'
  1988.  
  1989. cause the list separators to be interleaved with the operands in the
  1990. anonymous array in C<$item[2]>:
  1991.  
  1992.         [ 'a', '=>', '1', ',', 'b', '=>', '2' ]
  1993.  
  1994.  
  1995. But the following version:
  1996.  
  1997.         list:      '('  <leftop: list_item /,|=>/ list_item>  ')'
  1998.  
  1999. returns only the operators:
  2000.  
  2001.         [ 'a', '1', 'b', '2' ]
  2002.  
  2003. Of course, none of the above specifications handle the case of an empty
  2004. list, since the C<E<lt>leftop:...E<gt>> and C<E<lt>rightop:...E<gt>> directives
  2005. require at least a single right or left operand to match. To specify
  2006. that the operator can match "trivially",
  2007. it's necessary to add a C<(?)> qualifier to the directive:
  2008.  
  2009.         list:      '('  <leftop: list_item /(,|=>)/ list_item>(?)  ')'
  2010.  
  2011. Note that in almost all the above examples, the first and third arguments
  2012. of the C<<leftop:...E<gt>> directive were the same subrule. That is because
  2013. C<<leftop:...E<gt>>'s are frequently used to specify "separated" lists of the
  2014. same type of item. To make such lists easier to specify, the following
  2015. syntax:
  2016.  
  2017.         list:   element(s /,/)
  2018.  
  2019. is exactly equivalent to:
  2020.  
  2021.         list:   <leftop: element /,/ element>
  2022.  
  2023. Note that the separator must be specified as a raw pattern (i.e.
  2024. not a string or subrule).
  2025.  
  2026.  
  2027. =item Scored productions
  2028.  
  2029. By default, Parse::RecDescent grammar rules always accept the first
  2030. production that matches the input. But if two or more productions may
  2031. potentially match the same input, choosing the first that does so may
  2032. not be optimal.
  2033.  
  2034. For example, if you were parsing the sentence "time flies like an arrow",
  2035. you might use a rule like this:
  2036.  
  2037.         sentence: verb noun preposition article noun { [@item] }
  2038.                 | adjective noun verb article noun   { [@item] }
  2039.                 | noun verb preposition article noun { [@item] }
  2040.  
  2041. Each of these productions matches the sentence, but the third one
  2042. is the most likely interpretation. However, if the sentence had been
  2043. "fruit flies like a banana", then the second production is probably
  2044. the right match.
  2045.  
  2046. To cater for such situtations, the C<E<lt>score:...E<gt>> can be used.
  2047. The directive is equivalent to an unconditional C<E<lt>rejectE<gt>>,
  2048. except that it allows you to specify a "score" for the current
  2049. production. If that score is numerically greater than the best
  2050. score of any preceding production, the current production is cached for later
  2051. consideration. If no later production matches, then the cached
  2052. production is treated as having matched, and the value of the
  2053. item immediately before its C<E<lt>score:...E<gt>> directive is returned as the
  2054. result.
  2055.  
  2056. In other words, by putting a C<E<lt>score:...E<gt>> directive at the end of
  2057. each production, you can select which production matches using
  2058. criteria other than specification order. For example:
  2059.  
  2060.         sentence: verb noun preposition article noun { [@item] } <score: sensible(@item)>
  2061.                 | adjective noun verb article noun   { [@item] } <score: sensible(@item)>
  2062.                 | noun verb preposition article noun { [@item] } <score: sensible(@item)>
  2063.  
  2064. Now, when each production reaches its respective C<E<lt>score:...E<gt>>
  2065. directive, the subroutine C<sensible> will be called to evaluate the
  2066. matched items (somehow). Once all productions have been tried, the
  2067. one which C<sensible> scored most highly will be the one that is
  2068. accepted as a match for the rule.
  2069.  
  2070. The variable $score always holds the current best score of any production,
  2071. and the variable $score_return holds the corresponding return value.
  2072.  
  2073. As another example, the following grammar matches lines that may be
  2074. separated by commas, colons, or semi-colons. This can be tricky if
  2075. a colon-separated line also contains commas, or vice versa. The grammar
  2076. resolves the ambiguity by selecting the rule that results in the
  2077. fewest fields:
  2078.  
  2079.         line: seplist[sep=>',']  <score: -@{$item[1]}>
  2080.             | seplist[sep=>':']  <score: -@{$item[1]}>
  2081.             | seplist[sep=>" "]  <score: -@{$item[1]}>
  2082.  
  2083.         seplist: <skip:""> <leftop: /[^$arg{sep}]*/ "$arg{sep}" /[^$arg{sep}]*/>
  2084.  
  2085. Note the use of negation within the C<E<lt>score:...E<gt>> directive
  2086. to ensure that the seplist with the most items gets the lowest score.
  2087.  
  2088. As the above examples indicate, it is often the case that all productions
  2089. in a rule use exactly the same C<E<lt>score:...E<gt>> directive. It is
  2090. tedious to have to repeat this identical directive in every production, so
  2091. Parse::RecDescent also provides the C<E<lt>autoscore:...E<gt>> directive.
  2092.  
  2093. If an C<E<lt>autoscore:...E<gt>> directive appears in any
  2094. production of a rule, the code it specifies is used as the scoring
  2095. code for every production of that rule, except productions that already
  2096. end with an explicit C<E<lt>score:...E<gt>> directive. Thus the rules above could
  2097. be rewritten:
  2098.  
  2099.         line: <autoscore: -@{$item[1]}>
  2100.         line: seplist[sep=>',']
  2101.             | seplist[sep=>':']
  2102.             | seplist[sep=>" "]
  2103.  
  2104.  
  2105.         sentence: <autoscore: sensible(@item)>
  2106.                 | verb noun preposition article noun { [@item] }
  2107.                 | adjective noun verb article noun   { [@item] }
  2108.                 | noun verb preposition article noun { [@item] }
  2109.  
  2110. Note that the C<E<lt>autoscore:...E<gt>> directive itself acts as an
  2111. unconditional C<E<lt>rejectE<gt>>, and (like the C<E<lt>rulevar:...E<gt>>
  2112. directive) is pruned at compile-time wherever possible.
  2113.  
  2114.  
  2115. =item Dispensing with grammar checks
  2116.  
  2117. During the compilation phase of parser construction, Parse::RecDescent performs
  2118. a small number of checks on the grammar it's given. Specifically it checks that
  2119. the grammar is not left-recursive, that there are no "insatiable" constructs of
  2120. the form:
  2121.  
  2122.         rule: subrule(s) subrule
  2123.  
  2124. and that there are no rules missing (i.e. referred to, but never defined).
  2125.  
  2126. These checks are important during development, but can slow down parser
  2127. construction in stable code. So Parse::RecDescent provides the
  2128. E<lt>nocheckE<gt> directive to turn them off. The directive can only appear
  2129. before the first rule definition, and switches off checking throughout the rest
  2130. of the current grammar.
  2131.  
  2132. Typically, this directive would be added when a parser has been thoroughly
  2133. tested and is ready for release.
  2134.  
  2135. =back
  2136.  
  2137.  
  2138. =head2 Subrule argument lists
  2139.  
  2140. It is occasionally useful to pass data to a subrule which is being invoked. For
  2141. example, consider the following grammar fragment:
  2142.  
  2143.         classdecl: keyword decl
  2144.  
  2145.         keyword:   'struct' | 'class';
  2146.  
  2147.         decl:      # WHATEVER
  2148.  
  2149. The C<decl> rule might wish to know which of the two keywords was used
  2150. (since it may affect some aspect of the way the subsequent declaration
  2151. is interpreted). C<Parse::RecDescent> allows the grammar designer to
  2152. pass data into a rule, by placing that data in an I<argument list>
  2153. (that is, in square brackets) immediately after any subrule item in a
  2154. production. Hence, we could pass the keyword to C<decl> as follows:
  2155.  
  2156.         classdecl: keyword decl[ $item[1] ]
  2157.  
  2158.         keyword:   'struct' | 'class';
  2159.  
  2160.         decl:      # WHATEVER
  2161.  
  2162. The argument list can consist of any number (including zero!) of comma-separated
  2163. Perl expressions. In other words, it looks exactly like a Perl anonymous
  2164. array reference. For example, we could pass the keyword, the name of the
  2165. surrounding rule, and the literal 'keyword' to C<decl> like so:
  2166.  
  2167.         classdecl: keyword decl[$item[1],$item[0],'keyword']
  2168.  
  2169.         keyword:   'struct' | 'class';
  2170.  
  2171.         decl:      # WHATEVER
  2172.  
  2173. Within the rule to which the data is passed (C<decl> in the above examples)
  2174. that data is available as the elements of a local variable C<@arg>. Hence
  2175. C<decl> might report its intentions as follows:
  2176.  
  2177.         classdecl: keyword decl[$item[1],$item[0],'keyword']
  2178.  
  2179.         keyword:   'struct' | 'class';
  2180.  
  2181.         decl:      { print "Declaring $arg[0] (a $arg[2])\n";
  2182.                      print "(this rule called by $arg[1])" }
  2183.  
  2184. Subrule argument lists can also be interpreted as hashes, simply by using
  2185. the local variable C<%arg> instead of C<@arg>. Hence we could rewrite the
  2186. previous example:
  2187.  
  2188.         classdecl: keyword decl[keyword => $item[1],
  2189.                                 caller  => $item[0],
  2190.                                 type    => 'keyword']
  2191.  
  2192.         keyword:   'struct' | 'class';
  2193.  
  2194.         decl:      { print "Declaring $arg{keyword} (a $arg{type})\n";
  2195.                      print "(this rule called by $arg{caller})" }
  2196.  
  2197. Both C<@arg> and C<%arg> are always available, so the grammar designer may
  2198. choose whichever convention (or combination of conventions) suits best.
  2199.  
  2200. Subrule argument lists are also useful for creating "rule templates"
  2201. (especially when used in conjunction with the C<E<lt>matchrule:...E<gt>>
  2202. directive). For example, the subrule:
  2203.  
  2204.         list:     <matchrule:$arg{rule}> /$arg{sep}/ list[%arg]
  2205.                         { $return = [ $item[1], @{$item[3]} ] }
  2206.             |     <matchrule:$arg{rule}>
  2207.                         { $return = [ $item[1]] }
  2208.  
  2209. is a handy template for the common problem of matching a separated list.
  2210. For example:
  2211.  
  2212.         function: 'func' name '(' list[rule=>'param',sep=>';'] ')'
  2213.  
  2214.         param:    list[rule=>'name',sep=>','] ':' typename
  2215.  
  2216.         name:     /\w+/
  2217.  
  2218.         typename: name
  2219.  
  2220.  
  2221. When a subrule argument list is used with a repeated subrule, the argument list
  2222. goes I<before> the repetition specifier:
  2223.  
  2224.         list:   /some|many/ thing[ $item[1] ](s)
  2225.  
  2226. The argument list is "late bound". That is, it is re-evaluated for every
  2227. repetition of the repeated subrule.
  2228. This means that each repeated attempt to match the subrule may be
  2229. passed a completely different set of arguments if the value of the
  2230. expression in the argument list changes between attempts. So, for
  2231. example, the grammar:
  2232.  
  2233.         { $::species = 'dogs' }
  2234.  
  2235.         pair:   'two' animal[$::species](s)
  2236.  
  2237.         animal: /$arg[0]/ { $::species = 'cats' }
  2238.  
  2239. will match the string "two dogs cats cats" completely, whereas
  2240. it will only match the string "two dogs dogs dogs" up to the
  2241. eighth letter. If the value of the argument list were "early bound"
  2242. (that is, evaluated only the first time a repeated subrule match is
  2243. attempted), one would expect the matching behaviours to be reversed.
  2244.  
  2245. Of course, it is possible to effectively "early bind" such argument lists
  2246. by passing them a value which does not change on each repetition. For example:
  2247.  
  2248.         { $::species = 'dogs' }
  2249.  
  2250.         pair:   'two' { $::species } animal[$item[2]](s)
  2251.  
  2252.         animal: /$arg[0]/ { $::species = 'cats' }
  2253.  
  2254.  
  2255. Arguments can also be passed to the start rule, simply by appending them
  2256. to the argument list with which the start rule is called (I<after> the
  2257. "line number" parameter). For example, given:
  2258.  
  2259.         $parser = new Parse::RecDescent ( $grammar );
  2260.  
  2261.         $parser->data($text, 1, "str", 2, \@arr);
  2262.  
  2263.         #             ^^^^^  ^  ^^^^^^^^^^^^^^^
  2264.         #               |    |         |
  2265.         # TEXT TO BE PARSED  |         |
  2266.         # STARTING LINE NUMBER         |
  2267.         # ELEMENTS OF @arg WHICH IS PASSED TO RULE data
  2268.  
  2269. then within the productions of the rule C<data>, the array C<@arg> will contain
  2270. C<("str", 2, \@arr)>.
  2271.  
  2272.  
  2273. =head2 Alternations
  2274.  
  2275. Alternations are implicit (unnamed) rules defined as part of a production. An
  2276. alternation is defined as a series of '|'-separated productions inside a
  2277. pair of round brackets. For example:
  2278.  
  2279.         character: 'the' ( good | bad | ugly ) /dude/
  2280.  
  2281. Every alternation implicitly defines a new subrule, whose
  2282. automatically-generated name indicates its origin:
  2283. "_alternation_<I>_of_production_<P>_of_rule<R>" for the appropriate
  2284. values of <I>, <P>, and <R>. A call to this implicit subrule is then
  2285. inserted in place of the brackets. Hence the above example is merely a
  2286. convenient short-hand for:
  2287.  
  2288.         character: 'the'
  2289.                    _alternation_1_of_production_1_of_rule_character
  2290.                    /dude/
  2291.  
  2292.         _alternation_1_of_production_1_of_rule_character:
  2293.                    good | bad | ugly
  2294.  
  2295. Since alternations are parsed by recursively calling the parser generator,
  2296. any type(s) of item can appear in an alternation. For example:
  2297.  
  2298.         character: 'the' ( 'high' "plains"      # Silent, with poncho
  2299.                          | /no[- ]name/         # Silent, no poncho
  2300.                          | vengeance_seeking    # Poncho-optional
  2301.                          | <error>
  2302.                          ) drifter
  2303.  
  2304. In this case, if an error occurred, the automatically generated
  2305. message would be:
  2306.  
  2307.         ERROR (line <N>): Invalid implicit subrule: Expected
  2308.                           'high' or /no[- ]name/ or generic,
  2309.                           but found "pacifist" instead
  2310.  
  2311. Since every alternation actually has a name, it's even possible
  2312. to extend or replace them:
  2313.  
  2314.         parser->Replace(
  2315.                 "_alternation_1_of_production_1_of_rule_character:
  2316.                         'generic Eastwood'"
  2317.                         );
  2318.  
  2319. More importantly, since alternations are a form of subrule, they can be given
  2320. repetition specifiers:
  2321.  
  2322.         character: 'the' ( good | bad | ugly )(?) /dude/
  2323.  
  2324.  
  2325. =head2 Incremental Parsing
  2326.  
  2327. C<Parse::RecDescent> provides two methods - C<Extend> and C<Replace> - which
  2328. can be used to alter the grammar matched by a parser. Both methods
  2329. take the same argument as C<Parse::RecDescent::new>, namely a
  2330. grammar specification string
  2331.  
  2332. C<Parse::RecDescent::Extend> interprets the grammar specification and adds any
  2333. productions it finds to the end of the rules for which they are specified. For
  2334. example:
  2335.  
  2336.         $add = "name: 'Jimmy-Bob' | 'Bobby-Jim'\ndesc: colour /necks?/";
  2337.         parser->Extend($add);
  2338.  
  2339. adds two productions to the rule "name" (creating it if necessary) and one
  2340. production to the rule "desc".
  2341.  
  2342. C<Parse::RecDescent::Replace> is identical, except that it first resets are
  2343. rule specified in the additional grammar, removing any existing productions.
  2344. Hence after:
  2345.  
  2346.         $add = "name: 'Jimmy-Bob' | 'Bobby-Jim'\ndesc: colour /necks?/";
  2347.         parser->Replace($add);
  2348.  
  2349. are are I<only> valid "name"s and the one possible description.
  2350.  
  2351. A more interesting use of the C<Extend> and C<Replace> methods is to call them
  2352. inside the action of an executing parser. For example:
  2353.  
  2354.         typedef: 'typedef' type_name identifier ';'
  2355.                        { $thisparser->Extend("type_name: '$item[3]'") }
  2356.                | <error>
  2357.  
  2358.         identifier: ...!type_name /[A-Za-z_]w*/
  2359.  
  2360. which automatically prevents type names from being typedef'd, or:
  2361.  
  2362.         command: 'map' key_name 'to' abort_key
  2363.                        { $thisparser->Replace("abort_key: '$item[2]'") }
  2364.                | 'map' key_name 'to' key_name
  2365.                        { map_key($item[2],$item[4]) }
  2366.                | abort_key
  2367.                        { exit if confirm("abort?") }
  2368.  
  2369.         abort_key: 'q'
  2370.  
  2371.         key_name: ...!abort_key /[A-Za-z]/
  2372.  
  2373. which allows the user to change the abort key binding, but not to unbind it.
  2374.  
  2375. The careful use of such constructs makes it possible to reconfigure a
  2376. a running parser, eliminating the need for semantic feedback by
  2377. providing syntactic feedback instead. However, as currently implemented,
  2378. C<Replace()> and C<Extend()> have to regenerate and re-C<eval> the
  2379. entire parser whenever they are called. This makes them quite slow for
  2380. large grammars.
  2381.  
  2382. In such cases, the judicious use of an interpolated regex is likely to
  2383. be far more efficient:
  2384.  
  2385.         typedef: 'typedef' type_name/ identifier ';'
  2386.                        { $thisparser->{local}{type_name} .= "|$item[3]" }
  2387.                | <error>
  2388.  
  2389.         identifier: ...!type_name /[A-Za-z_]w*/
  2390.  
  2391.         type_name: /$thisparser->{local}{type_name}/
  2392.  
  2393.  
  2394. =head2 Precompiling parsers
  2395.  
  2396. Normally Parse::RecDescent builds a parser from a grammar at run-time.
  2397. That approach simplifies the design and implementation of parsing code,
  2398. but has the disadvantage that it slows the parsing process down - you
  2399. have to wait for Parse::RecDescent to build the parser every time the
  2400. program runs. Long or complex grammars can be particularly slow to
  2401. build, leading to unacceptable delays at start-up.
  2402.  
  2403. To overcome this, the module provides a way of "pre-building" a parser
  2404. object and saving it in a separate module. That module can then be used
  2405. to create clones of the original parser.
  2406.  
  2407. A grammar may be precompiled using the C<Precompile> class method.
  2408. For example, to precompile a grammar stored in the scalar $grammar,
  2409. and produce a class named PreGrammar in a module file named PreGrammar.pm,
  2410. you could use:
  2411.  
  2412.         use Parse::RecDescent;
  2413.  
  2414.         Parse::RecDescent->Precompile($grammar, "PreGrammar");
  2415.  
  2416. The first argument is the grammar string, the second is the name of the class
  2417. to be built. The name of the module file is generated automatically by
  2418. appending ".pm" to the last element of the class name. Thus
  2419.  
  2420.         Parse::RecDescent->Precompile($grammar, "My::New::Parser");
  2421.  
  2422. would produce a module file named Parser.pm.
  2423.  
  2424. It is somewhat tedious to have to write a small Perl program just to
  2425. generate a precompiled grammar class, so Parse::RecDescent has some special
  2426. magic that allows you to do the job directly from the command-line.
  2427.  
  2428. If your grammar is specified in a file named F<grammar>, you can generate
  2429. a class named Yet::Another::Grammar like so:
  2430.  
  2431.         > perl -MParse::RecDescent - grammar Yet::Another::Grammar
  2432.  
  2433. This would produce a file named F<Grammar.pm> containing the full
  2434. definition of a class called Yet::Another::Grammar. Of course, to use
  2435. that class, you would need to put the F<Grammar.pm> file in a
  2436. directory named F<Yet/Another>, somewhere in your Perl include path.
  2437.  
  2438. Having created the new class, it's very easy to use it to build
  2439. a parser. You simply C<use> the new module, and then call its
  2440. C<new> method to create a parser object. For example:
  2441.  
  2442.         use Yet::Another::Grammar;
  2443.         my $parser = Yet::Another::Grammar->new();
  2444.  
  2445. The effect of these two lines is exactly the same as:
  2446.  
  2447.         use Parse::RecDescent;
  2448.  
  2449.         open GRAMMAR_FILE, "grammar" or die;
  2450.         local $/;
  2451.         my $grammar = <GRAMMAR_FILE>;
  2452.  
  2453.         my $parser = Parse::RecDescent->new($grammar);
  2454.  
  2455. only considerably faster.
  2456.  
  2457. Note however that the parsers produced by either approach are exactly
  2458. the same, so whilst precompilation has an effect on I<set-up> speed,
  2459. it has no effect on I<parsing> speed. RecDescent 2.0 will address that
  2460. problem.
  2461.  
  2462.  
  2463. =head2 A Metagrammar for C<Parse::RecDescent>
  2464.  
  2465. The following is a specification of grammar format accepted by
  2466. C<Parse::RecDescent::new> (specified in the C<Parse::RecDescent> grammar format!):
  2467.  
  2468.  grammar    : components(s)
  2469.  
  2470.  component  : rule | comment
  2471.  
  2472.  rule       : "\n" identifier ":" production(s?)
  2473.  
  2474.  production : items(s)
  2475.  
  2476.  item       : lookahead(?) simpleitem
  2477.             | directive
  2478.             | comment
  2479.  
  2480.  lookahead  : '...' | '...!'                   # +'ve or -'ve lookahead
  2481.  
  2482.  simpleitem : subrule args(?)                  # match another rule
  2483.             | repetition                       # match repeated subrules
  2484.             | terminal                         # match the next input
  2485.             | bracket args(?)                  # match alternative items
  2486.             | action                           # do something
  2487.  
  2488.  subrule    : identifier                       # the name of the rule
  2489.  
  2490.  args       : {extract_codeblock($text,'[]')}  # just like a [...] array ref
  2491.  
  2492.  repetition : subrule args(?) howoften
  2493.  
  2494.  howoften   : '(?)'                            # 0 or 1 times
  2495.             | '(s?)'                           # 0 or more times
  2496.             | '(s)'                            # 1 or more times
  2497.             | /(\d+)[.][.](/\d+)/              # $1 to $2 times
  2498.             | /[.][.](/\d*)/                   # at most $1 times
  2499.             | /(\d*)[.][.])/                   # at least $1 times
  2500.  
  2501.  terminal   : /[/]([\][/]|[^/])*[/]/           # interpolated pattern
  2502.             | /"([\]"|[^"])*"/                 # interpolated literal
  2503.             | /'([\]'|[^'])*'/                 # uninterpolated literal
  2504.  
  2505.  action     : { extract_codeblock($text) }     # embedded Perl code
  2506.  
  2507.  bracket    : '(' Item(s) production(s?) ')'   # alternative subrules
  2508.  
  2509.  directive  : '<commit>'                       # commit to production
  2510.             | '<uncommit>'                     # cancel commitment
  2511.             | '<resync>'                       # skip to newline
  2512.             | '<resync:' pattern '>'           # skip <pattern>
  2513.             | '<reject>'                       # fail this production
  2514.             | '<reject:' condition '>'         # fail if <condition>
  2515.             | '<error>'                        # report an error
  2516.             | '<error:' string '>'             # report error as "<string>"
  2517.             | '<error?>'                       # error only if committed
  2518.             | '<error?:' string '>'            #   "    "    "    "
  2519.             | '<rulevar:' /[^>]+/ '>'          # define rule-local variable
  2520.             | '<matchrule:' string '>'         # invoke rule named in string
  2521.  
  2522.  identifier : /[a-z]\w*/i                      # must start with alpha
  2523.  
  2524.  comment    : /#[^\n]*/                        # same as Perl
  2525.  
  2526.  pattern    : {extract_bracketed($text,'<')}   # allow embedded "<..>"
  2527.  
  2528.  condition  : {extract_codeblock($text,'{<')}  # full Perl expression
  2529.  
  2530.  string     : {extract_variable($text)}        # any Perl variable
  2531.             | {extract_quotelike($text)}       #   or quotelike string
  2532.             | {extract_bracketed($text,'<')}   #   or balanced brackets
  2533.  
  2534.  
  2535. =head1 GOTCHAS
  2536.  
  2537. This section describes common mistakes that grammar writers seem to
  2538. make on a regular basis.
  2539.  
  2540. =head2 1. Expecting an error to always invalidate a parse
  2541.  
  2542. A common mistake when using error messages is to write the grammar like this:
  2543.  
  2544.         file: line(s)
  2545.  
  2546.         line: line_type_1
  2547.             | line_type_2
  2548.             | line_type_3
  2549.             | <error>
  2550.  
  2551. The expectation seems to be that any line that is not of type 1, 2 or 3 will
  2552. invoke the C<E<lt>errorE<gt>> directive and thereby cause the parse to fail.
  2553.  
  2554. Unfortunately, that only happens if the error occurs in the very first line.
  2555. The first rule states that a C<file> is matched by one or more lines, so if
  2556. even a single line succeeds, the first rule is completely satisfied and the
  2557. parse as a whole succeeds. That means that any error messages generated by
  2558. subsequent failures in the C<line> rule are quietly ignored.
  2559.  
  2560. Typically what's really needed is this:
  2561.  
  2562.         file: line(s) eofile    { $return = $item[1] }
  2563.  
  2564.         line: line_type_1
  2565.             | line_type_2
  2566.             | line_type_3
  2567.             | <error>
  2568.  
  2569.         eofile: /^\Z/
  2570.  
  2571. The addition of the C<eofile> subrule  to the first production means that
  2572. a file only matches a series of successful C<line> matches I<that consume the
  2573. complete input text>. If any input text remains after the lines are matched,
  2574. there must have been an error in the last C<line>. In that case the C<eofile>
  2575. rule will fail, causing the entire C<file> rule to fail too.
  2576.  
  2577. Note too that C<eofile> must match C</^\Z/> (end-of-text), I<not>
  2578. C</^\cZ/> or C</^\cD/> (end-of-file).
  2579.  
  2580. And don't forget the action at the end of the production. If you just
  2581. write:
  2582.  
  2583.         file: line(s) eofile
  2584.  
  2585. then the value returned by the C<file> rule will be the value of its
  2586. last item: C<eofile>. Since C<eofile> always returns an empty string
  2587. on success, that will cause the C<file> rule to return that empty
  2588. string. Apart from returning the wrong value, returning an empty string
  2589. will trip up code such as:
  2590.  
  2591.         $parser->file($filetext) || die;
  2592.  
  2593. (since "" is false).
  2594.  
  2595. Remember that Parse::RecDescent returns undef on failure,
  2596. so the only safe test for failure is:
  2597.  
  2598.         defined($parser->file($filetext)) || die;
  2599.  
  2600.  
  2601. =head1 DIAGNOSTICS
  2602.  
  2603. Diagnostics are intended to be self-explanatory (particularly if you
  2604. use B<-RD_HINT> (under B<perl -s>) or define C<$::RD_HINT> inside the program).
  2605.  
  2606. C<Parse::RecDescent> currently diagnoses the following:
  2607.  
  2608. =over 4
  2609.  
  2610. =item *
  2611.  
  2612. Invalid regular expressions used as pattern terminals (fatal error).
  2613.  
  2614. =item *
  2615.  
  2616. Invalid Perl code in code blocks (fatal error).
  2617.  
  2618. =item *
  2619.  
  2620. Lookahead used in the wrong place or in a nonsensical way (fatal error).
  2621.  
  2622. =item *
  2623.  
  2624. "Obvious" cases of left-recursion (fatal error).
  2625.  
  2626. =item *
  2627.  
  2628. Missing or extra components in a C<E<lt>leftopE<gt>> or C<E<lt>rightopE<gt>>
  2629. directive.
  2630.  
  2631. =item *
  2632.  
  2633. Unrecognisable components in the grammar specification (fatal error).
  2634.  
  2635. =item *
  2636.  
  2637. "Orphaned" rule components specified before the first rule (fatal error)
  2638. or after an C<E<lt>errorE<gt>> directive (level 3 warning).
  2639.  
  2640. =item *
  2641.  
  2642. Missing rule definitions (this only generates a level 3 warning, since you
  2643. may be providing them later via C<Parse::RecDescent::Extend()>).
  2644.  
  2645. =item *
  2646.  
  2647. Instances where greedy repetition behaviour will almost certainly
  2648. cause the failure of a production (a level 3 warning - see
  2649. L<"ON-GOING ISSUES AND FUTURE DIRECTIONS"> below).
  2650.  
  2651. =item *
  2652.  
  2653. Attempts to define rules named 'Replace' or 'Extend', which cannot be
  2654. called directly through the parser object because of the predefined
  2655. meaning of C<Parse::RecDescent::Replace> and
  2656. C<Parse::RecDescent::Extend>. (Only a level 2 warning is generated, since
  2657. such rules I<can> still be used as subrules).
  2658.  
  2659. =item *
  2660.  
  2661. Productions which consist of a single C<E<lt>error?E<gt>>
  2662. directive, and which therefore may succeed unexpectedly
  2663. (a level 2 warning, since this might conceivably be the desired effect).
  2664.  
  2665. =item *
  2666.  
  2667. Multiple consecutive lookahead specifiers (a level 1 warning only, since their
  2668. effects simply accumulate).
  2669.  
  2670. =item *
  2671.  
  2672. Productions which start with a C<E<lt>rejectE<gt>> or C<E<lt>rulevar:...E<gt>>
  2673. directive. Such productions are optimized away (a level 1 warning).
  2674.  
  2675. =item *
  2676.  
  2677. Rules which are autogenerated under C<$::AUTOSTUB> (a level 1 warning).
  2678.  
  2679. =back
  2680.  
  2681. =head1 AUTHOR
  2682.  
  2683. Damian Conway (damian@conway.org)
  2684.  
  2685. =head1 BUGS AND IRRITATIONS
  2686.  
  2687. There are undoubtedly serious bugs lurking somewhere in this much code :-)
  2688. Bug reports and other feedback are most welcome.
  2689.  
  2690. Ongoing annoyances include:
  2691.  
  2692. =over 4
  2693.  
  2694. =item *
  2695.  
  2696. There's no support for parsing directly from an input stream.
  2697. If and when the Perl Gods give us regular expressions on streams,
  2698. this should be trivial (ahem!) to implement.
  2699.  
  2700. =item *
  2701.  
  2702. The parser generator can get confused if actions aren't properly
  2703. closed or if they contain particularly nasty Perl syntax errors
  2704. (especially unmatched curly brackets).
  2705.  
  2706. =item *
  2707.  
  2708. The generator only detects the most obvious form of left recursion
  2709. (potential recursion on the first subrule in a rule). More subtle
  2710. forms of left recursion (for example, through the second item in a
  2711. rule after a "zero" match of a preceding "zero-or-more" repetition,
  2712. or after a match of a subrule with an empty production) are not found.
  2713.  
  2714. =item *
  2715.  
  2716. Instead of complaining about left-recursion, the generator should
  2717. silently transform the grammar to remove it. Don't expect this
  2718. feature any time soon as it would require a more sophisticated
  2719. approach to parser generation than is currently used.
  2720.  
  2721. =item *
  2722.  
  2723. The generated parsers don't always run as fast as might be wished.
  2724.  
  2725. =item *
  2726.  
  2727. The meta-parser should be bootstrapped using C<Parse::RecDescent> :-)
  2728.  
  2729. =back
  2730.  
  2731. =head1 ON-GOING ISSUES AND FUTURE DIRECTIONS
  2732.  
  2733. =over 4
  2734.  
  2735. =item 1.
  2736.  
  2737. Repetitions are "incorrigibly greedy" in that they will eat everything they can
  2738. and won't backtrack if that behaviour causes a production to fail needlessly.
  2739. So, for example:
  2740.  
  2741.         rule: subrule(s) subrule
  2742.  
  2743. will I<never> succeed, because the repetition will eat all the
  2744. subrules it finds, leaving none to match the second item. Such
  2745. constructions are relatively rare (and C<Parse::RecDescent::new> generates a
  2746. warning whenever they occur) so this may not be a problem, especially
  2747. since the insatiable behaviour can be overcome "manually" by writing:
  2748.  
  2749.         rule: penultimate_subrule(s) subrule
  2750.  
  2751.         penultimate_subrule: subrule ...subrule
  2752.  
  2753. The issue is that this construction is exactly twice as expensive as the
  2754. original, whereas backtracking would add only 1/I<N> to the cost (for
  2755. matching I<N> repetitions of C<subrule>). I would welcome feedback on
  2756. the need for backtracking; particularly on cases where the lack of it
  2757. makes parsing performance problematical.
  2758.  
  2759. =item 2.
  2760.  
  2761. Having opened that can of worms, it's also necessary to consider whether there
  2762. is a need for non-greedy repetition specifiers. Again, it's possible (at some
  2763. cost) to manually provide the required functionality:
  2764.  
  2765.         rule: nongreedy_subrule(s) othersubrule
  2766.  
  2767.         nongreedy_subrule: subrule ...!othersubrule
  2768.  
  2769. Overall, the issue is whether the benefit of this extra functionality
  2770. outweighs the drawbacks of further complicating the (currently
  2771. minimalist) grammar specification syntax, and (worse) introducing more overhead
  2772. into the generated parsers.
  2773.  
  2774. =item 3.
  2775.  
  2776. An C<E<lt>autocommitE<gt>> directive would be nice. That is, it would be useful to be
  2777. able to say:
  2778.  
  2779.         command: <autocommit>
  2780.         command: 'find' name
  2781.                | 'find' address
  2782.                | 'do' command 'at' time 'if' condition
  2783.                | 'do' command 'at' time
  2784.                | 'do' command
  2785.                | unusual_command
  2786.  
  2787. and have the generator work out that this should be "pruned" thus:
  2788.  
  2789.         command: 'find' name
  2790.                | 'find' <commit> address
  2791.                | 'do' <commit> command <uncommit>
  2792.                         'at' time
  2793.                         'if' <commit> condition
  2794.                | 'do' <commit> command <uncommit>
  2795.                         'at' <commit> time
  2796.                | 'do' <commit> command
  2797.                | unusual_command
  2798.  
  2799. There are several issues here. Firstly, should the
  2800. C<E<lt>autocommitE<gt>> automatically install an C<E<lt>uncommitE<gt>>
  2801. at the start of the last production (on the grounds that the "command"
  2802. rule doesn't know whether an "unusual_command" might start with "find"
  2803. or "do") or should the "unusual_command" subgraph be analysed (to see
  2804. if it I<might> be viable after a "find" or "do")?
  2805.  
  2806. The second issue is how regular expressions should be treated. The simplest
  2807. approach would be simply to uncommit before them (on the grounds that they
  2808. I<might> match). Better efficiency would be obtained by analyzing all preceding
  2809. literal tokens to determine whether the pattern would match them.
  2810.  
  2811. Overall, the issues are: can such automated "pruning" approach a hand-tuned
  2812. version sufficiently closely to warrant the extra set-up expense, and (more
  2813. importantly) is the problem important enough to even warrant the non-trivial
  2814. effort of building an automated solution?
  2815.  
  2816. =back
  2817.  
  2818. =head1 COPYRIGHT
  2819.  
  2820. Copyright (c) 1997-2000, Damian Conway. All Rights Reserved.
  2821. This module is free software. It may be used, redistributed
  2822. and/or modified under the terms of the Perl Artistic License
  2823.   (see http://www.perl.com/perl/misc/Artistic.html)
  2824.