>K X G The man(1) of descent - The Perl Journal, Winter 19982s7
This article is reproduced fromI
Issue #12 of The Perl Journal6
by the kind permission of the editor.

 






AThe man(1) of descent




"Damian Conway


B


Being a scholarly Treatife on the Myfterious OriginsN
and diverfe Ufes of that Module known as Parfe::RecDescent


 C

# 
%
Packages Used

W
Perl 5.004 or later          DCPANK
Parse::RecDescent         MCPAN

7So who cares about parsing anyway?H

Er, well, humans do. Our brains seem to be hard-wired for a syntacticGview of the world, and we strive (often unreasonably) to find or imposeFgrammatical structures in our lives. Homo Sapiens is a species evolvedKfor language (or possibly, by it). We are compulsive and incessant parsers:Gof written text, of spoken words, of our children's faces, of our dogs'Jtails, of our politicians' body language, or the simple grammar of trafficJlights, and the complex syntax of our own internal aches and pains. You'reFparsing right now: shapes into letters, letters into words, words into>sentences, sentences into messages, messages into (dis)belief!I

So it's not surprising that programmers (many of whom were once human)Fshould be concerned with parsing too. If you use any of the modules inHthe Pod::, Date::, HTML::, CGI::, LWP::, or Getopt:: hierarchies, or theGExpect module, or TeX::Hyphen, or Text::Refer, or ConfigReader, or PGP,Lor Term::ReadLine, or CPAN, or Mail::Tools, or one of the database interfaceJmodules, or even if you just read in a line at a time and match it againstGsome regular expressions, then you're parsing. Sometimes in the privacyand comfort of your own home.J

Each of those modules contains a chunk of custom-made, carefully-tuned,Swalnut-veneered code, which takes ugly raw data and sculpts it into finely-chiseled!information you can actually use.L

Of course, if the CPAN doesn't supply a parsing system for the particularIugly raw data you need to process, then you're going to have to roll yourBown. That's what parser generators like Parse::RecDescent are for.

!Anti-diff-erentiation

JTo use such tools, you first need to know something about formal grammars.)Now just relax! This next bit won't hurt.>

Suppose, for example, you want to "reverse" the output of a diffJ(i.e. as if the two files had been compared in the opposite order). Here'sa typical diff output:

17,18d16< (who writes under the"< pseudonym "Omniscient Trash")45,46c43,44"< soon every Tom, Dick or Harry&< will be writing his own Perl book---"> soon every Tom, Randal and Larry%> will be writing their own Perl book69a68,69'> Copyright (c) 1998, The Perl Journal.> All rights reserved.
MEach chunk encodes a single transformation of the original file. For example,Jthe first three lines mean "at lines 17 to 18 of the original file performHa 'Delete' operation, leaving us at line 16 in the second file." It thenEshows the two lines to be removed, each prefixed by a less-than sign.M

The next six lines mean "at lines 45 to 46 of the first file do a 'Change'Foperation, producing lines 43 to 44 in the second file." It then showsJthe lines to be replaced (prefixed by less-than signs) and the replacement lines (with greater-than signs).I

The last three lines mean "at line 69 in the first file do an 'Append'Foperation, to produce lines 68 to 69 in the second file." The lines to9be added are then listed, prefixed by greater-than signs.F

So a diff output consists of a series of operations, each ofMwhich in turn consists of a command followed by context information. CommandsIconsist of a single letter sandwiched between numbers that represent lineFranges in each file. Context information consists of one or more linesIof left context, right context, or both, where each context line consists'of a line of text preceded by an arrow.

.SAY IT GRAMMATICALLY

HPhew! That's a lot of structure for such a small piece of text. But it'suseful structure.I

Let's take this English and turn it into a formal grammar that conveysGthe same information more precisely (and in a more compact and readableformat):9

DiffOutput     -> Command(s) EOFSCommand        -> LineNum A_CHAR LineRange …                     RightLine(s)‡                   | LineRange D_CHAR LineNum„                     LeftLine(s)‰                   | LineRange C_CHAR LineRange„                     LeftLine(s)‚                     SEPARATOR…                     RightLine(s);LineNum        -> DIGITS@LineRange      -> LineNum COMMA LineNumv                   | LineNumELeftLine       -> LEFT_BRACKET TEXTLINEGRightLine      -> RIGHT_BRACKET TEXTLINE
IThe way to read a formal grammar is to replace each right arrow (->) withGthe words "...consists of..." and each vertical bar (|) with theFwords "...or possibly...". The parenthesized (s) means the sameKas in English, namely, "...one or more times". So, for example, the grammarJabove says that a LineRange consists of either a LineNum subrule,Fthen a COMMA, and finally another LineNum, or possibly just asingle LineNum.P

Each of the six chunks of the above grammar specifies a separate rule.HEach identifier on the left of an arrow is the rule's name and each listLof items to the right of an arrow (or a vertical bar) specifies the sequenceYof things that together comprise that rule. Such sequences are called productions.GThe vertical bars separate alternative productions, any one of which is8an acceptable set of components for the rule as a whole.H

Items in a production may be either the name of some other rule (suchFitems are called non-terminals or subrules), or the nameXof something which represents some actual text (such items are called terminals).JIn the above grammar, the nonterminals are in mixed-case and the terminalsin upper-case.F

The use of named terminals implies that something else - usually, aKspecially written subroutine called a lexer - is going to preprocessNLthe original input text and transform it into a sequence of labelled stringsF(called tokens). It is the labels on those tokens that will (we;hope) match the terminals. More on lexers and lexing later.d

1REVERSING A diff

#JIf you gave the full grammar to a parser generator, you'd get back a pieceIof code able to recognize any text conforming to the grammar's rules and,/Imore importantly, identify each part of the text (17,18eHis a LineRange, d is a D_CHAR, 16 isFa LineNum, and so on) Of course, recognizing the text is only+half the battle. Our goal is to reverse it.G

Fortunately, reversing a diff output is easy. You just change/Gevery 'Append' command to a 'Delete', and vice versa, and then swap theDoing that with the example text above you get:

16a17,184> (who writes under thep> pseudonym "Omniscient Trash")b43,44c45,46%< soon every Tom, Randal and Larrye(< will be writing their own Perl book---c> soon every Tom, Dick or Harry&#> will be writing his own Perl bookh68,69d69*< Copyright (c) 1998, The Perl Journal.< All rights reserved
GIn order for the above grammar to automatically reverse diff output, itJneeds to know what to do whenever it recognizes something reversible (i.e.Fa complete command). You can tell it what to do by embedding blocks ofHcode, which the parser then automatically calls whenever it successfully(recognizes the corresponding production.=

Adding the equivalent Perl actions into the above grammar:rE

DiffOutput       -> Command(s) EOFb;Command     -> LineNum A_CHAR LineRange y                   RightLine(s)d                    { print "$item3 d $item1\n";–                      $item4 =~ s/^>/</gm;                      print $item[4]; }u                | LineRange D_CHAR LineNumsx                   LeftLine(s)                    { print "$item3 a $item1\n"; –                      $item4 =~ s/^</>/gm;                      print $item[4]; }w                | LineRange C_CHAR LineRangee                   LeftLine(s) SEPARATOR RightLine(s)p                    { print "$item3 c $item1\n";i–                      $item4 =~ s/^</>/gm;–                      $item6 =~ s/^>/</gm;ž                      print $item6, $item5, $item4; }/LineNum      -> DIGITS"4LineRange    -> LineNum COMMA LineNum|                    | LineNum9LeftLine     -> LEFT_BRACKET TEXTLINEs;RightLine    -> RIGHT_BRACKET TEXTLINE
HNote that the actions need access to the various bits of data which haveGbeen recognized, in order to reprint them. In this example, they accessfHthe data by referring to the lexically scoped variables $item1,$item2,F$item3, and so on. These variables are automagically assignedFthe sub-strings of the original text that were matched by each item inFthe current production (just as $1, $2, $3,Hetc. automatically receive the values of the last matched parentheses of)a regular expression). So the production:A.
Command  -> LineNum A_CHAR LineRangea               RightLine(s)gq               { print "$item3 d $item1\n";dx                 $item4 =~ s/^>/</gm;x                 print $item[4]; }
Jhas now been told that if a Command rule matches an 'Append' command, thenGit should print out the text matching the LineRange (item 3 ofsVthe production), then a 'd', then the original text which matched the LineNumF(item 1). Then it should reverse the arrows on the context lines (item4) and print those out too.;

From Grammar to Reality

GHaving specified the grammar, and its behavior when various productionsRLare recognized, all you need to do is build an actual parser that implementsHthe grammar. Of course, building the parser is the tedious and difficultFbit. And that's why there are automated parser construction tools likeJParse::RecDescent, and its distant cousins yacc, perl-byacc,(PCCTS, Parse::Yapp, and libparse.

4MANY PATHS UP THE MOUNTAIN

FWhen it comes to such tools, the lazy programmer is spoilt for choice.GThere are dozens of freely-available packages for generating parsers inL>a variety of languages (but mostly in C, C++, Java, and Perl).T

Almost all of the parser generators belong to one of two families-top-downGor bottom-up-whose names describe the way their parsers go aboutpcomparing a text to a grammar.

'BOTTOMS UP...

gHBottom-up parsers -- better known as "LR" parsers: "scan Left, expandingHRightmost subrule(in reverse)" -- are usually implemented as a series ofGstates, encoded in a lookup table. The parser moves from state to state.Fby examining the next available token in the text, and then consultingLthe table to see what to do next. The choices are: perform an action, change&to a new state, or give up in disgust.I

A bottom-up parse succeeds if all the text is processed and the parsersHis left in a predefined "successful" state. Parsing can fail at any timeIif the parser sees a token for which there is no suitable next state, andeis therefore forced to give up.eK

In effect, a bottom-up parser converts the original grammar into a maze,oHwhich the text must thread its way through, state-to-state, one token atHa time. If the trail of tokens leads to a dead end, then the text didn'tOconform to the rules of the original grammar and is rejected. In this metaphor,rFany actions that were embedded in the grammar are scattered throughout8the maze and are executed whenever they are encountered.I

The bottom-up "maze" for the diff-reversing grammar above looks-like Figure 1.

±

Figure 1: bottom-up mazep@

Figure 1: bottom-up maze



....WITH THE TOP DOWN

GTop-down parsers -- a.k.a. "LL" parsers: "scan Left, expanding LeftmostMsubrule" -- work quite differently. Instead of working token-to-token throughgGa flattened-out version of the grammar rules, top-down parsers start atoCthe highest level and attempt to match the most general rule first.tG

Thus a top-down parser would start by attempting to match the entirenDiffOutputtOrule, and immediately realize that to do so it must match one or more instances Mof the Command rule. So it would attempt to match a CommandFJrule, and immediately realize that to do so it must match one of the threeFproductions in the Command rule. So it would try to match theJfirst production, and realize that it must first match a LineNum, and so on.F

It would keep moving ever further down the hierarchy of rules untilLit actually reached a point where it could try and match a terminal (againstIthe first available token). If the terminal and token matched, the parserJwould move back up the hierarchy looking for the next bit of the enclosingHproduction, and following that down until the next token was matched. IfHall the parts of the production were matched, the parser would move backHup, matching higher and higher rules, until it succeeded in matching thetop-most rule completely.dF

If at some point a token fails to match, then the parser would workIback up the tree, looking for an alternative way of matching the originaleLrule (i.e. via a different production of the same rule). If all alternatives1eventually fail, then the parse as a whole fails.iI

In other words, a top-down parser converts the grammar into a tree (orbSmore generally, a graph), which it then traverses in a top-to-bottom, left-to-rightmIorder. If a particular branch of the tree fails to match, then the parsernGbacks up and tries the next possible branch. If all branches fail, then;Kthe parse itself fails. In this approach, embedded actions represent leaves;Aon the tree, and are executed if the traversal ever reaches them.;G

The top-down "tree" for the diff-reversing grammar looks like Figuren2.

°

Figure 2: top-down tree?

Figure 2: top-down tree

s

3THE DESCENT OF RECDESCENT

eFTools for building bottom-up parsers have a long and glorious history,Idominated by the yacc program developed by Stephen Johnson at BellnKLabs in the mid 1970's. Yacc accepts a grammar very similar to thosenLshown above and generates C code, which can then be compiled into a function;that acts as parser for the language the grammar describes.nT

Rick Ohnenus adapted a modern variant of yacc to create perl-byacc,Fwhich generates Perl code directly. Later, Jake Donham developed a setHof patches allowing perl-byacc to generate parser objects (ratherthan parsing functions).L

Recently, Fran&ccecil;ois Desarmenien went one better and implementedQa complete object oriented yacc-like parser generator, called Parse::Yapp,n>directly in Perl (it also generates its parsers as Perl code).G

Top-down parsing has been less popular, but one prominent tool which;Kuses this approach is PCCTS, developed as a PhD research project by TerencesIParr. PCCTS provides much more power and flexibility than the yaccn)family, but generates C++, not Perl code.sF

John Wiegley's libparse bundle is an extremely comprehensiveFand ambitious parsing system that does generate Perl code. It is stillHin alpha release, but can already generate top-down parsers, at least onHNT machines. Finally, my own Parse::RecDescent module - the topic of theFrest of this article - creates very flexible top-down parsers in Perl.

!The Journey of 1000 Miles...

pIMost parser generators involve an unpleasantly complicated ritual. First,;Kyou create a lexer to split up your text into labelled tokens. That usually;Oinvolves hand-crafting some code or using a lexer generator such as lex,L flex,Lor DLG. Next, you create your grammar and feed to a parser generator.JThe parser generator spits out some more code: your parser. Then you writeLyour program, importing both the lexer and parser code you built previously.GYou hook the three bits together and voilá! Typically that looks something like Figure 3.
½

Figure 3: Parser GeneratoreB

Figure 3: Parser Generator

K

Of course, this multi-stage, multi-task, multi-file, multi-tool approach;&quickly becomes a multi-lobe headache.

"ONE STEP

9Building a parser with Parse::RecDescent looks like this:;
Θ

Figure 4: Parser with Parse::RecDescentO

Figure 4: Parser with Parse::RecDescent

/I

The entire parsing program is specified in a single file of Perl code.hHTo build a parser, you create a new Parse::RecDescent object, passing itHthe required grammar. The new object provides methods which you can thenMuse to parse a string. For example, here is the complete diff reversern$implemented using Parse::RecDescent:

#!/usr/bin/perl -weuse Parse::RecDescent;my $grammar = q{!  DiffOutput:Command(s) /\Z/n    Command:d;     LineNum 'a' LineRange RightLine(s).C       { print "$item[3]d$item[1]\n";dW         print map {s/>/</; $_} @{$item[4]};s&       }0   | LineRange 'd' LineNum LeftLine(s)C       { print "$item[3]a$item[1]\n"; W         print map {s/</>/; $_} @{$item[4]};y&       }&   | LineRange 'c' LineRange9     LeftLine(s) "---\n" RightLine(s) C       { print "$item[3]c$item[1]\n";mW         print map {s/>/</; $_} @{$item[6]};a@         print $item[5];X         print map {s/</>/; $_} @{$item[4]};}3   | <error: Invalid diff(1) command!>n   
LineRange:    LineNum ',' LineNum0     { join '',@item[1..3] }   | LineNum   LineNum: /\d+/LeftLine: /<.*\n/RightLine: />.*\n/};-my $parser = new Parse::RecDescent($grammar);p	undef $/; my $text = <STDIN>;!$parser->DiffOutput($text);
eGThe structure of this program is straightforward. First you specify theePgrammar as a string ($grammar). Next you create a new Parse::RecDescentLobject, passing $grammar as an argument to new(). AssumingFthe grammar was okay (and in this case it was), new() returns=an object, which has one method for each rule in the grammar.dO

You then read the entire STDIN into another string ($text)tMand pass that text to the parser object's DiffOutput method, causinge<the parser to attempt to match the string against that rule.J

As the match proceeds, the various actions specified for each rule willFbe executed. If the text is successfully parsed, the actions which getPfired off along the way will cause the program to print a "diff-reversed"version of its input.h

$Scalpel... Retractor... Forceps

JLet's dissect the program a little. First, observe that the grammar passedNto Parse::RecDescent::new() is very much like the one in the examplesLabove, except that it uses a colon to define new rules, instead of an arrow.F

Note too that the grammar constitutes the vast bulk of the program.@In fact, the rest of the code could be reduced to a single line:H

Parse::RecDescent::new($grammar)->DiffOutput(join '',<>);

(HANDLING ITEMS

QAnother minor difference is that Parse::RecDescent uses an array (@item)mKto represent matched items, instead of individual scalars ($item1,<$item2,Jetc.) The automagical behavior of this @item array bears a littleHmore explanation. When a subrule in a production matches during a parse,Fthat match returns the scalar value of the last item matched byFthe subrule. That returned value is then assigned to the correspondingGelement of @item in the production which requested the subruletmatch.D

That means that if a rule consists of a single item (for example, LineNum:M/\d+/) then the substring matched by that regular expression is returnedrLup the parse tree when the rule succeeds. On the other hand, if a productionPconsists of several items in sequence (e.g. LineRange: LineNumI',' LineNum), then only the value of the second LineNumosubrule would be returned.H

It's a reasonable default, but if it's not the behavior you want, youNneed to add an action as the last item (e.g. {join '', @item[1..3]}),Ito ensure that the appropriate value is returned for use higher up in theegrammar.

1HANDLING REPEATED ITEMS

rGAnother special case to keep in mind: if you specify a repeated subruletHin a production (like Command(s) or LeftLine(s) ), theIscalar value that comes back to @item is a reference to an arrayeRof values, one for each match. That's why the print statement for the 'c'Lcommand prints @{$item[4]} (i.e. the actual array of values matched=by LeftLine(s) ), instead of just $item[4].tH

By the way, the various map operations applied to these arrays simply4reverse the angle brackets, as diff requires.

"NO LEXER

GThe other major difference between the Parse::RecDescent version of theoHgrammar and those shown earlier is that, where the previous grammars hadFtoken names like DIGITS, SEPARATOR, A_CHAR,Pand EOF as its terminals, this version has quoted strings ('a'Linstead of A_CHAR, '---\n' instead of SEPARATOR),Por regular expressions (/\d+/ instead of DIGITS, /\Z/instead of EOF). P

This is because, unlike nearly all other parser generators, Parse::RecDescentIcreates a parser that doesn't require a separate lexer subroutine to chew"its input into predigested pieces.F

Instead, when a Parse::RecDescent parser reaches a quoted string orMregular expression in one of its productions, it simply matches the specifiedaPtext or pattern against its original input string. This is known as "on-the-fly"Ior "context-sensitive" tokenization, and is a more flexible strategy than Othe usual pretokenization, because it allows different productions to interpretlthe same input differently.tH

A well known case that cries out for such context-sensitive lexing isNin the grammar for C++, where nested templates (such as List<List<int>>)Kroutinely generate syntax errors because the pretokenizing lexer classifiesiKthe trailing >> as a single "right shift" token. A Parse::RecDescent parsertFwould have no such difficulties, should it ever demean itself to parsesomething as ugly as C++.a

(ERROR HANDLING

GA final addition to the Parse::RecDescent version of the grammar is thet&fourth production of the Command rule:/
<error: Invalid diff(1) command!>
oIThis is not a specification of what to match, but rather a directive thatoKtells the parser what to do if it reaches that point without having matchednanything else.K

This particular directive tells the parser to generate the error message Invalid.Gdiff(1) command and then fail. That failure will be fatal, becauserHit will stop the repeated Command subrule from matching any further, andFwill cause the following /\Z/ terminal to not find the end of the input.

!Surely you can't be serious?

cFGrammar-based parsing certainly isn't restricted to processing rigidlyIdefined data formats such as diff produces. Here's another example-Lthat's about as different as you can get. It's the classic "Who's on first?"Sroutine, as performed by a pair of Parse::RecDescent parsers named $abbott>and $costello.l
e%use vars qw( %base %man @try_again );puse Parse::RecDescent;7sub Parse::RecDescent::choose { $_[1 + int rand $#_]; }h3$abbott = new Parse::RecDescent <<'EOABBOTT'; :        Interpretation:n                ConfirmationRequest\              | NameRequest\              | BaseRequest?        ConfirmationRequest:c‡                Preface(s?)  Name  /[i']s on/ Basee±                        { (lc $::man{$item[4]} eq lc $item[2])/Β                                ? "Yes"β                                : "No, $::man{$item[4]}\'s on $item[4]"Œ                        }ˆ              | Preface(s?)  Name  /[i']s the (name of the)?/—                   Man  /('s name )?on/  Base p±                        { (lc $::man{$item[6]} eq lc $item[2])Θ                                ? "Certainly"λ                                : "No. \u$item[2] is on " . $::base{lc $item[2]}.Œ                        }7        BaseRequest:,                Preface(s?)  Name  /(is)?/t°                        { "He's on " . $::base{lc $item[2]} }7        NameRequest:I’                /(What's the name of )?the/i  Base  "baseman"Ÿ                        { $::man{$item[2]} }:B        Preface: ...!Name /\S*/[        Name:   Name12  | /I Don't Know/itI        Name12: /Who/i  | /What/irY        Base:   'first' | 'second' | 'third'<x        Man:    'man'   | 'guy'    | 'fellow'EOABBOTT7$costello = new Parse::RecDescent <<'EOCOSTELLO';r:        Interpretation:–                Meaning {prev}> ­                        { $thisparser->{prev} = $item[1] }si              | { choose(@::try_again) }:`                3        Meaning:dc                Questione`              | UnclearReferent\              | NonSequitur4        Question:’                Preface  Interrogative  /[i']s on/  BaseΕ                        { choose ("Yes, what is the name of the guy on $item[4]?",eί                                  "The $item[4] baseman?",tγ                                  "I'm asking you! $item[2]?",rW                                  "I don't know!")                      }l^              | Interrogative―                        { choose ("That's right, $item[1]?",pΟ                                  "What?",iW                                  "I don't know!")                      }m;        UnclearReferent:ao                "He's on"  Baseeͺ                        { choose ("Who's on $item[2]?",Ρ                                  "Who is?",hυ                                  "So, what is the name of the guy on $item[2]?"t’                                  )                                     }7        NonSequitur:e†                ( "Yes" | 'Certainly' | /that's correct/i )₯                        { choose("$item[1], who?",nΙ                                 "What?",sf                                 @::try_again)                          }J        Interrogative: /who/i | /what/iY        Base:   'first' | 'second' | 'third'sK        Preface: ...!Interrogative /\S*/;
EOCOSTELLOE%man = ( first => "Who", second => "What", third => "I Don't Know" );s&%base  = map { lc } reverse %man;@try_again = (;A        "So, who's on first?",nL        "I want to know who's on first!",S        "What's the name of the first baseman?",se        "Let's start again. What's the name of the guy on first?",;J        "Okay, then, who's on second?",H        "Well then, who's on third?",U        "What's the name of the fellow on third?",n);.$costello->{prev} = $line = "Who's on first?";	while (1)n{;^        print "  ", $line, "\n" and sleep 1;R        $line = $abbott->Interpretation($line);h        print "    ", $line, "\n" and sleep 1;T        $line = $costello->Interpretation($line);};
F


Each of the parsers encodes a particular world-view, which is aHcombination of interpretations of sentences it is parsing, together withKsome text generation logic that allows it to respond appropriately to thoseninterpretations.J

The Abbott grammar treats each line as either a statement that requiresGconfirmation (a ConfirmationRequest), or as a name or positionB"enquiry (a BaseRequest or$NameRequest), for which the@appropriate fielding position or player name should be supplied.F

In contrast, the Costello grammar treats each parsed line as eitherGa rephrasing of a previous question (a Question) that it tries"Hto confirm, or as an ambiguous statement (UnclearReferent) thatMit tries to clarify, or as an inexplicable utterance (a NonSequitur)sHthat derails the entire dialogue and forces it to start the conversation from scratch.F

The humor resides in the fact that, although the responses providedJby each parser are entirely consistent (within each grammar's world-view),=they mesh seamlessly into inescapable mutual incomprehension.a

Making Conversation

LThis example illustrates some additional features of the RecDescent package:Lparser return values, object oriented parsing, explicit rejection, "inlined"Jsubrules, optional and specified-repetition subrules, and rule lookaheads.

.PARSER RETURN VALUES

HJust as each subrule in a Parse::RecDescent parser evaluates to a singleFscalar value, so too the rule through which parsing is initiated (e.g.#$costello->Interpretation);Freturns a scalar value. Specifically, it returns the value assigned to4the Interpretation rule within the grammar.O

The program uses this feature to extract responses from Abbott and Costello.nJEach response is generated within some lower-level subrule of each grammarHby embedded actions that either analyze whether the recognized statementKis true (ConfirmationRequest) or look up the information requested;I(NameRequest) or, in desperation, choose a random (but relevant)sHresponse (UnclearReferent). The generated response bubbles backFup the parse tree, to be returned by the top-most rule. The while loopIthen feeds that response into the other parser, whose response is in turnnMfed back to the first parser. The ensuing alternation generates the dialogue.UJ

Although it can't happen in either of these parsers, the parser returnsSundef if the initial rule fails to match. Hence a common idiom in Parse::RecDescento parsers is:s*

$result = $parser->InitialRule($text);      or die "Bad input!\n";
i

1OBJECT ORIENTED PARSING

sHParsers generated with Parse::RecDescent are Perl objects (specifically,Jblessed hash references), and the Costello grammar takes advantage of thatfact in two ways.eG

First, it makes use of Parse::RecDescent::choose() function;M(which is not part of Parse:: RecDescent, but was added by the main program),n6to randomly select from a range of possible responses.N

Second, the Costello grammar adds an extra member to the $costelloNparser object: $thisparser->{prev}. It uses that to cache information*between parses (more on that in a moment).T

The $thisparser variable is automatically generated by Parse::RecDescentMhas abilities far beyond those described so far. Some of its more interestingnGabilities follow. Parse::RecDescent, and is the way in which actions insIa grammar can refer to the parser which is executing them. It's much likebIthe variable $self used when writing method subroutines for Perlclasses.

,EXPLICIT REJECTION

FYou can explicitly cause a production to reject itself under specifiedFconditions with the <reject:...> directive. This directiveItakes a Perl expression and evaluates it. If the expression is true, thennGthe directive immediately causes the current production to fail. If thesGexpression is false, the directive is ignored and matching continues in;the same production.F

The Costello grammar uses this facility in order to avoid repeating"its responses. Its top-level rule:

Interpretation:R      Meaning <reject:$item[1] eq $thisparser->{prev}>Y          { $thisparser->{prev} = $item[1] }p'  | { choose(@::try_again) }
pJfirst tries to match a Meaning, but then rejects the match if the returnedVresponse is the same as the previously-cached value (in $thisparser->{prev}).GIf the returned response isn't rejected, the following action caches it;Gfor next time. And since the action is the last item of the production,nKit returns that value on behalf of the entire Interpretation rule.sM

On the other hand, if the response was rejected, then the first production;Fimmediately fails, and the second production is tried. That productionJimmediately chooses a random response from the list in @try_againGand returns it as the value of the entire Interpretation rule.sORejection can even take into account factors outside the grammar. For instance,na rule like this:o

Filename:D      /\w+/ <reject: !-r $item[1]>
Fallows your grammar to recognize an identifier as a filename, but only-if the string is the name of a readable file.s

,"INLINED" SUBRULES

JAlternative subproductions can be specified in parentheses within a single+production. For example, the subproduction:n
NonSequitur:s1 ( "Yes" | 'Certainly' | /that's correct/i )n? { choose("$item[1], who?", "What?", @::try_again) }
uIlets you perform the same action for Yes, Certainly, or anythingn$matching /that's correct/i.

DOPTIONAL AND SPECIFIED-REPETITION SUBRULES

GJust as subrules in a production can be made repeatable with a trailing;J(s), they can also be made optional with a trailing (?),For optional and repeatable with a trailing (s?), or even madeIto repeat an exact number of times if a numeric range is specified in thentrailing parentheses."

For example, the rule:;0

BaseRequest: Preface(s?) Name /(is)?/
Nspecifies that a name may be preceded by zero or more prefaces. Alternatively,-you could set a limit with an explicit range:g3
BaseRequest: Preface(0..10) Name /(is)?/
n

)RULE LOOKAHEADS

;MParse::RecDescent also provides a mechanism similar to zero-length lookaheadsnJin regular expressions, better known as (?= ) and (?! ).FParse::RecDescent lookaheads act just like other production items whenFmatching, except that they do not "consume" the substrings they match.HThat means the next item encountered after a lookahead item will attempt6to match at the same starting point as that lookahead.H

Negative lookaheads are specified with a ...! prefix and areFtypically used as guards to prevent repeated subrules from eating moreLthan they should. The Abbott grammar, for example, uses a negative lookaheadIto make sure that the Preface subrule doesn't consume a significant name:s"

Preface: ...!Name /\S*/
KThe ...! preceding Name means that, to match a Preface, the string Hbeing parsed must not have a Name before the specified pattern.K

Positive lookaheads are specified with a ... prefix, and are also usefultGfor ensuring that repetitions don't get too greedy. They aren't used inoKthe Abbott or Costello grammars, but they're handy in situations like this:p-

Move: 'mv' File ExtraFile(s) Destination    | 'mv' File Files   ExtraFile: File ...FilenDestination: File
;LHere, an ExtraFile only matches a File followed by anotherFile.7That means that exactly one file will be left after thenExtraFile:subrule has matched repeatedly, ensuring that the trailingDestination>item will match. Without the trailing lookahead, ExtraFile would>match all the files, leaving nothing for Destination.
It Does What??!
HParse::RecDescent has abilities far beyond those describwed so far. Some*of it's more interseting abilities follow.

3AUTOMATED ERROR REPORTING

RKThe <error: message> directive used in the diff-reversersKprints a fixed message when triggered. Parse::RecDescent provides a relatedrFdirective, <error>, which automatically generates an errorHmessage, based on the specific context in which it's triggered. Consider this rule:
Command:t"LineNum 'a' LineRange RightLine(s)#| LineRange 'd' LineNum LeftLine(s)S| LineRange 'c' LineRanges'  LeftLine(s) "---\n" RightLine(s)r| <error> <error>
hQIf none of the preceding productions had matched anything, it would automatically generate the message:s&
ERROR (line 10): Invalid Command:e           was expecting LineNum or LineRange
s(when fed invalid diff output at line 10.

7INTEGRATED TRACING FACILITIES

iGTracking down glitches when a large grammar is applied to a long stringiOcan be tricky. Parse::RecDescent makes it easier with extensive error checking, Kand a tracing mode that provides copious information on parser constructiontand execution.O

As the parser is constructed from a grammar, Parse::RecDescent automaticallyeFdiagnoses common problems, such as invalid regular expressions used asTterminals, invalid Perl code in actions, incorrect use of lookaheads, unrecognizableGelements in the grammar specification, unreachable rule components, theoMuse of undefined rules as production items, and cases where greedy repetitionAbehavior will almost certainly cause the failure of a production.eQ

Other, less critical problems are reported if the variable $::RD_WARNJis defined. Extra information and hints for remedying problems can be also6supplied by defining the variable $::RD_HINT.L

Another variable, $::RD_TRACE, can be used to trace the parser'sGconstruction and execution. If $::RD_TRACE is defined prior toeGparser construction, Parse::RecDescent reports (via STDERR) onaIthe construction progress, indicating how each element of the grammar was Ointerpreted. This feature can be especially useful for tracking down mismatchedmJquotes or parentheses, and other subtle bugs in the grammar specification.G

These debugging facilities are designed for unobtrusiveness and ease>Fof use. They can be invoked without making any changes to the originalHgrammar, which reduces the incidents of heisenbugs. Likewise, the use ofJmain package variables as switches makes it easy to debug from the commandNline, without hacking the code at all (e.g. perl -s parserprog.pl -RD_WARN-RD_TRACE ).a

=POSITION INFORMATION WITHIN ACTIONS

eRYou can refer to $thisline, thiscolumn, and $thisoffsetGin any action or directive. These store the current line number, columneAnumber, and offset from the start of the input data. For example: 
Sequence: BaseSequence(s)BaseSequence: /[ACGT]+/ H   | <error: alien DNA detected at byte $thisoffset!>
 

,PARSE TREE PRUNING

HSometimes you know more about the structure of the input than can easilyJbe expressed in a grammar. Such knowledge can be used to prune unpromising"productions out of the parse tree.F

On certain inputs a production may be able to commit itself at someMpoint, effectively saying: "At this point, we know enough that if the currentiJproduction fails, all the rest must also fail." For example, in this rule:5

Command: 'find' <commit> <commit> FilenamesP       | 'delete' <commit> <commit> FilenameJ       | 'move' Filename 'to' Filename
Kthe first production can commit itself after matching find, since the other 6two productions have no hope of matching in that case.

<ARGUMENT PASSING AND GENERIC RULES

LAny non-terminal in a production can be passed arguments in a pair of squareHbrackets immediately after the subrule name. Any such arguments are thenavailable (in the array0@arg) within the corresponding subrule.M

Better still, since double-quoted literal terminals and regular expressioniKterminals are both interpolated during a parse (in the normal Perl manner),eGthis means that a rule can be parameterized according to the data beingl"processed. For example, the rules:"

Command: Keyword Statement(s)G         End[$item[1] $item[1]] Keyword: 'if' | 'while' | 'for't End: "end $arg[0] $arg[0]"
Gensure that command keywords are always matched by a corresponding "endsHkeyword" delimiter, because the Command rule passes the matchedPkeyword ($item[1]) to the End subrule, which then interpolates@it into a string terminal (end $arg[0] ) to be matched.K

It's even possible to interpolate a subrule within a production by using/*the <matchrule:...> directive:"

Command: Keyword Statement(s)l         <matchrule:"End_$item[1]"> <matchrule:"End_$item[1]">Keyword: 'if' | 'while' | 'for'nEnd_if: 'end if'End_while: 'end while'End_for: 'end for'
QIn this version the <matchrule:"End_$item[1]"> directive interpolatessGthe text matched by Keyword into a new subrule (either End_if,rEnd_while,f3or End_for) and then attempts to match it.t

*DEFERRED ACTIONS

NOne of the limitations of embedding actions in rules is that they are executedHas the rule is matched, even if some higher level rule eventually fails.LAt best, that means wasted effort; at worst, it leads to incorrect behavior,=especially if the actions have side effects such as printing.mF

For example, if the diff-reversing grammar were to encounterIincorrect input half way through its parse, it would have already printed/Fsome of the reversed commands when it finds the error, reports it, andstops. That's just plain messy.iI

Fortunately, parser actions in Parse::RecDescent can be deferred until<defer:...> directive around curly braces.H

Here's the diff-reversing grammar from the first example, withdeferred actions instead:k

DiffOutput: Command(s) /\Z/+Command: LineNum 'a' LineRange RightLine(s)o  <defer: <defer:C       { print "$item[3]d$item[1]\n"; ]         print map {s/>/</; $_} @{$item[4]}; } > >e#| LineRange 'd' LineNum LeftLine(s)x  <defer: <defer:C       { print "$item[3]a$item[1]\n"; ]         print map {s/</>/; $_} @{$item[4]}; } > >l| LineRange 'c' LineRangec LeftLine(s) "---\n" RightLine(s)  <defer: <defer:C       { print "$item[3]c$item[1]\n";aW         print map {s/>/</; $_} @{$item[6]};a@         print $item[5];]         print map {s/</>/; $_} @{$item[4]}; } > >b&| <error: Invalid diff(1) command!>LineNum: /\d+/LineRange: LineNum ',' LineNumT           { join '',@item[1..3] }:         | LineNumf                 LeftLine: /<.*\n/RightLine: />.*\n/
FNow the various calls to print are only executed once the entire inputQstring is correctly parsed. So the grammar either reverses the entire diff,!or prints a single error message.nL

As each deferred action is encountered during the parse, it is squirreledJaway and only executed when the entire grammar succeeds. More importantly,Fdeferred actions are only executed if they were part of a subrule thatIsucceeded during the parse. That means that you can defer actions in manyfJalternative productions, and Parse::RecDescent will only invoke those that@belonged to subrules contributing to the final successful parse.

-EXTENSIBLE GRAMMARS

iHThis is probably the weirdest science in Parse::RecDescent. Unlike otherHparser generators, you can extend or replace entire rules in a parser atFrun time. The bit that usually freaks yacc devotees out is thatKyou can even change the grammar while the parser is parsing with it!iJ

For example, suppose you are parsing a programming language that allowsLyou to define new type names, and that those new type names are subsequentlyHinvalid as normal identifiers. In Parse::RecDescent you could do it likethis:+,

TypeName: 'number' | 'text' | 'boolean')TypeDefn: 'type' Identifier 'is' TypeNames6  { $thisparser->Extend("TypeName: '$item[2]'") }*Identifier: ...!TypeName /[a-z]\w*/i
KTraditional parsers for languages like this require you to send semanticuHfeedback to the lexer, to inform it that certain identifiers are nowGto be treated as type names instead. Parse::RecDescent allows you to dodFthe same job using the much simpler notion of lexical feedback,Nby making the parser update itself when a type definition effectively modifiesthe language's syntax.

Do What, John?

nISo what do people actually do with Parse::RecDescent and the other parserw<generators available? Here's a list of typical applications:tHAnywhere that you can specify the structure of some data with a grammar,Ayou can build a recognizer for that data using Parse::RecDescent.>

Whither Parse::RecDescent?

cLParse::RecDescent is powerful, but far from perfect. Some of its limitationsNstem from the type of parsers it builds, others from its own ragged evolution.

.LEFT-RECURSE YE NOT!

RThe most significant limitation is, unfortunately, inherent to Parse::RecDescent'sKnature: like all top-down parsers, it doesn't do left recursion. That meanseOit can't build parsers for certain perfectly reasonable grammars. For instance,pHa fairly typical way of specifying the left associativity of addition isto write a rule like this:-
Addition: Addition '+' Term | Term
n<which ensures that terms are eventually grouped to the left.P

Bottom-up parsers like yacc have no trouble unravelling left-recursiveFrules, but top-down parsers can't handle them, because the first thingGthey would have to do when matching an Addition is to match annAddition,Gwhich in turn requires them to first match an Addition, and sofon.rH

Parse::RecDescent can at least diagnose these cases for you (they canGbe much more subtle than the example above), but it will probably neveroHbe able to build parsers for them. Fortunately that isn't a big problem,0since you can achieve the same effect with this:(

Addition: (Term '+')(s?) Term


.THE NEED...FOR SPEED

HParse::RecDescent parsers aren't always very fast, especially with largeFgrammars or long inputs. Fortunately, that's not an immutable propertyMof the universe, and version 2.00 (which should be in the CPAN for Christmas)n(will feature a considerable speed boost.

,COMING ATTRACTIONS

DOther features slated for future Parse::RecDescent releases include: 

#"Would you like to know more?"

x:Here's where to find more information on all of the above:H

The man(1) of descent. Charles Darwin published The DescentIof Man in 1871, becoming the first scientist to publicly suggest thataIyou could arrange your gran'ma in a Past Tree. The complete original texteis available online from[http://www.literature.org.n,

Sorry? You wanted more on parsing?H

Well, for an FMTYEWTK introduction to the field, it's hard to go past)the dragon book: Aho, Sethi & Ullman,e%Compilers: Principles, Techniques,rMand Tools, from Addison-Wesley. Or for a less rigorous, but more readableHapproach, try The Art of Compiler Design, by Pittman & Peters(Prentice Hall).G

A few online resources are also worth looking at. Two good places tonŸstart are the catalog of parsing tools at: http://www.first.gmd.de/cogent/catalogniand the even larger repository of tools at: http://www.km-cd.com.dragon_fodder/html/ToolBuildingBNF.html. G

If you're specifically interested in using yacc and lex, the Mothers1Gof All Parser Generators, O'Reilly publishes the excellent lex &;yacc (second edition).I

Parse::RecDescent, Parse::Yapp, and libparse are each availabledΊfrom the CPAN, while PCCTS is available from its homepage at http://dynamo.ecn.purdue.edu/~hankd/PCCTS/.G

Finally, if you want to know more about Parse::RecDescent, there's a;G40 page POD manual that comes with the distribution. You can also point Ψyour fevered browser at: http://theory.uwinnipeg.ca/CPAN/data/Parse-RecDescent/Parse/RecDescent.html.

-Deo (Et Al) Gratias

;FMy deepest gratitude to Nathan Torkington for suggesting this article,Jand for his heroic efforts cleaning up the Augean stables of my prolixity.FNo good deed ever goes unpunished. Thanks also to the (foreign) legionNof Parse::RecDescent testers, users, and other guinea-pigs for their feedback,Jcomplaints and wild-and-crazy suggestions. In particular, Helmut Jarausch,:Theo Petersen, and Mark Holloman have a lot to answer for.

__END__

r_


Damian Conway (damian@csse.monash.edu.au) Jlives in a former penal colony where he leads young minds to the Dark SideJ(by teaching them object oriented software engineering in C++). He is alsoFguilty of the Text::Balanced, Lingua::EN::Inflect, and Getopt::DeclareHmodules. Those last two tied for the 1998 Larry Wall Award for PracticalGUtility, which their author views as a damning evidence of endemic drugr!use in Perl's upper echelons.t

u



 o goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true"t!$ if jname .eqs. p1 then exit 1 $ goto jloop $ jloop:fF$ noaccess = f$getqui("display_job","job_inaccessible",,"all_jobs")-$ if noaccess .eqs. "true" then goto jloopp)$ if noaccess .eqs. "" then goto qloopp1$ jname = f$getqui("display_job","job_name",,-c$ "freeze_context,all_jobs")$! 'jname'= "true