home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / yay-1_0.zip / yay-1_0 / doc / yay10man.txt < prev   
Text File  |  1996-02-05  |  167KB  |  5,392 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.                       YYAAYY RReeffeerreennccee MMaannuuaall
  28.  
  29.  
  30.  
  31.  
  32.                                by
  33.  
  34.                          J. A. Gardner
  35.  
  36.                          Thinkage Ltd.
  37.                        85 McIntyre Drive
  38.                        Kitchener, Ontario
  39.                         Canada  N2R 1H6
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.                 Copyright 1995 by Thinkage Ltd.
  60.  
  61.  
  62.  
  63. Thinkage Ltd.                           YAY Reference Manual
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.                      TTaabbllee ooff CCoonntteennttss
  71.  
  72.  
  73. 11.. IInnttrroodduuccttiioonn........................................................................................22
  74.     1.1  A Note to Novices.................................2
  75.  
  76. 22.. HHooww YYAAYY WWoorrkkss......................................................................................44
  77.     2.1  "yyparse" and "yylex".............................4
  78.     2.2  Grammar Rules.....................................5
  79.     2.3  Notes on Compiling Source Code Produced by YAY....6
  80.  
  81. 33 IInnppuutt ttoo YYAAYY..........................................................................................77
  82.     3.1  The Declarations Section..........................8
  83.         3.1.1  Token Declarations..........................8
  84.         3.1.2  Precedence and Binding......................9
  85.         3.1.3  Variable/Function Declarations.............12
  86.         3.1.4  Summary....................................12
  87.     3.2  Grammar Rules....................................12
  88.         3.2.1  Recognition Actions........................14
  89.         3.2.2  Token and Symbol Values....................15
  90.         3.2.3  Precedence in the Grammar Rules............16
  91.         3.2.4  The Start Symbol...........................18
  92.         3.2.5  The End Marker.............................19
  93.         3.2.6  Declarations in yyparse....................19
  94.     3.3  The Programs Section.............................20
  95.         3.3.1  The Lexical Analyzer.......................21
  96.  
  97. 44.. IInntteerrnnaall SSttrruuccttuurreess........................................................................2222
  98.     4.1  States...........................................22
  99.     4.2  Diagramming States...............................23
  100.     4.3  State Actions....................................24
  101.         4.3.1  The Accept Action..........................25
  102.         4.3.2  The Shift Action...........................25
  103.         4.3.3  The Reduce Action..........................26
  104.         4.3.4  The Goto Action............................27
  105.         4.3.5  The Error Action...........................28
  106.  
  107. 55.. EErrrroorr--HHaannddlliinngg..................................................................................2299
  108.     5.1  The "error" Symbol...............................29
  109.     5.2  The Error Condition..............................29
  110.     5.3  Examples.........................................30
  111.     5.4  Error Recognition Actions........................32
  112.     5.5  The yyclearin Macro..............................33
  113.     5.6  The yyerror Function.............................33
  114.         5.6.1  Changing yychar in yyerror.................34
  115.     5.7  The yyerrflag Variable...........................35
  116.     5.8  The yyerrok Macro................................36
  117.     5.9  Other Error Support Routines.....................36
  118.  
  119.  
  120.  
  121. November, 1995                                        Page i
  122.  
  123.  
  124.  
  125. YAY Reference Manual                           Thinkage Ltd.
  126.  
  127.  
  128.  
  129. 66.. YYAAYY OOuuttppuutt..........................................................................................3388
  130.     6.1  Rules Summary....................................39
  131.     6.2  State Descriptions...............................39
  132.     6.3  Conflict Summary.................................42
  133.     6.4  Parser Statistics................................43
  134.  
  135. 77.. TTyyppeess....................................................................................................4466
  136.     The Default Action....................................47
  137.  
  138. 88.. AAmmbbiigguuiittiieess........................................................................................4499
  139.     8.1  Resolving Conflicts by Precedence................50
  140.     8.2  Disambiguating Rules.............................50
  141.     8.3  Conflicts in YAY Output..........................53
  142.  
  143. 99.. AAddvvaanncceedd FFeeaattuurreess............................................................................5544
  144.     9.1  LALR(2) Grammars.................................54
  145.         9.1.1  The Lookahead Action.......................54
  146.         9.1.2  The yy2lex Routine.........................55
  147.         9.1.3  Conflicts..................................56
  148.     9.2  Multiple Actions.................................57
  149.     9.3  Selection Preference.............................59
  150.     9.4  Negative Numbers in $N Constructs................63
  151.     9.5  Lists and Handling Null Strings..................64
  152.     9.6  Right vs. Left Recursion.........................66
  153.     9.7  YYDEBUG..........................................68
  154.     9.8  Important Symbols................................69
  155.     9.9  How YYERROR May Be Used..........................70
  156.     9.10  The Default Action..............................73
  157.     9.11  Invalid Tokens..................................74
  158.     9.12  Dynamic Stack Allocation........................74
  159.     9.13  Synchronizing the Lookahead.....................76
  160.     9.14  YYSHIFT.........................................76
  161.  
  162. AAppppeennddiixx AA -- AAnn EExxaammppllee......................................................................7788
  163.  
  164. AAppppeennddiixx BB -- YYAAYY vvss.. YYAACCCC..................................................................8811
  165.  
  166. AAppppeennddiixx CC -- TThhee LLIINNTT CCoommmmaanndd LLiinnee................................................8822
  167.  
  168.  
  169.  
  170.  
  171.  
  172.  
  173.  
  174.  
  175.  
  176.  
  177.  
  178.  
  179.  
  180.  
  181.  
  182.  
  183. Page ii                                       November, 1995
  184.  
  185.  
  186.  
  187. Thinkage Ltd.                           YAY Reference Manual
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.                       11.. IInnttrroodduuccttiioonn
  196.  
  197.     YAY is  a tool  for writing compilers and other programs
  198. that parse  input according  to strict  "grammar" rules.  In
  199. the terminology  of parsing  theory, YAY  can handle LALR(2)
  200. grammars with  disambiguating rules.  This is a fairly broad
  201. class of  grammars -- most of the computing languages in use
  202. today can be described using LALR(2) specifications.
  203.  
  204.     For a  precise definition  of this  sort of grammar, see
  205. any standard  text on  parsing theory,  e.g.  _P_r_i_n_c_i_p_l_e_s_ _ _o_f
  206. _C_o_m_p_i_l_e_r_ _D_e_s_i_g_n  by A.V.Aho  and J.D.Ullman, Addison-Wesley,
  207. 1977, or  _L_R_ _ _P_a_r_s_i_n_g  by  Aho  and  Johnson,  in  Computing
  208. Surveys.
  209.  
  210.     The appearance  of YAY  input is  based on  the input to
  211. YACC (Yet Another Compiler-Compiler), written by S.C.Johnson
  212. of Bell  Telephone Laboratories,  Murray  Hill,  N.J.    The
  213. LALR(1) version  of YAY  was written  by K.W.Lalonde  of the
  214. Software Development  Group of  the University  of Waterloo.
  215. Enhancements to  allow YAY  to handle  LALR(2) grammars were
  216. made by P.J.Fraser, also of SDG.
  217.  
  218.     The parsing  algorithm used  by YAY  is derived from the
  219. article  "Methods   for  Computing   LALR(k)  Lookahead"  by
  220. B.B.Kristensen   and   O.L.Madsen,   _A_C_M_ _ _ _T_r_a_n_s_a_c_t_i_o_n_s_ _ _ _o_n
  221. _P_r_o_g_r_a_m_m_i_n_g_ _L_a_n_g_u_a_g_e_s_ _ _a_n_d_ _ _S_y_s_t_e_m_s,  Vol.3,  No.1,  January
  222. 1981, pp.60-82.   Those  interested in  reading this article
  223. should first have a good grasp of parsing theory principles.
  224.  
  225.  
  226. 11..11  AA NNoottee ttoo NNoovviicceess
  227.  
  228.     YAY can produce anything from a simple parser for a desk
  229. calculator program  to  a  very  complicated  parser  for  a
  230. programming language.   Those  who are using YAY for complex
  231. tasks have  to know  all the  idiosyncrasies of the program,
  232. including a  good deal  about the  internal workings of YAY.
  233. On  the   other  hand,  the  internal  workings  are  mostly
  234. irrelevant to  someone who is making an easy straightforward
  235. parser.
  236.  
  237.     For this  reason, novices  may want  to  skip  some  the
  238. sections of the manual which describe very technical aspects
  239. of YAY.  This is particularly true on first reading, when it
  240. is more important to get an overview of how YAY is used than
  241. to try  to comprehend  every little  detail.   We  therefore
  242.  
  243.  
  244.  
  245. November, 1995                                        Page 3
  246.  
  247.  
  248.  
  249. YAY Reference Manual                           Thinkage Ltd.
  250.  
  251.  
  252.  
  253. suggest that  novices concentrate on the following sections,
  254. and only  look at other sections if the requirements of your
  255. parser make it necessary.
  256.  
  257.   -- All of Chapter 2
  258.   -- All of Chapter 3
  259.   -- All of Chapter 4
  260.   -- Sections 6.0, 6.1, 6.2
  261.   -- all of Chapter 7
  262.   -- Sections 9.3, 9.5, 9.6
  263.  
  264. Novices may  be particularly  interested in Appendix A which
  265. gives an example of YAY input for a simple parser.
  266.  
  267.  
  268.  
  269.  
  270.  
  271.  
  272.  
  273.  
  274.  
  275.  
  276.  
  277.  
  278.  
  279.  
  280.  
  281.  
  282.  
  283.  
  284.  
  285.  
  286.  
  287.  
  288.  
  289.  
  290.  
  291.  
  292.  
  293.  
  294.  
  295.  
  296.  
  297.  
  298.  
  299.  
  300.  
  301.  
  302.  
  303.  
  304.  
  305.  
  306.  
  307. Page 4                                        November, 1995
  308.  
  309.  
  310.  
  311. Thinkage Ltd.                           YAY Reference Manual
  312.  
  313.  
  314.  
  315.  
  316.                       22.. HHooww YYAAYY WWoorrkkss
  317.  
  318.     The input  to YAY describes the rules of a grammar.  YAY
  319. uses these  rules to  produce the  source code for a program
  320. that will  parse the  grammar.  This source code can then be
  321. compiled to  obtain a  program that  reads input,  parses it
  322. according to  the grammar,  and takes  action based  on  the
  323. result.
  324.  
  325.     The source  code produced by YAY consists of a number of
  326. data tables  that represent  the grammar,  plus a C function
  327. named "yyparse".   By  default, all the symbol names used by
  328. YAY begin  with "yy".   This  is an  historical  convention,
  329. dating back  to YAY's  predecessor YACC.   Users  can  avoid
  330. conflicts with YAY names by avoiding symbols that start with
  331. "yy".
  332.  
  333.     Users who  want to  use a  different prefix may indicate
  334. this with a line of the form
  335.  
  336.           %prefix PREFIX
  337.  
  338. at the beginning of their YAY input.  For example,
  339.  
  340.           %prefix ww
  341.  
  342. asks for  a prefix  of "ww"  instead of  "yy".   The  prefix
  343. chosen should  be one  or  two  characters  long  --  longer
  344. prefixes will  lead to  name  conflicts  on  machines  where
  345. external names  are truncated  to six  characters during the
  346. loading  process.     In  addition,  at  least  one  of  the
  347. characters in  the prefix  should be  a  lower  case  letter
  348. (because YAY  uses an  all upper  case version of the prefix
  349. for some  special names,  and this  has to be different from
  350. the real prefix).
  351.  
  352.     Different prefixes  are  useful  when  two  YAY-produced
  353. parsers are  to be  merged into  a single  program.  For the
  354. sake of  convenience, however,  the "yy"  convention will be
  355. used in this manual.
  356.  
  357.  
  358. 22..11  ""yyyyppaarrssee"" aanndd ""yyyylleexx""
  359.  
  360.     "yyparse" returns a value of 0 if the input it parses is
  361. valid according  to the given grammar rules.  It returns a 1
  362. if the  input is  invalid and  error recovery is impossible.
  363. "yyparse" does  not do  its own  lexical analysis.  In other
  364. words, it  does not  pull the  input apart into tokens ready
  365.  
  366.  
  367.  
  368.  
  369. November, 1995                                        Page 5
  370.  
  371.  
  372.  
  373. YAY Reference Manual                           Thinkage Ltd.
  374.  
  375.  
  376.  
  377. for parsing.   Instead,  it calls  a routine  called "yylex"
  378. every time it wishes to obtain a token from the input.
  379.  
  380.     "yylex" returns  a value  indicating the  _t_y_p_e of  token
  381. that has  been obtained.   If the token has an actual _v_a_l_u_e,
  382. this value  (or some  representation of  the value,  e.g.  a
  383. pointer to  a string containing the value) is returned in an
  384. external variable named "yylval".
  385.  
  386.     It is  up to  the user  to write  a "yylex" routine that
  387. breaks the  input into  tokens and returns the tokens one by
  388. one to  "yyparse".   We will  say  more  about  the  lexical
  389. analyzer in Section 3.3.
  390.  
  391.  
  392. 22..22  GGrraammmmaarr RRuulleess
  393.  
  394.     The grammar  rules given  to YAY  not only describe what
  395. inputs are  valid according  to the grammar but also specify
  396. what  action   should  be   taken  when  a  given  input  is
  397. encountered.   For  example,  if  the  parser  recognizes  a
  398. statement that  assigns a  value to  a variable,  the parser
  399. should either  perform the  assignment itself  or take  some
  400. action to  ensure that  the assignment  will eventually take
  401. place.
  402.  
  403.     As an  example, if  the parser is part of an interactive
  404. desk calculator,  it could carry out arithmetic calculations
  405. as soon as the instructions are recognized.  However, if the
  406. parser is acting as the first pass in a multi-pass compiler,
  407. it may simply encode the input in a way that will be used in
  408. a later code-generation pass.
  409.  
  410.     In summary,  the user  must provide  a number  of things
  411. when using YAY to produce a parser:
  412.  
  413. (1)  grammar rules indicating what input is and isn't valid;
  414.  
  415. (2)  a lexical analyzer ("yylex") that breaks raw input into
  416.      tokens for the parsing routine "yyparse";
  417.  
  418. (3)  any source  code or  functions that  may be  needed  to
  419.      perform appropriate  actions once particular inputs are
  420.      recognized;
  421.  
  422. (4)  a  mainline   routine  that   performs  any   necessary
  423.      initializations,   calls   "yyparse",   then   performs
  424.      possible  clean-up  actions.    The  simplest  kind  of
  425.      mainline  is   just  a   function  "main"   that  calls
  426.      "yyparse", then returns.
  427.  
  428.  
  429.  
  430.  
  431. Page 6                                        November, 1995
  432.  
  433.  
  434.  
  435. Thinkage Ltd.                           YAY Reference Manual
  436.  
  437.  
  438.  
  439.  
  440. 22..33  NNootteess oonn CCoommppiilliinngg SSoouurrccee CCooddee PPrroodduucceedd bbyy YYAAYY
  441.  
  442.     By default,  C source  code produced by YAY contains the
  443. line
  444.  
  445.           #define YYSCTAB const
  446.  
  447. It then  uses the  YYSCTAB manifest  to declare various data
  448. objects as  ccoonnsstt.   If you will be compiling the YAY output
  449. with an  old C  compiler that  doesn't recognize  the  ccoonnsstt
  450. qualifier, you should change the definition to read
  451.  
  452.           #define YYSCTAB
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.  
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.  
  467.  
  468.  
  469.  
  470.  
  471.  
  472.  
  473.  
  474.  
  475.  
  476.  
  477.  
  478.  
  479.  
  480.  
  481.  
  482.  
  483.  
  484.  
  485.  
  486.  
  487.  
  488.  
  489.  
  490.  
  491.  
  492.  
  493. November, 1995                                        Page 7
  494.  
  495.  
  496.  
  497. YAY Reference Manual                           Thinkage Ltd.
  498.  
  499.  
  500.  
  501.  
  502.                        33 IInnppuutt ttoo YYAAYY
  503.  
  504.     This chapter  describes the  input to  YAY when  you are
  505. defining an  LALR(1) grammar.   Chapter  9 will  talk  about
  506. additional needs for LALR(2) grammars.
  507.  
  508.     The input to YAY is broken into three sections:
  509.  
  510.   -- declarations
  511.   -- grammar rules
  512.   -- programs
  513.  
  514. The contents  of each section will be described shortly, but
  515. first we will give some overall rules for YAY input.
  516.  
  517.     Sections of  YAY input  are separated  by the symbol %%.
  518. The general lay-out of YAY input is therefore
  519.  
  520.           declarations
  521.           %%
  522.           grammar rules
  523.           %%
  524.           programs
  525.  
  526. The declarations  section may  be omitted if no declarations
  527. are necessary.   This  will mean  that the input starts with
  528. the first  %%.   The programs  section may  also be omitted,
  529. from the  second %%  on.   The simplest  input  for  YAY  is
  530. therefore
  531.  
  532.           %%
  533.           grammar rules
  534.  
  535.     Blanks, tabs,  and new-lines  are used to separate items
  536. in YAY input.  These are called _w_h_i_t_e_-_s_p_a_c_e characters.  Any
  537. place one  white-space character  is valid,  any  number  of
  538. blanks, tabs, and/or new-lines may be used.  This means, for
  539. example, that  the %%  to separate sections does not have to
  540. be on  a line  all by  itself.  However, giving it a line of
  541. its own makes the YAY input easier to read.
  542.  
  543.     Comments may appear anywhere a blank is valid.  As in C,
  544. comments begin with /* and end with */.
  545.  
  546.     Identifiers used  in  YAY  input  may  be  of  arbitrary
  547. length, and  may consist  of all  letters (upper  and  lower
  548. case), all digits, and the characters dot (.) and underscore
  549. (_).   The first  character of  an identifier  may not  be a
  550. digit.   YAY distinguishes  between  upper  and  lower  case
  551.  
  552.  
  553.  
  554.  
  555. Page 8                                        November, 1995
  556.  
  557.  
  558.  
  559. Thinkage Ltd.                           YAY Reference Manual
  560.  
  561.  
  562.  
  563. letters, so  "this" and  "THIS" and "This" are all different
  564. symbols.
  565.  
  566.     Literals  in   YAY  input  consist  of  a  single  ASCII
  567. character enclosed in single quotes, e.g. 'c'.  The standard
  568. C escape sequences are recognized:
  569.  
  570.           \b   -- backspace
  571.           \n   -- new-line
  572.           \r   -- carriage return
  573.           \t   -- tab
  574.           \'   -- single quote
  575.           \\   -- backslash
  576.           \xxx -- any ASCII character
  577.                   ("xxx" is octal representation)
  578.  
  579. For technical  reasons, the  null  character  '\000'  should
  580. never appear in YAY input.
  581.  
  582.  
  583. 33..11  TThhee DDeeccllaarraattiioonnss SSeeccttiioonn
  584.  
  585.     The  declarations   section  describes   many   of   the
  586. identifiers that  will be used in the rest of the YAY input.
  587. There are two types of declarations:
  588.  
  589. (a)  Token declarations;
  590.  
  591. (b)  Declarations of  functions and  variables used  in  the
  592.      actions that  the parser  takes when a particular input
  593.      is recognized.
  594.  
  595.     The declarations  section can also specify rules for the
  596. precedence and  binding of  operators used  in the  grammar.
  597. For example,  the standard  order of  arithmetic  operations
  598. would normally be set up in the declarations section.
  599.  
  600.  
  601. _3_._1_._1_ _ _T_o_k_e_n_ _D_e_c_l_a_r_a_t_i_o_n_s
  602.  
  603.     All ASCII  characters are  automatically  recognized  as
  604. tokens.   For example,  'a' stands  for a  token that is the
  605. literal character "a".
  606.  
  607.     Other tokens are declared with statements of the form
  608.  
  609.           %token name1 name2 name3 ...
  610.  
  611. This tells  YAY that  the given  names will refer to tokens.
  612. For example,
  613.  
  614.  
  615.  
  616.  
  617. November, 1995                                        Page 9
  618.  
  619.  
  620.  
  621. YAY Reference Manual                           Thinkage Ltd.
  622.  
  623.  
  624.  
  625.           %token INTNUM
  626.  
  627. indicates  that  the  identifier  INTNUM  will  refer  to  a
  628. particular type  of token  returned by  the lexical analyzer
  629. "yylex".  If INTNUM stands for any integer number token, you
  630. might have the following code in "yylex".
  631.  
  632.           c = getchar();
  633.           if ( (c >= '0') && (c <= '9') ) {
  634.               yylval = 0;
  635.               do {
  636.                   yylval = (yylval * 10) + (c - '0');
  637.                   c = getchar();
  638.               } while (c >= '0' && c <= '9');
  639.               ungetc(c, stdin);
  640.               return( INTNUM );
  641.           }
  642.  
  643. "yylex" returns  INTNUM to  indicate that  a certain kind of
  644. token (an  integer number)  has been  returned.   The actual
  645. value of  this number  is returned in "yylval".  The grammar
  646. rules in  the YAY  input would dictate where an INTNUM token
  647. is valid.
  648.  
  649.     In the  C source  code produced  by YAY, the identifiers
  650. named in  a %token statement will appear as constants set up
  651. with ##ddeeffiinnee.  The first named token has a #defined value of
  652. 257, the  next is  #defined as 258, and so on.  Token values
  653. start at  257 so  they will not conflict with any of the 256
  654. ASCII characters.
  655.  
  656.     Because  token   identifiers  are  set  up  as  manifest
  657. constants, they  must not  conflict with  reserved words  or
  658. other identifiers  that will  be used  by the  parser.   For
  659. example,
  660.  
  661.           %token if yyparse ...
  662.  
  663. will almost certainly lead to errors when you try to compile
  664. the source  code output  of YAY.  By convention, this manual
  665. will always  create  token  names  in  upper  case,  and  we
  666. recommend that you follow the same practice.
  667.  
  668.  
  669. _3_._1_._2_ _ _P_r_e_c_e_d_e_n_c_e_ _a_n_d_ _B_i_n_d_i_n_g
  670.  
  671.     Parsers  that   evaluate  expressions  usually  have  to
  672. establish the  order in which various operations are carried
  673. out.    For  example,  parsers  for  arithmetic  expressions
  674. usually carry  out multiplications  before additions.    Two
  675. factors affect order of operation: precedence and binding.
  676.  
  677.  
  678.  
  679. Page 10                                       November, 1995
  680.  
  681.  
  682.  
  683. Thinkage Ltd.                           YAY Reference Manual
  684.  
  685.  
  686.  
  687.  
  688.     Precedence dictates  which of  two different  operations
  689. should be carried out first.  For example, in
  690.  
  691.           A + B * C
  692.  
  693. the standard arithmetic rules of precedence dictate that the
  694. multiplication  should   take  place  before  the  addition.
  695. Operations that should be carried out first are said to have
  696. a _h_i_g_h_e_r precedence than operations that should be performed
  697. later.
  698.  
  699.     Different  operators   can  sometimes   have  the   same
  700. precedence.  In C, for example, addition and subtraction are
  701. similar enough to share the same precedence.
  702.  
  703.     Binding indicates which of two similar operations should
  704. be carried out first.  By "similar", we mean operations with
  705. the same  precedence (e.g.  addition and  subtraction in C).
  706. For example, C chooses to parse
  707.  
  708.           A - B - C
  709.  
  710. as
  711.  
  712.           (A - B) - C
  713.  
  714. while a language like APL would use
  715.  
  716.           A - (B - C)
  717.  
  718. If we  evaluate the  first operation before the second (as C
  719. does), we  say the  operation  is  _l_e_f_t_-_a_s_s_o_c_i_a_t_i_v_e.  If  we
  720. evaluate the  second operation  before  the  first  (as  APL
  721. does), we say the operation is _r_i_g_h_t_-_a_s_s_o_c_i_a_t_i_v_e_.
  722.  
  723.     Occasionally, a  compiler may  have operations which are
  724. not associative.  For example, Fortran regards
  725.  
  726.           A .GT. B .GT. C
  727.  
  728. as invalid.   In  this case,  we say  the operation  is _n_o_n_-
  729. _a_s_s_o_c_i_a_t_i_v_e.   The precedence  and associativity of operator
  730. tokens may be declared in the declarations section using the
  731. keywords
  732.  
  733.           %left
  734.           %right
  735.           %nonassoc
  736.  
  737. For example,
  738.  
  739.  
  740.  
  741. November, 1995                                       Page 11
  742.  
  743.  
  744.  
  745. YAY Reference Manual                           Thinkage Ltd.
  746.  
  747.  
  748.  
  749.  
  750.           %left '+' '-'
  751.  
  752. indicates  that  the  +  and  -  operations  have  the  same
  753. precedence and are left-associative.
  754.  
  755.     Associativity declarations  should be  given in order of
  756. precedence.   Operations with  lowest precedence  are listed
  757. first, and  those with  highest precedence  are listed last.
  758. Operations with  equal precedence  are listed  on  the  same
  759. line.  For example,
  760.  
  761.           %right '='
  762.           %left  '+' '-'
  763.           %left  '*' '/' '%'
  764.  
  765. says that  = has  a lower  precedence than + and -, which in
  766. turn have  a lower  precedence than  *, /, and %.  = is also
  767. right-associative, so that
  768.  
  769.           A = B = C
  770.  
  771. is parsed as
  772.  
  773.           A = (B = C)
  774.  
  775.     Because  of   the  way   YAY  specifies  precedence  and
  776. associativity, operators  with equal  precedence will always
  777. have the  same associativity.   For example, if A and B have
  778. equal precedence,  their precedence  must have been set with
  779. one of
  780.  
  781.           %left A B
  782.           %right A B
  783.           %nonassoc A B
  784.  
  785. which means A and B must have the same associativity.
  786.  
  787.     The names supplied with %right, %left, and %nonassoc may
  788. be literals  or YAY  identifiers.   If they are identifiers,
  789. they are  regarded as  token names.   YAY generates a %token
  790. directive for  such names  if they  have  not  already  been
  791. declared.  For example, in
  792.  
  793.           %left '+' '-'
  794.           %left '*' '/'
  795.           %left UMINUS
  796.  
  797. UMINUS is  taken to be a token identifier.  There is no need
  798. to define UMINUS as a token identifier -- a %token directive
  799.  
  800.  
  801.  
  802.  
  803. Page 12                                       November, 1995
  804.  
  805.  
  806.  
  807. Thinkage Ltd.                           YAY Reference Manual
  808.  
  809.  
  810.  
  811. will  be   generated  automatically   if  necessary.  It  is
  812. perfectly valid to have an explicit
  813.  
  814.           %token UMINUS
  815.  
  816. if  you   want.     However,  it   must  precede  the  %left
  817. declaration.
  818.  
  819.     For a  more technical  discussion of  how precedence and
  820. binding rules affect a parser, see Chapter 8.
  821.  
  822.  
  823. _3_._1_._3_ _ _V_a_r_i_a_b_l_e_/_F_u_n_c_t_i_o_n_ _D_e_c_l_a_r_a_t_i_o_n_s
  824.  
  825.     The  declarations   section  may   contain  standard   C
  826. declarations for  variables and/or  functions  used  in  the
  827. actions specified  in the  grammar rules  section.  All such
  828. declarations should  be included in a block that begins with
  829. %{ and ends with %}.  For example,
  830.  
  831.           %{
  832.               int i, j, k;
  833.               static float x = 1.0;
  834.           %}
  835.  
  836. gives a  few variable  declarations.  These declarations are
  837. essentially transferred  "as is"  to the  _b_e_g_i_n_n_i_n_g  of  the
  838. source code  that is  produced by YAY.  This means that they
  839. will  be   external  to   "yyparse"  and   therefore  extern
  840. definitions.
  841.  
  842.  
  843. _3_._1_._4_ _ _S_u_m_m_a_r_y
  844.  
  845.     The source code produced by YAY contains the following.
  846.  
  847.   -- code from the declarations section
  848.   -- code given in the programs section
  849.   -- parsing tables produced by YAY to represent the grammar
  850.   -- the "yyparse" routine
  851.  
  852.  
  853. 33..22  GGrraammmmaarr RRuulleess
  854.  
  855.     A YAY grammar rule has the general form
  856.  
  857.           identifier : definition ;
  858.  
  859. A colon  separates the  definition from the identifier being
  860. defined.  A semicolon marks the end of the definition.
  861.  
  862.  
  863.  
  864.  
  865. November, 1995                                       Page 13
  866.  
  867.  
  868.  
  869. YAY Reference Manual                           Thinkage Ltd.
  870.  
  871.  
  872.  
  873.     The identifiers  defined in the grammar rule section are
  874. known as _n_o_n_-_t_e_r_m_i_n_a_l_ _s_y_m_b_o_l_s.  "Non-terminal" suggests that
  875. these symbols  aren't the  "end of the line".  Instead, they
  876. are made  up of smaller things: tokens or other non-terminal
  877. symbols.
  878.  
  879.     Here is  a simple  example of  the definition  of a non-
  880. terminal symbol.
  881.  
  882.           paren_expr : '(' expr ')' ;
  883.  
  884.     This  says  that  a  "paren_expr"  consists  of  a  left
  885. parenthesis, followed  by an  "expr", followed  by  a  right
  886. parenthesis.  The "expr" is either a token or a non-terminal
  887. symbol defined  in another  grammar rule.  This grammar rule
  888. could be  interpreted to say that a parenthesized expression
  889. consists of a normal expression inside parentheses.
  890.  
  891.     A non-terminal symbol may have more than one definition.
  892. For example, we might define "if" statements with
  893.  
  894.           if_stat : IF '(' expr ')' stat ;
  895.           if_stat : IF '(' expr ')' stat ELSE stat ;
  896.  
  897. This  definition   assumes  that  IF  and  ELSE  are  tokens
  898. recognized by  the lexical  analyzer (which  means that this
  899. parser's "yylex"  can recognize  keywords).   The definition
  900. also assumes that "expr" and "stat" are non-terminal symbols
  901. defined elsewhere.
  902.  
  903.     When a single symbol has more than one meaning, YAY lets
  904. you join the various possibilities into a single definition.
  905. Different meanings  are separated  by or-bars (|).  Thus you
  906. could write
  907.  
  908.           if_stat : IF '(' expr ')' stat
  909.                   | IF '(' expr ')' stat ELSE stat ;
  910.  
  911. This technique  is highly  recommended, since  it makes  YAY
  912. input more readable.
  913.  
  914.     Definitions in a grammar may be recursive.  For example,
  915.  
  916.           list : item
  917.                | list ',' item;
  918.  
  919. defines "list" to be one or more items separated by commas.
  920.  
  921.           intexp : '(' intexp ')'
  922.                  | intexp '+' intexp
  923.                  | intexp '-' intexp
  924.  
  925.  
  926.  
  927. Page 14                                       November, 1995
  928.  
  929.  
  930.  
  931. Thinkage Ltd.                           YAY Reference Manual
  932.  
  933.  
  934.  
  935.                  | intexp '*' intexp
  936.                  | intexp '/' intexp
  937.                  | INTNUM ;
  938.  
  939. says that  an integer  expression  can  be  another  integer
  940. expression in  parentheses, the  sum of integer expressions,
  941. the  difference  of  integer  expressions,  the  product  of
  942. integer expressions, the quotient of integer expressions, or
  943. an integer  number standing  on its  own (where  INTNUM is a
  944. token recognized by the lexical analyzer).
  945.  
  946.     In recursive  symbol definitions,  it is often useful to
  947. have the  empty string  as one  of the possible definitions.
  948. For example,
  949.  
  950.           program :
  951.                 /* the empty string */
  952.                 | statement ';' program ;
  953.  
  954. defines a  program as  zero or  more statements separated by
  955. semicolons.
  956.  
  957.     Our definition  of "list"  above was  an example of _l_e_f_t
  958. _r_e_c_u_r_s_i_o_n because  "list" was  on the  left in the recursive
  959. definition.   The definition  of "program" was an example of
  960. _r_i_g_h_t_ _r_e_c_u_r_s_i_o_n.   In  Section 9.6,  we discuss the pros and
  961. cons of the two types of recursion.
  962.  
  963.  
  964. _3_._2_._1_ _ _R_e_c_o_g_n_i_t_i_o_n_ _A_c_t_i_o_n_s
  965.  
  966.     In addition to defining what a non-terminal symbol is, a
  967. grammar rule  usually describes  what  to  do  if  the  non-
  968. terminal symbol  is encountered  in parser  input.   We call
  969. this a _r_e_c_o_g_n_i_t_i_o_n_ _a_c_t_i_o_n_.
  970.  
  971.     Recognition actions are specified as part of the grammar
  972. rule.     They  are   enclosed  in  brace  brackets  in  the
  973. definition, as in
  974.  
  975.           break_stat : BREAK ';'
  976.               { breakfn(); };
  977.  
  978. In this  definition, "break_stat"  is a  non-terminal symbol
  979. made  up  of  the  token  known  as  BREAK,  followed  by  a
  980. semicolon.   If this  symbol is  recognized, the parser will
  981. invoke a  function named  "breakfn".   Presumably this  is a
  982. user-defined function that handles a "break;" statement.
  983.  
  984.     Note that  a semicolon  is needed to mark the end of the
  985. definition even  though the  recognition action  ends  in  a
  986.  
  987.  
  988.  
  989. November, 1995                                       Page 15
  990.  
  991.  
  992.  
  993. YAY Reference Manual                           Thinkage Ltd.
  994.  
  995.  
  996.  
  997. brace bracket.   Programmers who are used to the way C works
  998. should bear this in mind.
  999.  
  1000.     For compatibility  with some  versions of YACC, YAY lets
  1001. you put  an equals  sign (=)  before the  opening brace that
  1002. begins a recognition action, as in
  1003.  
  1004.           break_stat : BREAK ';'
  1005.               = { breakfn(); };
  1006.  
  1007.     When a  symbol has more than one definition, a different
  1008. recognition action  may be  associated with each definition.
  1009. We will show some examples of this in a moment.
  1010.  
  1011.  
  1012. _3_._2_._2_ _ _T_o_k_e_n_ _a_n_d_ _S_y_m_b_o_l_ _V_a_l_u_e_s
  1013.  
  1014.     One of  the most common recognition actions is to return
  1015. a value.   For  example, if  an input  is recognized  as  an
  1016. expression to  be evaluated,  the parser  may want to return
  1017. the resulting  value of  the expression.  To return a value,
  1018. the recognition action merely assigns the value to a special
  1019. variable named $$.  For example,
  1020.  
  1021.           hexdigit : '0' { $$ = 0; }
  1022.                    | '1' { $$ = 1; }
  1023.                            ...
  1024.                    | 'A' { $$ = 10; }
  1025.                    | 'B' { $$ = 11; }
  1026.                    | 'C' { $$ = 12; }
  1027.                    | 'D' { $$ = 13; }
  1028.                    | 'E' { $$ = 14; }
  1029.                    | 'F' { $$ = 15; } ;
  1030.  
  1031. could be  a way  to convert  hexadecimal digits into numeric
  1032. values.   In this  case, "yylex"  just returns the digits it
  1033. finds and "yyparse" performs the actual conversion.
  1034.  
  1035.     Another common  recognition action  is to return a value
  1036. based on  one or  more of  the items  that make  up the non-
  1037. terminal symbol.   Inside  the recognition action, $1 stands
  1038. for the value of the first item in the symbol, $2 stands for
  1039. the value  of the  second item, and so on.  If the item is a
  1040. token, its  value is  the "yylval" value returned by "yylex"
  1041. when the  token was  read.   If  the  item  is  non-terminal
  1042. symbol, its  value is  the $$  value set  by the recognition
  1043. action associated with the symbol.  Thus we might write
  1044.  
  1045.  
  1046.  
  1047.  
  1048.  
  1049.  
  1050.  
  1051. Page 16                                       November, 1995
  1052.  
  1053.  
  1054.  
  1055. Thinkage Ltd.                           YAY Reference Manual
  1056.  
  1057.  
  1058.  
  1059.           intexp : '(' intexp ')'
  1060.                         {
  1061.                             $$ = $2;
  1062.                         }
  1063.                     /* value of parenthesized expression
  1064.                        is expression inside parentheses */
  1065.                  | intexp '+' intexp
  1066.                         {
  1067.                             $$ = $1 + $3 ;
  1068.                         }
  1069.                    /* value of addition is sum of two
  1070.                       expressions */
  1071.                  | intexp '-' intexp
  1072.                         {
  1073.                             $$ = $1 - $3 ;
  1074.                         }
  1075.                    /* value of subtraction is difference
  1076.                       of two expressions */
  1077.                  |  /* and so on */
  1078.                  ;
  1079.  
  1080. Note that this particular definition shows that each part of
  1081. a multiple  definition  may  have  a  different  recognition
  1082. action.
  1083.  
  1084.     In the  source code  for "yyparse",  this set of actions
  1085. will be  turned into a large sswwiittcchh statement.  The cases of
  1086. the sswwiittcchh will be the various possible recognition actions.
  1087.  
  1088.     If no  recognition action is specified for a definition,
  1089. the default is
  1090.  
  1091.           { $$ = $1 ; }
  1092.  
  1093. This action just returns the value of the first item (if the
  1094. item has a value).
  1095.  
  1096.  
  1097. _3_._2_._3_ _ _P_r_e_c_e_d_e_n_c_e_ _i_n_ _t_h_e_ _G_r_a_m_m_a_r_ _R_u_l_e_s
  1098.  
  1099.     In our discussion of the declarations section, we showed
  1100. how precedence  could be  assigned to  _o_p_e_r_a_t_o_r_s. Precedence
  1101. can also  be assigned  to _g_r_a_m_m_a_r_ _r_u_l_e_s_, and this is done in
  1102. the grammar input section.
  1103.  
  1104.     One way  to give  a grammar  rule a  precedence uses the
  1105. %prec construct.
  1106.  
  1107.           %prec TOKEN
  1108.  
  1109.  
  1110.  
  1111.  
  1112.  
  1113. November, 1995                                       Page 17
  1114.  
  1115.  
  1116.  
  1117. YAY Reference Manual                           Thinkage Ltd.
  1118.  
  1119.  
  1120.  
  1121. in a  grammar rule  indicates that  the rule should have the
  1122. same precedence as the specified token.
  1123.  
  1124.     As a  simple example,  consider the  case of  the  unary
  1125. minus operator.  Suppose our declaration section contains
  1126.  
  1127.           %left '+' '-'
  1128.           %left '*' '/'
  1129.           %left UMINUS
  1130.  
  1131. In the grammar rules section, we can write
  1132.  
  1133.           exp : exp '+' exp
  1134.               | exp '-' exp
  1135.               | exp '*' exp
  1136.               | exp '/' exp
  1137.               | '-' exp %prec UMINUS
  1138.               | /* and so on */
  1139.               ;
  1140.  
  1141. We could  not directly  set up  a precedence  for the  unary
  1142. minus, since  we had  already set  up a precedence for the -
  1143. token.  Instead, we created a token named UMINUS and gave it
  1144. the precedence we wanted to assign the unary minus.  When we
  1145. wrote out the grammar rule for the unary minus, we added
  1146.  
  1147.           %prec UMINUS
  1148.  
  1149. to show that this rule should have the precedence of UMINUS.
  1150.  
  1151.     As another example, we might set up precedence rules for
  1152. the right shift and left shift operations of C with
  1153.  
  1154.           %left RS LS
  1155.               ...
  1156.           exp :
  1157.               | exp '<' '<' exp %prec LS
  1158.               | exp '>' '>' exp %prec RS
  1159.               ...
  1160.  
  1161. In  this  way  we  give  the  shift  operations  the  proper
  1162. precedence and  avoid confusing  them  with  the  comparison
  1163. operations >  and <.  Of course, another way to resolve this
  1164. problem is  to make  the lexical  analyzer clever  enough to
  1165. recognize >>  and <<  and to  return the  RS  or  LS  tokens
  1166. directly.
  1167.  
  1168.     Although symbols  like UMINUS, LS, and RS are treated as
  1169. tokens, they  do not  have to  correspond to  actual  input.
  1170. They may  just be placeholders for operator tokens that have
  1171. two different meanings.
  1172.  
  1173.  
  1174.  
  1175. Page 18                                       November, 1995
  1176.  
  1177.  
  1178.  
  1179. Thinkage Ltd.                           YAY Reference Manual
  1180.  
  1181.  
  1182.  
  1183.  
  1184.     We should  note that the use of %prec is relatively rare
  1185. in YAY.   People don't usually think of %prec in their first
  1186. draft of  a grammar.   %prec  is only added in later drafts,
  1187. when it  is needed to resolve conflicts that appear when the
  1188. rules are run through YAY.
  1189.  
  1190.     If a  grammar rule  is not  assigned a  precedence using
  1191. %prec, the  precedence of  the rule  is taken  from the last
  1192. _t_o_k_e_n in the rule.  For example, if the rule is
  1193.  
  1194.           expr : expr '+' expr
  1195.  
  1196. the last  token in  the rule  is +  (since "expr"  is a non-
  1197. terminal symbol,  not a  token).  Thus the precedence of the
  1198. rule is the same as the precedence of +.
  1199.  
  1200.     If the  last token in a rule has no assigned precedence,
  1201. the rule  will not  have a  precedence.   This can result in
  1202. some surprises  if you  aren't careful.  For example, if you
  1203. define
  1204.  
  1205.           expr : expr '+' expr ';'
  1206.  
  1207. the last  token in  the rule is ; so the rule probably won't
  1208. have a precedence even if + does.
  1209.  
  1210.     A rule that contains no tokens cannot have a precedence.
  1211.  
  1212.  
  1213. _3_._2_._4_ _ _T_h_e_ _S_t_a_r_t_ _S_y_m_b_o_l
  1214.  
  1215.     The first  non-terminal  symbol  defined  in  the  rules
  1216. section is called the _s_t_a_r_t_ _s_y_m_b_o_l.  This symbol is taken to
  1217. be the  largest, most  general structure  described  by  the
  1218. grammar rules.   For  example, if  you  are  generating  the
  1219. parser for a compiler, the start symbol should describe what
  1220. a complete program looks like in the language to be parsed.
  1221.  
  1222.     If you do not want the first grammar rule to be taken as
  1223. the start symbol, you can use the directive
  1224.  
  1225.           %start NAME
  1226.  
  1227. in your rules section.  This indicates that the non-terminal
  1228. symbol named NAME is the start symbol.  NAME must be defined
  1229. somewhere in the rules section.
  1230.  
  1231.     The start  symbol must  be all-encompassing: every other
  1232. rule in the grammar must be related to the start symbol.  In
  1233. a sense,  the grammar  forms a "tree": the root is the start
  1234.  
  1235.  
  1236.  
  1237. November, 1995                                       Page 19
  1238.  
  1239.  
  1240.  
  1241. YAY Reference Manual                           Thinkage Ltd.
  1242.  
  1243.  
  1244.  
  1245. symbol, the  first set of branches are the symbols that make
  1246. up the  start symbol,  the next  set  of  branches  are  the
  1247. symbols that  make up  the first set, and so on.  Any symbol
  1248. that is  "outside"  this  tree  is  reported  as  a  _u_s_e_l_e_s_s
  1249. _v_a_r_i_a_b_l_e in  YAY output.   Useless  variables are ignored by
  1250. the parser  -- the  parser is  looking for  a complete start
  1251. symbol, and nothing else.
  1252.  
  1253.  
  1254. _3_._2_._5_ _ _T_h_e_ _E_n_d_ _M_a_r_k_e_r
  1255.  
  1256.     The end  of parser  input is  marked by  a special token
  1257. called the _e_n_d_ _m_a_r_k_e_r.  This token is often written as $end;
  1258. the value of the token is zero.
  1259.  
  1260.     It is  the job of the lexical analyzer "yylex" to return
  1261. a zero  to indicate  $end when  the end  of input is reached
  1262. (e.g. at  end of file, or at a keyword that indicates end of
  1263. input).
  1264.  
  1265.     "yyparse" terminates  when it  has parsed a start symbol
  1266. followed by the end marker.
  1267.  
  1268.  
  1269. _3_._2_._6_ _ _D_e_c_l_a_r_a_t_i_o_n_s_ _i_n_ _y_y_p_a_r_s_e
  1270.  
  1271.     You can  specify C  declarations that  will be  local to
  1272. "yyparse" in  much the  same way  that you  specify external
  1273. declarations in  the  Declarations  Section.    Enclose  the
  1274. declarations in %{ and %} symbols, as in
  1275.  
  1276.           %{
  1277.               /* External declaratios */
  1278.           %}
  1279.           %%
  1280.           /* Rules Section starts here */
  1281.           {%
  1282.               /* Declarations here will be
  1283.                  local to "yyparse" */
  1284.           %}
  1285.           /* Rules */
  1286.           %%
  1287.           /* Program section */
  1288.  
  1289. You may  also put  declarations at  the start of recognition
  1290. action code.
  1291.  
  1292.  
  1293.  
  1294.  
  1295.  
  1296.  
  1297.  
  1298.  
  1299. Page 20                                       November, 1995
  1300.  
  1301.  
  1302.  
  1303. Thinkage Ltd.                           YAY Reference Manual
  1304.  
  1305.  
  1306.  
  1307.  
  1308. 33..33  TThhee PPrrooggrraammss SSeeccttiioonn
  1309.  
  1310.     The programs  section of YAY input may contain functions
  1311. that should  be linked  in with  the "yyparse" routine.  YAY
  1312. itself does  nothing with  these functions -- it simply adds
  1313. the source  code on the end of the source code produced from
  1314. the grammar  rules.   In this  way,  the  functions  can  be
  1315. compiled at  the same  time that  the YAY-produced  code  is
  1316. compiled.
  1317.  
  1318.     Of course,  these additional functions could be compiled
  1319. separately and  linked with  the YAY-produced  code later on
  1320. (once everything  is  in  object  code  format).    Separate
  1321. compilation of  modules is  strongly recommended  for  large
  1322. parsers.   However, functions  that are  compiled separately
  1323. need a  special mechanism  if they want to use any manifests
  1324. that are  defined  in  the  YAY-produced  code,  and  it  is
  1325. sometimes simpler to make the program part of the YAY input.
  1326.  
  1327.     For example,  consider the  case of "yylex".  Every time
  1328. "yylex" obtains  a token  from  the  input,  it  returns  to
  1329. "yyparse" with  a value  that indicates  the type  of  token
  1330. found.   Obviously then, "yylex" and "yyparse" must agree on
  1331. which return  values indicate  which kind  of tokens.  Since
  1332. "yyparse" already  refers to tokens using manifest constants
  1333. (created  in   the  declarations  section  with  the  %token
  1334. directive), it  makes sense  for "yylex"  to  use  the  same
  1335. manifest constants.   The  lexical analyzer can do this very
  1336. easily if it is compiled along with "yyparse".
  1337.  
  1338.     Size might  be the determining factor.  With very simple
  1339. parsers, it's easier to put "yylex" in the Programs Section.
  1340. With larger  parsers, the advantages of separate compilation
  1341. are well worth the extra effort.
  1342.  
  1343.     If you  are going  to compile  "yylex" or other routines
  1344. separately from "yyparse", use the
  1345.  
  1346.           Header=file
  1347.  
  1348. option on  the YAY  command line.   YAY  will write  out the
  1349. manifest definitions  to the file of your choice.  This file
  1350. can then  be  #included  to  obtain  these  definitions  for
  1351. "yylex" or any other routine that needs them.  The manifests
  1352. are already  included in  the generated  parser code, so you
  1353. only need them for separately compiled modules.
  1354.  
  1355.  
  1356.  
  1357.  
  1358.  
  1359.  
  1360.  
  1361. November, 1995                                       Page 21
  1362.  
  1363.  
  1364.  
  1365. YAY Reference Manual                           Thinkage Ltd.
  1366.  
  1367.  
  1368.  
  1369.  
  1370. _3_._3_._1_ _ _T_h_e_ _L_e_x_i_c_a_l_ _A_n_a_l_y_z_e_r
  1371.  
  1372.     The lexical  analyzer "yylex"  reads input and breaks it
  1373. into tokens.  It is "yylex" that determines what constitutes
  1374. a token.   For  example, some  lexical analyzers  may return
  1375. numbers one  digit at a time while others collect numbers in
  1376. their entirety before passing them to the parser.
  1377.  
  1378.     Similarly, some lexical analyzers may recognize keywords
  1379. such as  IF or  WHILE and  will tell  the parser  that an IF
  1380. token or  WHILE token  has been  found.   Others may  not be
  1381. designed to  recognize keywords,  so it  is up to the parser
  1382. itself to distinguish between keywords and other things like
  1383. variable names.
  1384.  
  1385.     As noted  before, each  token named  in the declarations
  1386. section of  the YAY  input is set up as a manifest constant.
  1387. The value  of the first token named is 257, the value of the
  1388. next is  258, and  so on.   You can also set your own values
  1389. for tokens  by placing  a positive  integer after  the first
  1390. appearance of  any token  in the  declarations section.  For
  1391. example,
  1392.  
  1393.           %token AA 56
  1394.  
  1395. assigns a  value of  56 to  the manifest  (token) symbol AA.
  1396. This mechanism  is very seldom needed, and we recommend that
  1397. users avoid it whenever possible.
  1398.  
  1399.     There is  little else  to  say  about  requirements  for
  1400. "yylex".   If it  wishes to  return the  value of a token as
  1401. well as  an indication of its type, the value is assigned to
  1402. the external  variable "yylval".   By  default, "yylval"  is
  1403. defined as  an iinntt  value but  it can  also be  used to hold
  1404. other types  of values.    For  more  information,  see  the
  1405. description of %union in Chapter 7.
  1406.  
  1407.  
  1408.  
  1409.  
  1410.  
  1411.  
  1412.  
  1413.  
  1414.  
  1415.  
  1416.  
  1417.  
  1418.  
  1419.  
  1420.  
  1421.  
  1422.  
  1423. Page 22                                       November, 1995
  1424.  
  1425.  
  1426.  
  1427. Thinkage Ltd.                           YAY Reference Manual
  1428.  
  1429.  
  1430.  
  1431.  
  1432.                    44.. IInntteerrnnaall SSttrruuccttuurreess
  1433.  
  1434.     In order  to use  YAY  effectively,  it  is  helpful  to
  1435. understand some  of the internal workings of the parser that
  1436. YAY produces.   In  this chapter,  we will  look at  some of
  1437. these structures.
  1438.  
  1439.     To give  us  a  point  of  reference,  suppose  we  have
  1440. produced a parser with grammar
  1441.  
  1442.           %token NUM
  1443.           %left '+' '-'
  1444.           %left '*' '/'
  1445.           %%
  1446.           expr : NUM
  1447.                | expr '+' expr
  1448.                | expr '-' expr
  1449.                | expr '*' expr
  1450.                | expr '/' expr
  1451.                | '(' expr ')'
  1452.                ;
  1453.  
  1454.  
  1455. 44..11  SSttaatteess
  1456.  
  1457.     As the  parser reads  in token  after token, it switches
  1458. between various  _s_t_a_t_e_s.   You can think of a state as point
  1459. where the parser says, "I have read _t_h_i_s particular sequence
  1460. of input  tokens and  now I  am looking  for  one  of  _t_h_e_s_e
  1461. tokens."
  1462.  
  1463.     For example,  a parser  for the C language might be in a
  1464. state where it has finished reading a complete statement and
  1465. is ready  for the  start of  a new  statement.  It therefore
  1466. expects some  token that  can legitimately start a statement
  1467. (e.g. a  keyword like IF or WHILE, or the name of a variable
  1468. for an assignment).
  1469.  
  1470.     In this state, it reads a token.  Say it finds the token
  1471. corresponding to  the keyword IF.  It then switches to a new
  1472. state where it says "I have seen an IF and now I want to see
  1473. the (  that begins  the IF condition."  When it finds the (,
  1474. it switches again to a state that says "I have found IF( and
  1475. now I want the start of a condition expression."
  1476.  
  1477.     States break  the parsing process into simple steps.  At
  1478. each step,  the parser knows what it has seen and what it is
  1479. looking for next.
  1480.  
  1481.  
  1482.  
  1483.  
  1484.  
  1485. November, 1995                                       Page 23
  1486.  
  1487.  
  1488.  
  1489. YAY Reference Manual                           Thinkage Ltd.
  1490.  
  1491.  
  1492.  
  1493.     YAY assigns  numbers to  every possible state the parser
  1494. can enter.   The  0th state is always the one that describes
  1495. the parser's  condition before it has read any input.  Other
  1496. states are numbered arbitrarily.
  1497.  
  1498.     Sometimes a  particular input  can only  be the start of
  1499. one construct.   For  example, the FOR keyword in C can only
  1500. be the  start of a FOR statement, and the FOR statement only
  1501. has one form.
  1502.  
  1503.     On the  other hand,  a grammar  may  have  several  non-
  1504. terminal symbols  that start  the same  way.   In our sample
  1505. grammar, all of
  1506.  
  1507.           expr '+' expr
  1508.           expr '-' expr
  1509.           expr '*' expr
  1510.           expr '/' expr
  1511.  
  1512. start with  an "expr".   If  the parser finds that the input
  1513. begins with  an "expr",  the parser  has no  idea which rule
  1514. matches the  input until  it has read the operator following
  1515. the first "expr".
  1516.  
  1517.     The parser  chooses which  state it  will enter  next by
  1518. looking at  the next  input token.  This token is called the
  1519. _l_o_o_k_a_h_e_a_d_ _s_y_m_b_o_l for that state.
  1520.  
  1521.  
  1522. 44..22  DDiiaaggrraammmmiinngg SSttaatteess
  1523.  
  1524.     YAY uses  simple diagrams to describe the various states
  1525. of the parser.  These diagrams show what the parser has seen
  1526. and what  it is looking for next.  The diagrams are given in
  1527. the Parser  Description report  prouced by  YAY (see Chapter
  1528. 6).
  1529.  
  1530.     For example,  consider the  state where  the parser  has
  1531. just read  a complete  "expr" at  the beginning  of a larger
  1532. expression.   It is  now in  a state where it expects to see
  1533. one of  the operators  +, -,  *, or  /, or  perhaps the $end
  1534. marker indicating the end of input.  YAY diagrams this state
  1535. as
  1536.  
  1537.           $accept:  expr.$end
  1538.           expr:     expr.'+' expr
  1539.           expr:     expr.'-' expr
  1540.           expr:     expr.'*' expr
  1541.           expr:     expr.'/' expr
  1542.  
  1543.  
  1544.  
  1545.  
  1546.  
  1547. Page 24                                       November, 1995
  1548.  
  1549.  
  1550.  
  1551. Thinkage Ltd.                           YAY Reference Manual
  1552.  
  1553.  
  1554.  
  1555. This lists  the possible  grammar constructs that the parser
  1556. may be  working on.   (The first line $accept stands for the
  1557. Start symbol.)   The  "." indicates  how much the parser has
  1558. read so far.
  1559.  
  1560.     If the  lookahead symbol is *, the parser will switch to
  1561. a state diagrammed by
  1562.  
  1563.           expr:     expr '*'.expr
  1564.  
  1565. In this  state, the parser knows that the next thing to come
  1566. will be  another "expr".   This  means that  the only  valid
  1567. tokens that  can be  read next are ( or NUM, since those are
  1568. the only things that start a valid "expr".
  1569.  
  1570.  
  1571. 44..33  SSttaattee AAccttiioonnss
  1572.  
  1573.     There are  several possible  actions that the parser can
  1574. take in a state:
  1575.  
  1576. (a)  _a_c_c_e_p_t the input;
  1577.  
  1578. (b)  _s_h_i_f_t to a new state;
  1579.  
  1580. (c)  _r_e_d_u_c_e one  or more  input  tokens  to  a  single  non-
  1581.      terminal symbol, according to a grammar rule;
  1582.  
  1583. (d)  _g_o_t_o a new state;
  1584.  
  1585. (e)  raise an _e_r_r_o_r condition.
  1586.  
  1587. In order  to decide  which action to take, the parser checks
  1588. the lookahead  symbol (except in states where the parser can
  1589. only take  one possible  action so  the lookahead  symbol is
  1590. irrelevant).
  1591.  
  1592.     This means that a typical state has a series of possible
  1593. actions based  upon the  possible values  of  the  lookahead
  1594. symbol.  In YAY output, you might see
  1595.  
  1596.           '+'   shift 8
  1597.           '-'   shift 7
  1598.           '*'   shift 6
  1599.           '/'   shift 5
  1600.           ')'   shift 9
  1601.            .    error
  1602.  
  1603. This says  that if  the parser  is in  this  state  and  the
  1604. lookahead symbol is +, the parser will shift to State 8.  If
  1605.  
  1606.  
  1607.  
  1608.  
  1609. November, 1995                                       Page 25
  1610.  
  1611.  
  1612.  
  1613. YAY Reference Manual                           Thinkage Ltd.
  1614.  
  1615.  
  1616.  
  1617. the lookahead symbol is -, the parser will shift to State 7,
  1618. and so on.
  1619.  
  1620.     The "." in the final line stands for any other token not
  1621. mentioned in  the preceding  list. If  the parser  finds any
  1622. unexpected tokens in this particular state, it will take the
  1623. error action.
  1624.  
  1625.     The sections  that follow  explain precisely  what  each
  1626. state action  means and what the parser does to handle these
  1627. actions.
  1628.  
  1629.  
  1630. _4_._3_._1_ _ _T_h_e_ _A_c_c_e_p_t_ _A_c_t_i_o_n
  1631.  
  1632.     The Accept  action only  happens when the parser is in a
  1633. state that  indicates it  has seen  a complete input and the
  1634. lookahead symbol  is the  end marker  $end.  When the parser
  1635. takes the  Accept action, "yyparse" terminates and returns a
  1636. zero to indicate that the input was correct.
  1637.  
  1638.  
  1639. _4_._3_._2_ _ _T_h_e_ _S_h_i_f_t_ _A_c_t_i_o_n
  1640.  
  1641.     The Shift  action happens  when the  parser is  part way
  1642. through a  grammar construct and a new token is read in.  As
  1643. an example, State 4 in our sample parser is diagrammed with
  1644.  
  1645.           expr:     expr.'+' expr
  1646.           expr:     expr.'-' expr
  1647.           expr:     expr.'*' expr
  1648.           expr:     expr.'/' expr
  1649.           expr:     '(' expr.')'
  1650.  
  1651.           '+'   shift 8
  1652.           '-'   shift 7
  1653.           '*'   shift 6
  1654.           '/'   shift 5
  1655.           ')'   shift 9
  1656.            .    error
  1657.  
  1658. This shows  that the  parser will  shift  to  various  other
  1659. states depending  on the value of the lookahead symbol.  For
  1660. example, if  the lookahead  symbol is * the parser shifts to
  1661. State 6 which has the diagram
  1662.  
  1663.  
  1664.  
  1665.  
  1666.  
  1667.  
  1668.  
  1669.  
  1670.  
  1671. Page 26                                       November, 1995
  1672.  
  1673.  
  1674.  
  1675. Thinkage Ltd.                           YAY Reference Manual
  1676.  
  1677.  
  1678.  
  1679.           expr:     expr '*'.expr
  1680.  
  1681.           NUM   shift 2
  1682.           '('   shift 1
  1683.            .    error
  1684.  
  1685.           expr  goto 11
  1686.  
  1687. In this  new state,  the parser  has further  shifts it  can
  1688. make, depending on the next lookahead symbol.
  1689.  
  1690.     When the  parser shifts  to a  new state,  it saves  the
  1691. previous state on a stack called the _s_t_a_t_e_ _s_t_a_c_k.  The stack
  1692. provides a  history of the states that the parser has passed
  1693. through while  it was  reading input.   It is also a control
  1694. mechanism as will be seen later in this chapter.
  1695.  
  1696.     Paralleling the  state  stack  is  a  _v_a_l_u_e  stack  that
  1697. records  the  values  of  tokens  and  non-terminal  symbols
  1698. encountered while  parsing.   The value  of a  token is  the
  1699. "yylval" value returned by "yylex" at the time the token was
  1700. read.   The value  of a  non-terminal symbol is the $$ value
  1701. set by  the recognition action associated with that symbol's
  1702. definition.   If the  definition didn't  have  an  associate
  1703. recognition action,  the value of the symbol is the value of
  1704. the first item in the symbol's definition.
  1705.  
  1706.     At the  same time  that  the  Shift  action  pushes  the
  1707. current state  onto the  state stack,  it  also  pushes  the
  1708. "yylval" value  of the  lookahead symbol  (token)  onto  the
  1709. value stack.
  1710.  
  1711.  
  1712. _4_._3_._3_ _ _T_h_e_ _R_e_d_u_c_e_ _A_c_t_i_o_n
  1713.  
  1714.     The Reduce action takes place in states where the parser
  1715. has recognized  all the  items that  make up  a non-terminal
  1716. symbol.   For example,  the diagram of State 9 in our sample
  1717. grammar is
  1718.  
  1719.           expr:     '(' expr ')'.
  1720.  
  1721.            .    reduce (6)
  1722.  
  1723. At this point, the parser has seen all three components that
  1724. make up the non-terminal symbol "expr":
  1725.  
  1726.           '('
  1727.           expr
  1728.           ')'
  1729.  
  1730.  
  1731.  
  1732.  
  1733. November, 1995                                       Page 27
  1734.  
  1735.  
  1736.  
  1737. YAY Reference Manual                           Thinkage Ltd.
  1738.  
  1739.  
  1740.  
  1741. As the line
  1742.  
  1743.            .    reduce (6)
  1744.  
  1745. shows, it  doesn't matter  what the  lookahead symbol  is at
  1746. this point.   The  non-terminal symbol  has been recognized,
  1747. and the parser is ready for a Reduce action.  (Note that the
  1748. (6) in  the above  line  just  means  that  the  parser  has
  1749. recognized the  non-terminal symbol  defined in  rule (6) of
  1750. the grammar.   We  will say  more  about  this  in  a  later
  1751. chapter.)
  1752.  
  1753.     The Reduce  action  performs  a  number  of  operations.
  1754. First,  it  pops  states  off  the  state  stack.    If  the
  1755. recognized non-terminal symbol had N components, a reduction
  1756. pops N-1  states off  the stack.  In other words, the parser
  1757. goes back  to the  state it  was in  when it  first began to
  1758. gather the recognized construct.
  1759.  
  1760.     Next, the Reduce action pops values off the value stack.
  1761. If the  definition that  is being  reduced  consisted  of  N
  1762. items, the  Reduce action conceptually pops N values off the
  1763. stack.   The topmost  value on  the stack is assigned to $N,
  1764. the next to $N-1, and so on down to $1.
  1765.  
  1766.     Once the  Reduce action  has gathered all the $X values,
  1767. the  parser   invokes  the   recognition  action   that  was
  1768. associated with  the  grammar  rule  being  reduced.    This
  1769. recognition will  use the  $X values  to come  up with  a $$
  1770. value for  the non-terminal  symbol.   This value  is pushed
  1771. onto the  value stack,  thereby replacing  the N values that
  1772. were previously on the stack.
  1773.  
  1774.     If the non-terminal symbol had no recognition action, or
  1775. if the  recognition action  did not  set $$, the parser puts
  1776. the value  of $1  back on the stack.  (In reality, the value
  1777. is never popped off.)
  1778.  
  1779.     Lastly, the  Reduce action  sets things  up so that  the
  1780. lookahead symbol  seems to  be the  non-terminal symbol that
  1781. was just  recognized.   For example,  it may  say  that  the
  1782. lookahead symbol is now an "expr" instead of a token.
  1783.  
  1784.  
  1785. _4_._3_._4_ _ _T_h_e_ _G_o_t_o_ _A_c_t_i_o_n
  1786.  
  1787.     The Goto action is a continuation of the Reduce process.
  1788. Goto is  almost the  same as Shift -- the only difference is
  1789. that the  Goto action  takes place when the lookahead symbol
  1790. is a  non-terminal symbol while a Shift takes place when the
  1791. lookahead symbol is a token.
  1792.  
  1793.  
  1794.  
  1795. Page 28                                       November, 1995
  1796.  
  1797.  
  1798.  
  1799. Thinkage Ltd.                           YAY Reference Manual
  1800.  
  1801.  
  1802.  
  1803.  
  1804.     For example, State 6 in our sample grammar reads
  1805.  
  1806.           expr:    expr '*'.expr
  1807.  
  1808.           NUM   shift 2
  1809.           '('   shift 1
  1810.            .    error
  1811.  
  1812.           expr  goto 12
  1813.  
  1814. The first  time the  parser enters this state, the lookahead
  1815. symbol will  be a  token and  the parser  will Shift  on the
  1816. token into  some state  where it  will begin  to  gather  an
  1817. "expr".   When it  has a  complete "expr", it will perform a
  1818. Reduce action  that will  return to  this state  and set the
  1819. lookahead symbol  to "expr".   Now  when the  parser has  to
  1820. decide what  to do  next, it  sees that it has an "expr" for
  1821. the lookahead symbol and therefore takes the Goto action and
  1822. moves to State 12.
  1823.  
  1824.     The Shift action pushes the current state onto the state
  1825. stack.   The Goto  does not have to do this -- the state was
  1826. on the  stack already.  Similarly, Shift pushes a value onto
  1827. the  value  stack,  but  Goto  does  not,  since  the  value
  1828. corresponding to  the non-terminal symbol was already put on
  1829. the value stack by the Reduce action.
  1830.  
  1831.     When the  parser reaches  the new  state, the  lookahead
  1832. symbol will  be restored  to whatever  it was at the time of
  1833. the Reduce action.
  1834.  
  1835.     Essentially then,  a Goto is like a Shift except that it
  1836. takes place  when you  come _b_a_c_k  to a state with the Reduce
  1837. action.   Also, a  Shift is  based on  the value of a single
  1838. input token while a Goto is based on a non-terminal symbol.
  1839.  
  1840.  
  1841. _4_._3_._5_ _ _T_h_e_ _E_r_r_o_r_ _A_c_t_i_o_n
  1842.  
  1843.     The parser takes the Error action when it encounters any
  1844. input token  which cannot  validly appear  in  a  particular
  1845. input location.   When  this happens,  the parser raises the
  1846. "error"  condition.    Since  error-handling  can  be  quite
  1847. complicated, we will devote the whole of the next chapter to
  1848. the subject.
  1849.  
  1850.  
  1851.  
  1852.  
  1853.  
  1854.  
  1855.  
  1856.  
  1857. November, 1995                                       Page 29
  1858.  
  1859.  
  1860.  
  1861. YAY Reference Manual                           Thinkage Ltd.
  1862.  
  1863.  
  1864.  
  1865.  
  1866.                      55.. EErrrroorr--HHaannddlliinngg
  1867.  
  1868.     If a  piece of  input is  invalid,  the  parser  can  do
  1869. nothing with  it.   Except in  extreme cases, however, it is
  1870. inappropriate for  the parser to stop all processing as soon
  1871. as an  error is found.  Instead, the parser should skip over
  1872. the invalid input and resume parsing as soon after the error
  1873. as possible.   In  this way, the parser can find many syntax
  1874. errors in  one pass  through  the  input,  saving  time  and
  1875. trouble for the user.
  1876.  
  1877.     YAY therefore  tries  to  generate  a  parser  that  can
  1878. "restart" as  soon as  possible after  an error occurs.  YAY
  1879. does this  by letting you specify points at which the parser
  1880. can pick up after errors.  You may also dictate what special
  1881. processing should  take place  if an error is encountered at
  1882. one of these points.
  1883.  
  1884.  
  1885. 55..11  TThhee ""eerrrroorr"" SSyymmbbooll
  1886.  
  1887.     YAY's error handling facilities use the keyword eerrrroorr to
  1888. signify an  erroneous input.   As a result, eerrrroorr may not be
  1889. used as  the name  of a  user-defined token  or non-terminal
  1890. symbol.
  1891.  
  1892.     You should put "eerrrroorr" in your grammar rules where error
  1893. recovery might take place.  For example, you might write
  1894.  
  1895.           statement: error
  1896.               | /* other definitions of a statement */;
  1897.  
  1898. This tells YAY that errors may occur in statements, and that
  1899. after an error, the parser is free to restart parsing at the
  1900. end of a complete statement.
  1901.  
  1902.  
  1903. 55..22  TThhee EErrrroorr CCoonnddiittiioonn
  1904.  
  1905.     As noted  in the  last chapter,  YAY will take the Error
  1906. action if  it  finds  an  input  that  is  not  valid  in  a
  1907. particular location.   The  Error action  has the  following
  1908. steps.
  1909.  
  1910. (a)  See if  the current state has a Shift action associated
  1911.      with the  eerrrroorr symbol.   If  it does,  shift  on  this
  1912.      action.
  1913.  
  1914. (b)  If the  current state has no such action, pop the state
  1915.      off the  stack and  check the next state.  Also pop off
  1916.  
  1917.  
  1918.  
  1919. Page 30                                       November, 1995
  1920.  
  1921.  
  1922.  
  1923. Thinkage Ltd.                           YAY Reference Manual
  1924.  
  1925.  
  1926.  
  1927.      the top  value on  the value  stack, so  that the state
  1928.      stack and value stack stay in synch.
  1929.  
  1930. (c)  Repeat (b)  until the  parser finds  a state  that  can
  1931.      shift on the eerrrroorr symbol.
  1932.  
  1933. (d)  Take the Shift action associated with the eerrrroorr symbol.
  1934.      Note that  this pushes  the current state on the stack,
  1935.      i.e. the  state that is capable of handling errors.  No
  1936.      new value  is pushed onto the value stack -- the parser
  1937.      keeps whatever  value was  already associated  with the
  1938.      state that can handle errors.
  1939.  
  1940.     When the  parser shifts out of the state that can handle
  1941. errors, the  lookahead symbol  will be whatever token caused
  1942. the error  condition in  the first  place.   The parser will
  1943. then try to proceed with normal processing.
  1944.  
  1945.     Of course,  it  is  quite  possible  that  the  original
  1946. lookahead symbol  is invalid  in the  new context.   If  the
  1947. lookahead symbol  causes an error again, it is discarded and
  1948. the error  condition stays  in  effect.    The  parser  will
  1949. continue to  read new tokens and discard them until it finds
  1950. a token  that can validly follow the eerrrroorr.  The parser will
  1951. then take  whatever action  is  associated  with  the  valid
  1952. token.
  1953.  
  1954.     In a  typical grammar,  the state that has been handling
  1955. errors will  eventually be  popped off the stack in a Reduce
  1956. operation.
  1957.  
  1958.     Notice that the parser always Shifts on the error token.
  1959. It will  never Reduce  on eerrrroorr,  even if  the grammar has a
  1960. state where eerrrroorr is associated with a Reduce action.
  1961.  
  1962.     In some  situations, an  error condition  will be raised
  1963. and the  parser will  pop all  the way  to the bottom of the
  1964. state stack  without finding  a state  that can  handle  the
  1965. eerrrroorr  symbol.    For  example,  the  grammar  may  have  no
  1966. provisions for  error  recovery.  In  this  case,  "yyparse"
  1967. simply terminates and returns a 1 to its caller.
  1968.  
  1969.  
  1970. 55..33  EExxaammpplleess
  1971.  
  1972.     As a simple example, consider a parser for a simple desk
  1973. calculator.   All statements  end in  a semicolon.   Thus we
  1974. might see the rule
  1975.  
  1976.  
  1977.  
  1978.  
  1979.  
  1980.  
  1981. November, 1995                                       Page 31
  1982.  
  1983.  
  1984.  
  1985. YAY Reference Manual                           Thinkage Ltd.
  1986.  
  1987.  
  1988.  
  1989.           statement : var '=' expr ';'
  1990.                     | expr ';'
  1991.                     | error ';'
  1992.                     ;
  1993.  
  1994. When an  error occurs  in input,  the parser  will pop  back
  1995. through the  state stack until it comes to a state where the
  1996. eerrrroorr symbol is recognized.  For example, the state might be
  1997. diagrammed as
  1998.  
  1999.           $accept:   .statement $end
  2000.  
  2001.           error  shift 2
  2002.           NUM    shift 4
  2003.           .      error
  2004.  
  2005.           var       goto 7
  2006.           expr      goto 3
  2007.           statement goto 5
  2008.  
  2009. If an  error occurs  anywhere in  an  input  statement,  the
  2010. parser will  pop back  to this state, then Shift to State 2.
  2011. State 2 will look like
  2012.  
  2013.           statement:   error.';'
  2014. .
  2015.           ';'   shift 6
  2016.            .    error
  2017.  
  2018. In other  words, the  next token must be a semicolon.  If it
  2019. isn't, another  error occurs.   The  parser pops back to the
  2020. previous state  and takes the eerrrroorr shift again.  Input will
  2021. be discarded  token by  token until  a semicolon  is  found.
  2022. When the  semicolon is  found, the  parser will  be able  to
  2023. shift from State 2 to State 6 which is
  2024.  
  2025.           statement:  error ';'.
  2026.  
  2027.            .    reduce (3)
  2028.  
  2029. The erroneous  line is reduced to a "statement" non-terminal
  2030. symbol.
  2031.  
  2032.     Now this  example is  simple, but  it has its drawbacks.
  2033. It will  get you into trouble if the grammar has any concept
  2034. of block structure or parenthesization.  Why?  Once an error
  2035. occurs, the rule
  2036.  
  2037.           statement : error ';'
  2038.  
  2039.  
  2040.  
  2041.  
  2042.  
  2043. Page 32                                       November, 1995
  2044.  
  2045.  
  2046.  
  2047. Thinkage Ltd.                           YAY Reference Manual
  2048.  
  2049.  
  2050.  
  2051. effectively  tells   the  parser   to   discard   absolutely
  2052. everything until  it finds  a ;  character.   If you  have a
  2053. parser for  C, for  example, it  would skip  over  important
  2054. characters like  ) or  } until  it found  a semicolon.  Your
  2055. parentheses and  braces would be out of balance for the rest
  2056. of the  input and the whole parsing process would be a waste
  2057. of time.   The same principle applies to any rule that shows
  2058. the eerrrroorr  token followed  by some other non-null symbol: it
  2059. can lead to hopeless confusion in a lot of grammars.
  2060.  
  2061.     It is safer to write the rule in a form like
  2062.  
  2063.           statement : error
  2064.                     | ';'
  2065.                     | /* other stuff */
  2066.  
  2067.     In this  case, the  eerrrroorr token  only  matches  material
  2068. until the  parser finds  something else  it recognizes (e.g.
  2069. the semicolon).   Once this happens, the eerrrroorr state will be
  2070. reduced to  a "statement"  symbol and  popped off the stack.
  2071. Parsing can then proceed as usual.
  2072.  
  2073.  
  2074. 55..44  EErrrroorr RReeccooggnniittiioonn AAccttiioonnss
  2075.  
  2076.     The easiest  way to  generate an  error  message  is  to
  2077. associate a  recognition action  with the  grammar rule that
  2078. recognizes the error.  You can do something simple like
  2079.  
  2080.           statement: error
  2081.               {
  2082.                   printf("You made an error!\n");
  2083.               }
  2084.  
  2085. or you can be fancier, as in
  2086.  
  2087.           line: error '\n' prompt line
  2088.               { $$ = $4; };
  2089.           prompt: /* null token */
  2090.               { printf("Please re-enter line.\n"); };
  2091.  
  2092.     If an  error occurs,  the parser  skips until it finds a
  2093. new-line character.  After the new-line, it will always find
  2094. a null  token matching  "prompt", and the recognition action
  2095. for "prompt" will print out the message
  2096.  
  2097.           Please re-enter line
  2098.  
  2099. The final  symbol in  the rule  is another  "line", and  the
  2100. action after  the eerrrroorr  rule shows  that the  result of the
  2101.  
  2102.  
  2103.  
  2104.  
  2105. November, 1995                                       Page 33
  2106.  
  2107.  
  2108.  
  2109. YAY Reference Manual                           Thinkage Ltd.
  2110.  
  2111.  
  2112.  
  2113. rule ($$)  should be the material associated with the second
  2114. input line.
  2115.  
  2116.     All this means that if the user makes a mistake entering
  2117. an input  line, the  parser prints  out an error message and
  2118. accepts a  second input  line in  place of  the first.  This
  2119. allows for an interactive user to correct an input line that
  2120. was incorrectly typed the first time.
  2121.  
  2122.     Of course,  this set-up  will  only  work  if  the  user
  2123. doesn't make an error the second time the line is typed too.
  2124. If the  next token  he or  she types  is also  invalid,  the
  2125. parser will  discard the  token and  decide that  it's still
  2126. gobbling up the original error.
  2127.  
  2128.  
  2129. 55..55  TThhee yyyycclleeaarriinn MMaaccrroo
  2130.  
  2131.     After an  Error action,  the  parser  will  restore  the
  2132. lookahead symbol  to the  value it had at the time the error
  2133. was detected.  However, this is sometimes undesirable.
  2134.  
  2135.     For example,  your grammar may have a recognition action
  2136. associated with  the eerrrroorr  symbol and this may read through
  2137. the next  lot of  input until  it finds the next sure-to-be-
  2138. valid data.   If  this happens, you certainly don't want the
  2139. parser to  pick up the old lookahead symbol again once error
  2140. recovery is finished.
  2141.  
  2142.     If you  want the  parser to throw away the old lookahead
  2143. symbol after an error, put
  2144.  
  2145.           yyclearin ;
  2146.  
  2147. in the  recognition action associated with the eerrrroorr symbol.
  2148. "yyclearin" is  a macro that expands into code that discards
  2149. the lookahead symbol.
  2150.  
  2151.  
  2152. 55..66  TThhee yyyyeerrrroorr FFuunnccttiioonn
  2153.  
  2154.     The first  thing the  parser does  when it  performs the
  2155. Error action  is to  call a  function named "yyerror".  This
  2156. happens _b_e_f_o_r_e  the parser begins going down the state stack
  2157. in search  of a  state that  can handle  the  eerrrroorr  symbol.
  2158. "yyerror" must be supplied by the user -- note that its name
  2159. is in lower case.
  2160.  
  2161.     The  simplest   "yyerror"  functions  either  abort  the
  2162. parsing job  or just  return so  that the parser can perform
  2163. its standard error handling.
  2164.  
  2165.  
  2166.  
  2167. Page 34                                       November, 1995
  2168.  
  2169.  
  2170.  
  2171. Thinkage Ltd.                           YAY Reference Manual
  2172.  
  2173.  
  2174.  
  2175.  
  2176.     The  "yyerror"   function  is  passed  one  argument:  a
  2177. character string describing the type of error that just took
  2178. place.  This string is almost always
  2179.  
  2180.           "Syntax error"
  2181.  
  2182. The only other argument strings that might be passed are
  2183.  
  2184.           "Not enough space for parser stacks"
  2185.           "Parser stack overflow"
  2186.  
  2187. which are  used when  the parser  runs out of memory for the
  2188. state stack.
  2189.  
  2190.     Once "yyerror"  returns to  "yyparse", the  parser  will
  2191. proceed popping down the stack in search of a state that can
  2192. handle errors.
  2193.  
  2194.     If another  error is  encountered soon  after the first,
  2195. "yyerror" will  _n_o_t be  called again.   The parser considers
  2196. itself to be in a "potential error" situation until it finds
  2197. three correct  tokens in a row.  This avoids the torrents of
  2198. error messages  that often occur as the parser wades through
  2199. input in search of some recognizable sequence.
  2200.  
  2201.     Once the parser has found three correct tokens in a row,
  2202. it leaves  the "potential  error" situation.  If a new error
  2203. is found later on, "yyerror" will be called again.
  2204.  
  2205.  
  2206. _5_._6_._1_ _ _C_h_a_n_g_i_n_g_ _y_y_c_h_a_r_ _i_n_ _y_y_e_r_r_o_r
  2207.  
  2208.     The "yyerror"  function may change the value of "yychar"
  2209. (the variable  that indicates the type of token just read by
  2210. "yylex").   If "yyerror"  does this,  "yyparse"  immediately
  2211. gets rid of the error condition and tries to make a shift or
  2212. reduce using  the new  "yychar" token.   If there is a valid
  2213. action that  can be  taken, "yyparse" will proceed as if the
  2214. error never happened.
  2215.  
  2216.     This behavior  can help you deal with at least two kinds
  2217. of unusual situations:
  2218.  
  2219. (a)  When "yyerror"  is attempting  to correct  a problem by
  2220.      supplying the  correct input.   For  example, it may be
  2221.      possible to  determine  what  input  should  have  been
  2222.      received; the  classic example  is a compiler which can
  2223.      figure out  that a  particular  statement  should  have
  2224.      ended in  a semicolon.   In  this case,  "yyerror"  can
  2225.      supply  the   missing   semicolon   by   assigning   an
  2226.  
  2227.  
  2228.  
  2229. November, 1995                                       Page 35
  2230.  
  2231.  
  2232.  
  2233. YAY Reference Manual                           Thinkage Ltd.
  2234.  
  2235.  
  2236.  
  2237.      appropriate value  to "yychar".   If  "yyerror" guessed
  2238.      correctly, action  can proceed as if the problem didn't
  2239.      occur.
  2240.  
  2241. (b)  When a particular token can be interpreted in different
  2242.      ways in  different contexts.  For example, suppose that
  2243.      X can be a keyword in some contexts and a variable name
  2244.      in others.   You  can write  "yylex" so  that it always
  2245.      interprets X  as a  keyword.   If "yyerror"  is invoked
  2246.      because  that   keyword  is  invalid  in  a  particular
  2247.      context, "yyerror"  can change  "yychar" and see if the
  2248.      input is  valid when  X is  interpreted as  a  variable
  2249.      name.
  2250.  
  2251.     If "yyerror"  changes "yychar",  "yyerror" may  have  to
  2252. inform "yylex"  of the  situation so that "yylex" can return
  2253. the proper input token the next time it is called.
  2254.  
  2255.  
  2256. 55..77  TThhee yyyyeerrrrffllaagg VVaarriiaabbllee
  2257.  
  2258.     "yyerrflag" is  an external integer variable whose value
  2259. must be  0, 1,  2, or  3.   YYABORT (described  in  a  later
  2260. section) is called if "yyerrflag" does not have one of these
  2261. values.
  2262.  
  2263.     As we  mentioned earlier,  "yyparse" doesn't  leave  its
  2264. error state  until three  consecutive valid tokens have been
  2265. read.  "yyerrflag" is used in this process.
  2266.  
  2267.     If "yyerrflag"  is zero,  "yyerror" will  be invoked the
  2268. next time  an error is encountered.  As soon as "yyerror" is
  2269. invoked, it  sets "yyerrflag"  to 3.   Each time a "yyparse"
  2270. shifts on  a valid  token, "yyerrflag" is decremented, until
  2271. it gets  to zero.  At this point, "yyparse" leaves its error
  2272. state; if  a new  error occurs,  "yyerror"  will  be  called
  2273. again.
  2274.  
  2275.     There are two ways in which actions can use "yyerrflag".
  2276. First, they  can check the variable to see if there has been
  2277. a recent  error.   For example,  if an  action encounters  a
  2278. semantic error,  it can  check "yyerrflag"  to see  if it is
  2279. non-zero (meaning  that  there  has  been  a  recent  syntax
  2280. error).   If "yyerrflag"  is non-zero, the semantic error is
  2281. almost certainly  a result  of the  previous  syntax  error.
  2282. Using this  information, the  action may choose to modify or
  2283. suppress the semantic error message.
  2284.  
  2285.     Second, actions  can set  "yyerrflag" to a value if they
  2286. want to  prevent calls to "yyerror".  As long as "yyerrflag"
  2287. is non-zero,  "yyerror" will  not be  called.   This may  be
  2288.  
  2289.  
  2290.  
  2291. Page 36                                       November, 1995
  2292.  
  2293.  
  2294.  
  2295. Thinkage Ltd.                           YAY Reference Manual
  2296.  
  2297.  
  2298.  
  2299. useful if  an action  is smart  enough to realize that it is
  2300. still recovering  from a previous error and "yyerror" should
  2301. not be called again for a while.
  2302.  
  2303.  
  2304. 55..88  TThhee yyyyeerrrrookk MMaaccrroo
  2305.  
  2306.     In some  situations, you may want "yyerror" to be called
  2307. even if  the parser  hasn't seen  three correct tokens since
  2308. the last error.
  2309.  
  2310.     For example,  suppose you  have a  parser for  a line by
  2311. line desk  calculator.   A line of input contains errors, so
  2312. "yyerror" is  called.   "yyerror" prints an error message to
  2313. the user,  throws away the rest of the line, and prompts for
  2314. new input.   If the next line contains an error in the first
  2315. three tokens,  the parser  will  normally  start  discarding
  2316. input _w_i_t_h_o_u_t  calling "yyerror"  again.   This  means  that
  2317. "yyerror" doesn't  print an error message for the user, even
  2318. though the input line is wrong.
  2319.  
  2320.     To avoid  this problem,  you  can  explicitly  tell  the
  2321. parser to  leave its  "potential error"  state, even  if  it
  2322. hasn't yet seen three correct tokens.  Simply say
  2323.  
  2324.           yyerrok ;
  2325.  
  2326. as part  of the  error recognition action.  For example, you
  2327. might have the rule
  2328.  
  2329.           expr : error
  2330.                {
  2331.                    yyerrok;
  2332.                    printf("Please re-enter line.\n");
  2333.                    yyclearin;
  2334.                }
  2335.  
  2336. "yyerrok" is  a macro  that is expanded into code that takes
  2337. the parser  out of  its "potential  error" state and lets it
  2338. start fresh.   More precisely, "yyerrok" sets "yyerrflag" to
  2339. zero.
  2340.  
  2341.  
  2342. 55..99  OOtthheerr EErrrroorr SSuuppppoorrtt RRoouuttiinneess
  2343.  
  2344.     YYABORT halts  "yyparse" in  midstream  and  immediately
  2345. returns a  1.   To the  function that called "yyparse", this
  2346. means that "yyparse" failed for some reason.
  2347.  
  2348.     YYACCEPT halts  the parser in midstream and returns a 0.
  2349. To the  function that  called  "yyparse",  this  means  that
  2350.  
  2351.  
  2352.  
  2353. November, 1995                                       Page 37
  2354.  
  2355.  
  2356.  
  2357. YAY Reference Manual                           Thinkage Ltd.
  2358.  
  2359.  
  2360.  
  2361. "yyparse" terminated  successfully, even if the entire input
  2362. has not yet been scanned.
  2363.  
  2364.     YYERROR (note  that this  is upper case) is a macro that
  2365. "fakes" an  error.  When YYERROR is encountered in the code,
  2366. the parser will react as if it just saw an error and will go
  2367. about recovering from the error.  In Chapter 9, we will give
  2368. an example of how YYERROR can be useful.
  2369.  
  2370.  
  2371.  
  2372.  
  2373.  
  2374.  
  2375.  
  2376.  
  2377.  
  2378.  
  2379.  
  2380.  
  2381.  
  2382.  
  2383.  
  2384.  
  2385.  
  2386.  
  2387.  
  2388.  
  2389.  
  2390.  
  2391.  
  2392.  
  2393.  
  2394.  
  2395.  
  2396.  
  2397.  
  2398.  
  2399.  
  2400.  
  2401.  
  2402.  
  2403.  
  2404.  
  2405.  
  2406.  
  2407.  
  2408.  
  2409.  
  2410.  
  2411.  
  2412.  
  2413.  
  2414.  
  2415. Page 38                                       November, 1995
  2416.  
  2417.  
  2418.  
  2419. Thinkage Ltd.                           YAY Reference Manual
  2420.  
  2421.  
  2422.  
  2423.  
  2424.                        66.. YYAAYY OOuuttppuutt
  2425.  
  2426.     YAY can  produce several  output files.   Options on the
  2427. YAY command line dictate which files are actually generated.
  2428.  
  2429.     The most  important output  file is  the one  containing
  2430. source code  that can  be compiled  into the  actual parser.
  2431. The name  of this  file is  specified with  the  Parser=file
  2432. command line option.
  2433.  
  2434.     Another   possible   output   file   contains   manifest
  2435. definitions.   The name  of  this  file  is  specified  with
  2436. Header=file  on   the  command   line.     This  file  is  a
  2437. distillation of  the declarations  section of the YAY input.
  2438. For example, all the %token directives are restated in terms
  2439. of manifest definitions.
  2440.  
  2441.           %token IF
  2442.  
  2443. would appear as
  2444.  
  2445.           #define IF 257
  2446.  
  2447. in the  C version of the manifests (assuming that IF was the
  2448. first token in the declarations section).  By including this
  2449. file with
  2450.  
  2451.           #include "filename"
  2452.  
  2453. separately  compiled   modules  can  make  use  of  all  the
  2454. pertinent definitions in the YAY input.
  2455.  
  2456.     The third output file that YAY can produce is called the
  2457. Parser Description.   The name of the file is specified with
  2458. Description=file  on   the  command   line.     The   Parser
  2459. Description is split into three sections:
  2460.  
  2461. (a)  a summary of the grammar rules;
  2462.  
  2463. (b)  a list of state descriptions;
  2464.  
  2465. (c)  a list of statistics for the parser generated by YAY.
  2466.  
  2467.     In the  sections that  follow, we  will  show  what  the
  2468. Parser Description looks like for the following grammar:
  2469.  
  2470.  
  2471.  
  2472.  
  2473.  
  2474.  
  2475.  
  2476.  
  2477. November, 1995                                       Page 39
  2478.  
  2479.  
  2480.  
  2481. YAY Reference Manual                           Thinkage Ltd.
  2482.  
  2483.  
  2484.  
  2485.           %token IF ELSE A
  2486.           %%
  2487.           stmt : IF stmt ELSE stmt
  2488.                | IF stmt
  2489.                | A
  2490.                ;
  2491.  
  2492.  
  2493. 66..11  RRuulleess SSuummmmaarryy
  2494.  
  2495.     The rules  summary section  of  the  Parser  Description
  2496. begins with  the command  line used  to invoke YAY.  This is
  2497. intended to  serve as  a "heading"  for the output material.
  2498. We'll use the command line
  2499.  
  2500.           yay infile.y description=out +verbose
  2501.  
  2502. YAY input  is in  the file infile.y and output is written to
  2503. the file out.  We have specified the +Verbose option because
  2504. this provides  the largest amount of output.  See Appendix C
  2505. for more information on the YAY command line.
  2506.  
  2507.     Next comes  a summary  of the  grammar rules.    In  our
  2508. example, we will have
  2509.  
  2510.           Rules:
  2511.              (0)  $accept:  stmt $end
  2512.              (1)  stmt:     IF stmt ELSE stmt
  2513.              (2)  stmt:     IF stmt
  2514.              (3)  stmt:     A
  2515.  
  2516.     The 0th  rule will always be the definition for a symbol
  2517. named $accept.   This  describes what a complete input looks
  2518. like: the  Start symbol  followed by  the end marker.  Other
  2519. rules are those given in the grammar.
  2520.  
  2521.     YAY puts a formfeed character on the line after the last
  2522. grammar rule so that the next part of the Parser Description
  2523. starts on a new page.
  2524.  
  2525.  
  2526. 66..22  SSttaattee DDeessccrriippttiioonnss
  2527.  
  2528.     The  Parser   Description   output   contains   complete
  2529. descriptions of  every possible state.  For example, here is
  2530. the description of one state from our sample grammar.
  2531.  
  2532.  
  2533.  
  2534.  
  2535.  
  2536.  
  2537.  
  2538.  
  2539. Page 40                                       November, 1995
  2540.  
  2541.  
  2542.  
  2543. Thinkage Ltd.                           YAY Reference Manual
  2544.  
  2545.  
  2546.  
  2547.           State 2
  2548.               stmt :  IF.stmt ELSE stmt
  2549.               stmt :  IF.stmt
  2550.  
  2551.               IF   shift 2
  2552.               A    shift 1
  2553.               .    error
  2554.  
  2555.               stmt     goto 4
  2556.  
  2557. By now, this sort of diagram should be familiar to you.  The
  2558. numbers after  the word  "shift" indicate the state to which
  2559. the parser  will Shift if the lookahead symbol happens to be
  2560. IF or  A.   If the  lookahead symbol  is anything  else, the
  2561. parser raises the error condition and starts error recovery.
  2562.  
  2563.     If the  parser pops back to state 2 by means of a Reduce
  2564. Action, the  lookahead symbol  will now  be "stmt"  and  the
  2565. parser will Goto state 4.
  2566.  
  2567.     As another example of a state, here is State 1.
  2568.  
  2569.           State 1
  2570.               stmt :  A.  (3)
  2571.  
  2572.               .     reduce (3)
  2573.  
  2574.     This is  the state  that is  entered when an A token has
  2575. been found.   The (3) on the end of the first line is a _r_u_l_e
  2576. _n_u_m_b_e_r.   It indicates that this particular line sums up the
  2577. whole of  the third  grammar rule  that was specified in the
  2578. YAY input.  The line
  2579.  
  2580.               .    reduce (3)
  2581.  
  2582. indicates that  no matter  what token  comes  next,  we  can
  2583. reduce this  particular input using grammar rule (3) and say
  2584. that we  have successfully  collected a  valid "stmt".   The
  2585. parser will perform a reduction by popping the top state off
  2586. the stack and setting the lookahead symbol to "stmt".
  2587.  
  2588.     It is important to distinguish between
  2589.  
  2590.             A  shift 1
  2591.  
  2592. in State 2 and
  2593.  
  2594.             .  reduce (3)
  2595.  
  2596. in State  1.   In the  Shift instruction,  the  number  that
  2597. follows  is   the  number   of  a  _s_t_a_t_e.    In  the  Reduce
  2598.  
  2599.  
  2600.  
  2601. November, 1995                                       Page 41
  2602.  
  2603.  
  2604.  
  2605. YAY Reference Manual                           Thinkage Ltd.
  2606.  
  2607.  
  2608.  
  2609. instruction, the  number that  follows is  the number  of  a
  2610. _g_r_a_m_m_a_r_ _r_u_l_e  (using the  numbers given to the grammar rules
  2611. in the  first part  of the  Parser Description).  The Parser
  2612. Description always encloses rule numbers in parentheses, and
  2613. leaves state numbers as they are.
  2614.  
  2615.     The complete  state descriptions  for  the  grammar  are
  2616. given below.
  2617.  
  2618.           State 0
  2619.                    $accept: .stmt $end
  2620.  
  2621.               IF    shift 2
  2622.               A     shift 1
  2623.               .     error
  2624.  
  2625.               stmt    goto 3
  2626.  
  2627.           State 1
  2628.               (3)  stmt:     A.
  2629.  
  2630.               .     reduce (3)
  2631.  
  2632.           State 2
  2633.                    stmt:     IF.stmt ELSE stmt
  2634.                    stmt:     IF.stmt
  2635.  
  2636.               IF    shift 2
  2637.               A     shift 1
  2638.               .     error
  2639.  
  2640.               stmt    goto 4
  2641.  
  2642.           State 3
  2643.                    $accept:  stmt.$end
  2644.  
  2645.               $end  accept
  2646.               .     error
  2647.  
  2648.           State 4
  2649.                    stmt:     IF stmt.ELSE stmt
  2650.               (2)  stmt:     IF stmt. [ $end ELSE ]
  2651.  
  2652.             Shift/reduce conflict (5,2) on ELSE
  2653.               ELSE  shift 5
  2654.               .     reduce (2)
  2655.  
  2656.           State 5
  2657.                    stmt:     IF stmt ELSE.stmt
  2658.  
  2659.  
  2660.  
  2661.  
  2662.  
  2663. Page 42                                       November, 1995
  2664.  
  2665.  
  2666.  
  2667. Thinkage Ltd.                           YAY Reference Manual
  2668.  
  2669.  
  2670.  
  2671.               IF    shift 2
  2672.               A     shift 1
  2673.               .     error
  2674.  
  2675.               stmt    goto 6
  2676.  
  2677.           State 6
  2678.               (1)  stmt:     IF stmt ELSE stmt.
  2679.  
  2680.               .     reduce (1)
  2681.  
  2682.     The parser  always begins  in State  0, i.e.  in a state
  2683. where no  input has been read yet.  An acceptable input is a
  2684. "stmt" followed  by the  end marker.  When a "stmt" has been
  2685. collected, the  parser goes  to State  3.   In State  3, the
  2686. required end  marker $end indicates that the input should be
  2687. accepted.  If anything else is found, it is excess input and
  2688. means an error.
  2689.  
  2690.     In State 4, the rule labelled (2) has
  2691.  
  2692.           [ $end ELSE ]
  2693.  
  2694. on the  end.  This just means that the parser expects to see
  2695. one of these two tokens next.
  2696.  
  2697.  
  2698. 66..33  CCoonnfflliicctt SSuummmmaarryy
  2699.  
  2700.     As noted  in the  sample output, there is a shift/reduce
  2701. conflict in  State 4.   If  an ELSE is encountered while the
  2702. parser is  in this state, the parser doesn't know whether to
  2703. shift (into  State 5) or to reduce using rule (2).  Thus YAY
  2704. prints the message
  2705.  
  2706.           Shift/reduce conflict (5,2) on ELSE
  2707.  
  2708.     After the  state descriptions,  YAY prints  a summary of
  2709. all such  conflicts.   With our  sample grammar,  the output
  2710. contains
  2711.  
  2712.           Conflicts:
  2713.               State  Token        Action
  2714.                   4  ELSE         shift 5
  2715.                   4  ELSE         reduce (2)
  2716.  
  2717. Each line  in this  summary gives the number of the state in
  2718. which the  conflict occurs,  the  token(s)  that  cause  the
  2719. conflict, and the conflicting actions.
  2720.  
  2721.  
  2722.  
  2723.  
  2724.  
  2725. November, 1995                                       Page 43
  2726.  
  2727.  
  2728.  
  2729. YAY Reference Manual                           Thinkage Ltd.
  2730.  
  2731.  
  2732.  
  2733.  
  2734. 66..44  PPaarrsseerr SSttaattiissttiiccss
  2735.  
  2736.     The last  section of  the Parser Description is a set of
  2737. statistics summarizing  YAY's work.   Here  are the stats we
  2738. got when we ran our sample grammar through YAY.
  2739.  
  2740. 4 rules, 5 tokens, 2 variables, 7 states
  2741. Memory:  max = 8K
  2742. States: 3 wasted, 4 resets
  2743. Items:  18, 0 kernel, (2,0) per state, maxival=16 (1 w/s)
  2744. Lalr:  1 calls, 2 recurs, (0 trans, 12 epred)
  2745. Actions:  0 entries, gotos: 0 entries
  2746. Exceptions: 1 states, 4 entries
  2747. Simple state elim: 0%, Error default elim: 33%
  2748. Optimizer: in 0, out 0
  2749. Size of tables:  24 bytes
  2750. 2 seconds, final mem = 4
  2751. 1 shift/reduce conflict
  2752.  
  2753.     Some of  these values  are machine independent (e.g. the
  2754. number of  rules), others  are machine  dependent (e.g.  the
  2755. amount of memory used), and some can be different every time
  2756. you run the job (e.g. time elapsed while YAY was running).
  2757.  
  2758.     The statistic  lines are described below.  Many of these
  2759. will be  of  no  interest  to  the  normal  user;  YAY  only
  2760. generates them  for the  use of  those maintaining  the  YAY
  2761. software.   A number of the statistics refer to shift/reduce
  2762. or reduce/reduce  conflicts.   We will  discuss these  in  a
  2763. later chapter.
  2764.  
  2765. 4 rules, 5 tokens, 2 variables, 7 states
  2766.      The four rules are the grammar rules given in the first
  2767.      part of the Parser Description.  The five tokens are A,
  2768.      IF, ELSE,  $end, and  error (which  is always  defined,
  2769.      even if  we don't  use it  in this  grammar).   The two
  2770.      variables are  the non-terminal symbols, "stmt" and the
  2771.      special $accept.  The seven states are states 0 to 6.
  2772.  
  2773. Memory:  max = 8K
  2774.      This gives  the maximum  amount of  dynamic memory that
  2775.      YAY required while producing the parser.  This line may
  2776.      also have  a "success  rate" that  tells how  often YAY
  2777.      succeeded in having enough memory to handle a situation
  2778.      and how often it had to ask for more memory.
  2779.  
  2780. States: 3 wasted, 4 resets
  2781.      The algorithm  that constructs  states from the grammar
  2782.      rules makes  a guess  at the  number of  states it will
  2783.  
  2784.  
  2785.  
  2786.  
  2787. Page 44                                       November, 1995
  2788.  
  2789.  
  2790.  
  2791. Thinkage Ltd.                           YAY Reference Manual
  2792.  
  2793.  
  2794.  
  2795.      need, very  early on in the YAY process.  If this guess
  2796.      is too high, the excess states are said to be "wasted".
  2797.  
  2798.      When creating states from the various grammar rules, it
  2799.      is  sometimes   found  that   a  state  from  one  rule
  2800.      duplicates the  state from  another (for example, there
  2801.      were two  rules that  started with  IF in  our  example
  2802.      above).   In the  final parsing  tables, such duplicate
  2803.      states are  merged together  into a  single state.  The
  2804.      number of  "resets" is  the number  of duplicate states
  2805.      formed, then merged.
  2806.  
  2807. Items: 18, 0 kernel, (2,0) per state, maxival=16 (1 w/s)
  2808.      A state  is made  of items, and the kernel items are an
  2809.      important subset  of these:  the size  of the resulting
  2810.      parsing  tables  and  the  running  time  for  YAY  are
  2811.      proportional to  the number  of items and kernel items.
  2812.      The rest  of the  statistics in  this line  are not  of
  2813.      interest to normal users.
  2814.  
  2815. Lalr: 1 call, 2 recurs, (0 trans, 12 epred)
  2816.      This gives  the number  of calls and recursive calls to
  2817.      the conflict  resolution routine.    The  parenthesized
  2818.      figures are related to the same process.  In some ways,
  2819.      this is  a measure  of the  complexity of  the  grammar
  2820.      being parsed.   This  line will not appear if there are
  2821.      no reduce/reduce  or  shift/reduce  conflicts  in  your
  2822.      grammar.
  2823.  
  2824. Actions: 0 entries, gotos: 0 entries
  2825.      This gives  the number of entries in the tables "yyact"
  2826.      and "yygo".  "yyact" keeps track of the possible Shifts
  2827.      that a  program may  make and "yygo" keeps track of the
  2828.      "gotos" that take place at the end of states.
  2829.  
  2830. Exceptions: 1 states, 4 entries
  2831.      This gives  the number of entries in the table "yydef",
  2832.      yet another  table used in YAY.  "yydef" keeps track of
  2833.      the possible  Reduce, Accept,  and Error actions that a
  2834.      program may make.
  2835.  
  2836. Simple state elim: 0%, Error default elim: 33%
  2837.      The percentage  figures indicate  how much  table space
  2838.      could be  saved through various optimization processes.
  2839.      The  better  written  your  grammar,  the  greater  the
  2840.      percentage of space that can be saved.  Therefore, high
  2841.      percentages here  are an  indication of  a well-written
  2842.      grammar.
  2843.  
  2844.  
  2845.  
  2846.  
  2847.  
  2848.  
  2849. November, 1995                                       Page 45
  2850.  
  2851.  
  2852.  
  2853. YAY Reference Manual                           Thinkage Ltd.
  2854.  
  2855.  
  2856.  
  2857. Optimizer: in 0, out 0
  2858.      More optimization statistics: not of interest to normal
  2859.      YAY users.
  2860.  
  2861. Size of tables: 24 bytes
  2862.      The size  of the  tables  generated  to  represent  the
  2863.      parsing rules.  This size is given in bytes on the host
  2864.      machine, so  it will  be inaccurate if a cross-compiler
  2865.      is being  used on the eventual source code output.  The
  2866.      size does  not include stack space used by "yyparse" or
  2867.      debug tables obtained by defining YYDEBUG.
  2868.  
  2869. 2 seconds, final mem = 4
  2870.      Total real  time that  YAY used  to produce the parser,
  2871.      and the  final dynamic  memory  of  the  parser  (in  K
  2872.      bytes).
  2873.  
  2874. 1 shift/reduce conflict
  2875.      Number of conflicts in the grammar.
  2876.  
  2877.  
  2878.  
  2879.  
  2880.  
  2881.  
  2882.  
  2883.  
  2884.  
  2885.  
  2886.  
  2887.  
  2888.  
  2889.  
  2890.  
  2891.  
  2892.  
  2893.  
  2894.  
  2895.  
  2896.  
  2897.  
  2898.  
  2899.  
  2900.  
  2901.  
  2902.  
  2903.  
  2904.  
  2905.  
  2906.  
  2907.  
  2908.  
  2909.  
  2910.  
  2911. Page 46                                       November, 1995
  2912.  
  2913.  
  2914.  
  2915. Thinkage Ltd.                           YAY Reference Manual
  2916.  
  2917.  
  2918.  
  2919.  
  2920.                           77.. TTyyppeess
  2921.  
  2922.     Earlier we mentioned that "yylval" is iinntt by default, as
  2923. are $$,  $1, $2,  etc.   If you want these to have different
  2924. types, you may redeclare them in the declarations section of
  2925. the YAY input.  This is done with a statement of the form
  2926.  
  2927.           %union {
  2928.                /* possible types for "yylval" and
  2929.                 * $$, $1, $2, etc.  */
  2930.           }
  2931.  
  2932. For example,  suppose "yylval"  can  be  either  integer  or
  2933. floating point.  You might write
  2934.  
  2935.           %union {
  2936.                int intval;
  2937.                float realval;
  2938.           }
  2939.  
  2940. in the  declarations section of the YAY input.  YAY converts
  2941. the %union statement into the following C source.
  2942.  
  2943.           typedef union {
  2944.               int intval;
  2945.               float realval;
  2946.           } YYSTYPE;
  2947.  
  2948. "yylval" is  always declared  to have  type YYSTYPE.   If no
  2949. %union statement is given in the YAY input, it will use
  2950.  
  2951.           #define YYSTYPE int
  2952.  
  2953.     Once YYSTYPE  has been  defined  as  a  union,  you  may
  2954. specify  a   particular  interpretation   of  the  union  by
  2955. including a statement of the form
  2956.  
  2957.           %type <interpretation> SYMBOL
  2958.  
  2959. in  the   declarations  section  of  the  YAY  input.    The
  2960. "interpretation" enclosed  in the angle brackets is the name
  2961. of the interpretation of the union variable that you want to
  2962. use.   The SYMBOL  name is the name of a non-terminal symbol
  2963. defined in the grammar rules.  For example, you might write
  2964.  
  2965.           %type <intval> intexp
  2966.           %type <realval> realexp
  2967.  
  2968. to indicate  that an integer expression has an integer value
  2969. and a real expression has a floating point value.
  2970.  
  2971.  
  2972.  
  2973. November, 1995                                       Page 47
  2974.  
  2975.  
  2976.  
  2977. YAY Reference Manual                           Thinkage Ltd.
  2978.  
  2979.  
  2980.  
  2981.  
  2982.     Tokens may also be declared to have types.  This is done
  2983. in the  %token statement  in the  declaration  section,  and
  2984. again shows the union interpretation in angle brackets, e.g.
  2985.  
  2986.           %token <realval> floatnum
  2987.  
  2988.     If you  use types  in your  YAY input,  YAY will enforce
  2989. compatibility of  types in all expressions.  For example, if
  2990. you write
  2991.  
  2992.           $$ = $2
  2993.  
  2994. in an  action, YAY  will demand  that the  two corresponding
  2995. tokens have the same type; otherwise, the assignment will be
  2996. marked as  invalid.   The reason  for this  is that YAY must
  2997. always know  what interpretation  of the union is being used
  2998. in order to generate correct code.
  2999.  
  3000.  
  3001. TThhee DDeeffaauulltt AAccttiioonn
  3002.  
  3003.     The default  action associated  with  any  rule  can  be
  3004. written as
  3005.  
  3006.           $$ = $1
  3007.  
  3008. which means  that the  value of  associated with  $1 on  the
  3009. value stack  is assigned  to $$  on the value stack when the
  3010. rule is reduced.  If, for example, $1 is an integer, then $$
  3011. will be the same integer after the reduction occurs.
  3012.  
  3013.     On the  other hand,  suppose that the recognition action
  3014. associated with a rule explicitly states
  3015.  
  3016.           $$ = $1
  3017.  
  3018. This explicit assignment may not have the same effect as the
  3019. implicit assignment.  For example, suppose that you define
  3020.  
  3021.           %union {
  3022.               float floatval;
  3023.               int intval;
  3024.           }
  3025.  
  3026. Also suppose  that the type associated with $$ is "floatval"
  3027. and the  type associated  with $1  is "intval".    Then  the
  3028. explicit statement
  3029.  
  3030.           $$ = $1
  3031.  
  3032.  
  3033.  
  3034.  
  3035. Page 48                                       November, 1995
  3036.  
  3037.  
  3038.  
  3039. Thinkage Ltd.                           YAY Reference Manual
  3040.  
  3041.  
  3042.  
  3043. performs an  integer to  floating point  conversion when the
  3044. value  of  $1  is  assigned  to  $$,  whereas  the  implicit
  3045. statement did  an integer  to integer assignment and did _n_o_t
  3046. perform this  conversion.  You must therefore be careful and
  3047. think  about   the  effects   of   implicit   vs.   explicit
  3048. assignments.
  3049.  
  3050.  
  3051.  
  3052.  
  3053.  
  3054.  
  3055.  
  3056.  
  3057.  
  3058.  
  3059.  
  3060.  
  3061.  
  3062.  
  3063.  
  3064.  
  3065.  
  3066.  
  3067.  
  3068.  
  3069.  
  3070.  
  3071.  
  3072.  
  3073.  
  3074.  
  3075.  
  3076.  
  3077.  
  3078.  
  3079.  
  3080.  
  3081.  
  3082.  
  3083.  
  3084.  
  3085.  
  3086.  
  3087.  
  3088.  
  3089.  
  3090.  
  3091.  
  3092.  
  3093.  
  3094.  
  3095.  
  3096.  
  3097. November, 1995                                       Page 49
  3098.  
  3099.  
  3100.  
  3101. YAY Reference Manual                           Thinkage Ltd.
  3102.  
  3103.  
  3104.  
  3105.  
  3106.                        88.. AAmmbbiigguuiittiieess
  3107.  
  3108.     Suppose we have a grammar with the rule
  3109.  
  3110.           expr : expr '-' expr ;
  3111.  
  3112. and the parser is reading an expression of the form
  3113.  
  3114.           expr - expr - expr
  3115.  
  3116. The parser  reads this  token by  token, of course, so after
  3117. three tokens it will have
  3118.  
  3119.           expr - expr
  3120.  
  3121. The parser  recognizes this form.  In fact, the parser could
  3122. reduce this right away into a single "expr" according to the
  3123. given grammar rule.
  3124.  
  3125.     However, the  parser has  a problem.  At this point, the
  3126. parser doesn't  know what comes next, and perhaps the entire
  3127. line will be something like
  3128.  
  3129.           expr - expr * expr
  3130.  
  3131. If it  is, the  precedence rules say that the multiplication
  3132. should be  performed before the subtraction, so handling the
  3133. subtraction first  is incorrect.   The parser must therefore
  3134. read another  token to see if it is really all right to deal
  3135. with the  subtraction now,  or if  the correct  action is to
  3136. skip the  subtraction for  the moment and deal with whatever
  3137. follows the second "expr".
  3138.  
  3139.     In terms  of parser states, this problem boils down to a
  3140. choice between _r_e_d_u_c_i_n_g the expression
  3141.  
  3142.           expr - expr
  3143.  
  3144. or  _s_h_i_f_t_i_n_g  and  acquiring  more  input  before  making  a
  3145. reduction.   This  is  known  as  a  _s_h_i_f_t_/_r_e_d_u_c_e_ _ _c_o_n_f_l_i_c_t_.
  3146. Sometimes a  parser must  also choose  between two  possible
  3147. reductions.     This  kind   of  situation   is   called   a
  3148. _r_e_d_u_c_e_/_r_e_d_u_c_e_ _c_o_n_f_l_i_c_t_.
  3149.  
  3150.     In case  you are  curious, there  is no  such thing as a
  3151. shift/shift conflict.    To  see  why  this  is  impossible,
  3152. suppose that we have the following definitions.
  3153.  
  3154.  
  3155.  
  3156.  
  3157.  
  3158.  
  3159. Page 50                                       November, 1995
  3160.  
  3161.  
  3162.  
  3163. Thinkage Ltd.                           YAY Reference Manual
  3164.  
  3165.  
  3166.  
  3167.           thing : a b
  3168.                 | a c
  3169.                 ;
  3170.           b : T rest_of_b;
  3171.           c : T rest_of_c;
  3172.  
  3173. If the  parser is  in the  state where  it has seen "a", you
  3174. would have the diagram
  3175.  
  3176.           thing : a.b
  3177.           thing : a.c
  3178.  
  3179.     You might  think that  if the  lookahead symbol  was the
  3180. token T,  the parser would be confused, since T is the first
  3181. token of  both "b"  and "c".  However, there is no confusion
  3182. at all.   The  parser just  Shifts to  a state that we could
  3183. diagram as
  3184.  
  3185.           b : T.rest_of_b
  3186.           c : T.rest_of_c
  3187.  
  3188.  
  3189. 88..11  RReessoollvviinngg CCoonnfflliiccttss bbyy PPrreecceeddeennccee
  3190.  
  3191.     The precedence directives (%left, %right, and %nonassoc)
  3192. let YAY-produced  parsers resolve  shift/reduce conflicts in
  3193. an obvious way:
  3194.  
  3195. (a)  The precedence  of a  Shift operation  is defined to be
  3196.      the precedence  of the  token on  which the Shift takes
  3197.      place.
  3198.  
  3199. (b)  The precedence  of a  Reduce operation is defined to be
  3200.      the precedence  of the  grammar rule  that  the  Reduce
  3201.      operation uses.
  3202.  
  3203.     If you  have a  shift/reduce conflict, and the Shift and
  3204. Reduce operations both have a precedence, the parser chooses
  3205. the operation with the higher precedence.
  3206.  
  3207.  
  3208. 88..22  DDiissaammbbiigguuaattiinngg RRuulleess
  3209.  
  3210.     Precedence cannot  resolve  conflicts  if  one  or  both
  3211. conflicting operations  have no  precedence.   For  example,
  3212. consider the following.
  3213.  
  3214.           statmt:  IF '(' cond ')' statmt
  3215.               |    IF '(' cond ')' statmt ELSE statmt ;
  3216.  
  3217. Given this rule, how should the parser interpret the input
  3218.  
  3219.  
  3220.  
  3221. November, 1995                                       Page 51
  3222.  
  3223.  
  3224.  
  3225. YAY Reference Manual                           Thinkage Ltd.
  3226.  
  3227.  
  3228.  
  3229.  
  3230.           IF ( cond1 ) IF ( cond2 ) statmt1 ELSE statmt2
  3231.  
  3232. There are two equally valid interpretations of this input:
  3233.  
  3234.           IF ( cond1 ) {
  3235.                IF ( cond2 ) statmt1
  3236.                ELSE statmt2
  3237.           }
  3238.  
  3239. and
  3240.  
  3241.           IF ( cond1 ) {
  3242.                IF ( cond2 ) statmt1
  3243.           }
  3244.           ELSE statmt2
  3245.  
  3246.     In a  typical grammar,  the IF  and  IF-ELSE  statements
  3247. would not have a precedence, so precedence could not resolve
  3248. the conflict.   Thus consider what happens at the point when
  3249. the parser has read
  3250.  
  3251.           IF ( cond1 ) IF ( cond2 ) statmt1
  3252.  
  3253. and has just picked up ELSE as the lookahead symbol.
  3254.  
  3255. (1)  It can immediately Reduce the
  3256.  
  3257.           IF ( cond2 ) statmt1
  3258.  
  3259.      using the first definition of "statmt" and obtain
  3260.  
  3261.           IF ( cond1 ) statmt ELSE ...
  3262.  
  3263.      thereby associating the ELSE with the first IF.
  3264.  
  3265. (2)  It can  Shift, which means ignoring the first part (the
  3266.      IF with  "cond1") and  going on  to handle  the  second
  3267.      part, thereby associating the ELSE with the second IF.
  3268.  
  3269.     In this  case,  most  programming  languages  choose  to
  3270. associate the  ELSE with  the second  IF, i.e. they want the
  3271. parser to  Shift instead  of Reduce.  Because of  this  (and
  3272. other similar situations), YAY-produced parsers are designed
  3273. to use the following rule to resolve shift/reduce conflicts.
  3274.  
  3275. _D_i_s_a_m_b_i_g_u_a_t_i_n_g_ _R_u_l_e_ _1_:
  3276.      If there is a shift/reduce conflict in situations where
  3277.      no precedence  rules have  been created  to resolve the
  3278.      conflict, the  default action is to Shift. The conflict
  3279.      will also  be reported  in the  YAY output  so you  can
  3280.  
  3281.  
  3282.  
  3283. Page 52                                       November, 1995
  3284.  
  3285.  
  3286.  
  3287. Thinkage Ltd.                           YAY Reference Manual
  3288.  
  3289.  
  3290.  
  3291.      check that  Shifting is  actually what you want.  If it
  3292.      isn't what  you want, the grammar rules will have to be
  3293.      rewritten.
  3294.  
  3295.     This is  known as a disambiguating rule because it helps
  3296. YAY-produced parsers  resolve ambiguities.  The rule is only
  3297. used in situations where precedence rules cannot resolve the
  3298. conflict.   If both  the  Shift  operation  and  the  Reduce
  3299. operation  have  an  assigned  precedence,  the  parser  can
  3300. compare precedences  and decide  which operation  to perform
  3301. first.   Even if  the precedences are equal, the precedences
  3302. must  have   originated  from   either  %left,   %right,  or
  3303. %nonassoc, so  the parser knows how to handle the situation.
  3304. The only  time the disambiguating rule is needed is when one
  3305. or both  of the  Shift or Reduce operations does not have an
  3306. assigned precedence.
  3307.  
  3308.     In  a   similar  vein,   YAY-produced  parsers  use  the
  3309. following rule to resolve reduce/reduce conflicts.
  3310.  
  3311. _D_i_s_a_m_b_i_g_u_a_t_i_n_g_ _R_u_l_e_ _2_:
  3312.      If there  is a  reduce/reduce conflict, the parser will
  3313.      always Reduce  by the  rule that was given _f_i_r_s_t in the
  3314.      rules section  of the  YAY input.   Again, the conflict
  3315.      will be  reported in  the YAY  output so that users may
  3316.      ensure that the choice of Reduction is correct.
  3317.  
  3318.     Note that  precedence is  _n_o_t consulted in reduce/reduce
  3319. conflicts.  YAY always Reduces by the earliest grammar rule,
  3320. regardless of precedence.
  3321.  
  3322.     Finally, YAY-produced parsers use a third disambiguating
  3323. rule to prevent excessive errors.
  3324.  
  3325. _D_i_s_a_m_b_i_g_u_a_t_i_n_g_ _R_u_l_e_ _3_:
  3326.      If the  parser is  asked to  choose between shifting on
  3327.      eerrrroorr or  on any  other item,  it will  choose the non-
  3328.      error item.
  3329.  
  3330.     The disambiguating  rules are  simple to state, but they
  3331. can have  complex  repercussions  if  the  grammar  is  non-
  3332. trivial.   If the grammar is sufficiently complicated, these
  3333. simple rules  for resolving  conflicts may not be capable of
  3334. handling all  the necessary intricacies in the way you want.
  3335. You should pay close attention to all conflicts noted in the
  3336. parsing table  report produced by YAY and should ensure that
  3337. the default  actions taken  by the  parser are  the  desired
  3338. ones.
  3339.  
  3340.     NNoottee:: the conflict between the rules
  3341.  
  3342.  
  3343.  
  3344.  
  3345. November, 1995                                       Page 53
  3346.  
  3347.  
  3348.  
  3349. YAY Reference Manual                           Thinkage Ltd.
  3350.  
  3351.  
  3352.  
  3353.           statmt:  IF '(' cond ')' statmt
  3354.               |    IF '(' cond ')' ELSE statmt ;
  3355.  
  3356. can be resolved by adding
  3357.  
  3358.           %left ELSE
  3359.  
  3360. to the  declarations section  of the YAY input.  This puts a
  3361. precedence on  the ELSE  action and  says that  it is  left-
  3362. associative.   This is another example of using a precedence
  3363. to resolve an ambiguity.
  3364.  
  3365.  
  3366. 88..33  CCoonnfflliiccttss iinn YYAAYY OOuuttppuutt
  3367.  
  3368.     If  your   grammar  has  shift/reduce  or  reduce/reduce
  3369. conflicts, you  will also  see a  table of  conflicts in the
  3370. statistics section  of the Parser Description.  For example,
  3371. if we change the rules section of our sample grammar to
  3372.  
  3373.           stmt : IF stmt ELSE stmt
  3374.                | IF stmt
  3375.                | stmt stmt
  3376.                | A ;
  3377.  
  3378. we get the following conflict report.
  3379.  
  3380.           Conflicts:
  3381.               State  Token      Action
  3382.                   5  IF         shift 2
  3383.                   5  IF         reduce (3)
  3384.                   5  A          shift 1
  3385.                   5  A          reduce (3)
  3386.  
  3387.     This shows  that State 5 has two shift/reduce conflicts.
  3388. If the  parser is  in State 5 and encounters an IF token, it
  3389. can shift  to state 2 or reduce using rule 3.  If the parser
  3390. encounters an  A token,  it can  shift to  state 1 or reduce
  3391. using rule  3.   This is  summarized in the final statistics
  3392. with the line
  3393.  
  3394.           2 shift/reduce conflicts
  3395.  
  3396.     Reading the  conflict report  shows you  what action the
  3397. parser takes  in case  of a  conflict --  the parser  always
  3398. takes the  _f_i_r_s_t action  shown in  the report.   This action
  3399. will be  chosen in  accordance with  the two  disambiguating
  3400. rules.
  3401.  
  3402.  
  3403.  
  3404.  
  3405.  
  3406.  
  3407. Page 54                                       November, 1995
  3408.  
  3409.  
  3410.  
  3411. Thinkage Ltd.                           YAY Reference Manual
  3412.  
  3413.  
  3414.  
  3415.  
  3416.                     99.. AAddvvaanncceedd FFeeaattuurreess
  3417.  
  3418.     In this  chapter, we  describe more specialized features
  3419. of YAY.
  3420.  
  3421.  
  3422. 99..11  LLAALLRR((22)) GGrraammmmaarrss
  3423.  
  3424.     An LALR(2)  grammar has  one more  level of  "lookahead"
  3425. than an LALR(1) grammar.  When trying to decide how to parse
  3426. a given input, an LALR(1) parser sometimes looks at the next
  3427. input token  to see if that makes a difference.  In the same
  3428. situation, an  LALR(2) parser  can  look  at  the  next  _t_w_o
  3429. tokens.
  3430.  
  3431.     LALR(2) grammars  are  described  in  the  same  way  as
  3432. LALR(1) grammars.  To indicate  that  you  want  an  LALR(2)
  3433. parser, you  must put  the option  +LR2 on  the command line
  3434. that invokes YAY.
  3435.  
  3436.     An LALR(2) parser can perform a _l_o_o_k_a_h_e_a_d action as well
  3437. as Shift,  Reduce, Goto, Accept, and Error.  For example, in
  3438. a state diagram you might see
  3439.  
  3440.           A    shift 1
  3441.           B    reduce (2)
  3442.           C    lookahead
  3443.  
  3444. This means that if token A is encountered in this state, the
  3445. parser will  shift to State 1; if token B is encountered, it
  3446. will reduce  using Rule  (2); and if token C is encountered,
  3447. it will lookahead.
  3448.  
  3449.  
  3450. _9_._1_._1_ _ _T_h_e_ _L_o_o_k_a_h_e_a_d_ _A_c_t_i_o_n
  3451.  
  3452.     A state  that has  a Lookahead  action  has  a  list  of
  3453. possible states  the parser  can enter  next.   These states
  3454. conflict with  each other  --  the  Lookahead  action  isn't
  3455. needed if  there is  no conflict.   The  parser attempts  to
  3456. resolve the  conflict by  reading one  additional token.  If
  3457. the grammar  is set up properly, this token will be valid in
  3458. only one  of the possible contexts, so the parser can choose
  3459. that rule instead of the other possibilities.
  3460.  
  3461.     Thus the Lookahead action tests all the possibilities in
  3462. the list.  It begins  by making  a private copy of the state
  3463. stack.   (Actually, it  just sets things up so that it looks
  3464. like it has a separate copy of the state stack -- it doesn't
  3465. really make  a copy.)   Next,  it calls  on a  routine named
  3466.  
  3467.  
  3468.  
  3469. November, 1995                                       Page 55
  3470.  
  3471.  
  3472.  
  3473. YAY Reference Manual                           Thinkage Ltd.
  3474.  
  3475.  
  3476.  
  3477. "yy2lex" (described  later) to  obtain  a  second  lookahead
  3478. token.
  3479.  
  3480.     The Lookahead  action  then  begins  going  through  the
  3481. possible rules  on its  list.   Some of  these rules  may be
  3482. Shifts, while  others are Reduces -- the reductions are what
  3483. make it  necessary to  simulate a  copy of  the state stack,
  3484. because you don't want to play with the true stack.
  3485.  
  3486.     The Lookahead  action takes  the action  associated with
  3487. each possibility  in the  list, entering  new states through
  3488. Shifts or  Reduces.   It then  sees if  the second lookahead
  3489. token causes  an error  in this  new state.    If  an  error
  3490. occurs, the parser pops back to the original Lookahead state
  3491. and checks the next possibility on the list.
  3492.  
  3493.     When it  finally finds a rule where the second lookahead
  3494. symbol doesn't  cause an error, it pops back to the original
  3495. Lookahead state  one last  time.   It gets  rid of the stack
  3496. set-up that  the Lookahead  action was  using and returns to
  3497. the old  state stack.   It then takes the action that it has
  3498. discovered in the list of possibilities.
  3499.  
  3500.     Note that  the Lookahead action takes the first possible
  3501. rule where  the second lookahead symbol is valid.  It is, of
  3502. course, possible that there are other valid possibilities in
  3503. the list.   The  order of the list of possibilities is based
  3504. on the  standard disambiguating  rules: a shift comes first,
  3505. followed  by   reductions  in   the  order   in  which   the
  3506. corresponding grammar rules were given.
  3507.  
  3508.  
  3509. _9_._1_._2_ _ _T_h_e_ _y_y_2_l_e_x_ _R_o_u_t_i_n_e
  3510.  
  3511.     In order  to perform  the lookahead,  "yyparse" calls  a
  3512. routine called  "yy2lex".   This is  a user-written  lexical
  3513. analyzer, just  as "yylex"  is.  It returns the same kind of
  3514. token value that "yylex" does.  However, "yy2lex" should not
  3515. set the "yylval" value.
  3516.  
  3517.     For some  applications, "yy2lex"  could even be the same
  3518. routine as  "yylex".   There are  good reasons  why the  two
  3519. should be  separate, however.   Suppose,  for  the  sake  of
  3520. argument, that  "yyparse"  called  "yylex"  for  all  input.
  3521. "yyparse" might  call  "yylex"  for  the  next  token,  then
  3522. immediately call "yylex" again for a lookahead.  This second
  3523. call could  overwrite important  values like "yylval" before
  3524. they had  been used,  thereby confusing things greatly.  For
  3525. such reasons,  "yy2lex" and  "yylex" sometimes  have  to  be
  3526. different routines.
  3527.  
  3528.  
  3529.  
  3530.  
  3531. Page 56                                       November, 1995
  3532.  
  3533.  
  3534.  
  3535. Thinkage Ltd.                           YAY Reference Manual
  3536.  
  3537.  
  3538.  
  3539.     In practice, parsers rarely call "yy2lex" -- the routine
  3540. is only  needed in  special circumstances.   This means that
  3541. "yy2lex" usually  can be  much simpler than "yylex": "yylex"
  3542. must be  able to  handle all  possible input  tokens,  while
  3543. "yy2lex" is only called in a few special cases.  To find out
  3544. the tokens  that "yy2lex"  must be  able to handle, run your
  3545. grammar through  YAY and  get a list of the states where the
  3546. parser performs  a Lookahead  instead of  a Shift or Reduce.
  3547. These instances are the only ones where the parser will call
  3548. "yy2lex", so  the associated  tokens are  the only ones that
  3549. the routine has to handle.
  3550.  
  3551.     The values obtained by "yy2lex" are thrown away once the
  3552. parser has  used them  in its lookahead.  What this means is
  3553. that the  parser doesn't remember what "yy2lex" returned, so
  3554. it will  call on  "yylex" to  re-read the  token for  normal
  3555. parsing.  This means one of two things:
  3556.  
  3557. (a)  "yy2lex" can  duplicate  the  processing  that  "yylex"
  3558.      does, then  leave the  pertinent information around for
  3559.      "yylex" to obtain.  This means that "yylex" must have a
  3560.      way of  knowing when "yy2lex" has already read the next
  3561.      token (e.g. "yy2lex" can set a flag).
  3562.  
  3563. (b)  "yy2lex" can cheat and only do minimal processing.  For
  3564.      example, "yy2lex"  may only  have to  look at the first
  3565.      character of  the next  token to  figure  out  what  is
  3566.      coming next.  "yy2lex" can then "ungetc" that character
  3567.      and return an appropriate token value.  When "yylex" is
  3568.      called, it reads the full token in the usual manner.
  3569.  
  3570.     The second approach is sufficient for most grammars.  It
  3571. simplifies both "yylex" and "yy2lex".
  3572.  
  3573.  
  3574. _9_._1_._3_ _ _C_o_n_f_l_i_c_t_s
  3575.  
  3576.     With an  additional level  of lookahead,  there  is  the
  3577. potential  for  a  staggering  number  of  conflicts.    For
  3578. example, you  may lookahead  to a  new state  to resolve one
  3579. conflict, only  to find  that  the  new  state  also  has  a
  3580. lookahead to resolve a conflict.
  3581.  
  3582.     If an  LALR(2) parser  is  performing  a  lookahead  and
  3583. enters a  state where  the secondary lookahead token invokes
  3584. another Lookahead action, the parser ruthlessly resolves the
  3585. second Lookahead action by choosing the first possibility on
  3586. the second Lookahead list.  This is not very elegant, so you
  3587. should avoid this double lookahead situation.
  3588.  
  3589.  
  3590.  
  3591.  
  3592.  
  3593. November, 1995                                       Page 57
  3594.  
  3595.  
  3596.  
  3597. YAY Reference Manual                           Thinkage Ltd.
  3598.  
  3599.  
  3600.  
  3601.     Conflicts of  this nature  are  reported  in  the  usual
  3602. conflict table at the end of the State Description output.
  3603.  
  3604.  
  3605. 99..22  MMuullttiippllee AAccttiioonnss
  3606.  
  3607.     A rule  can have more than one action.  For example, you
  3608. might have
  3609.  
  3610.           a : A1 {action1} A2 {action2} A3 {action3};
  3611.  
  3612. The non-terminal  symbol "a" consists of symbols A1, A2, and
  3613. A3.  When A1 is recognized, "action1" is invoked; when A2 is
  3614. recognized, "action2"  is invoked; and when A3 is recognized
  3615. (and therefore the entire symbol "a"), "action3" is invoked.
  3616. In this case,
  3617.  
  3618.           $1   -- is the value of A1
  3619.           $2   -- is the value of $$ in action1
  3620.           $3   -- is the value of A2
  3621.           $4   -- is the value of $$ in action2
  3622.           $5   -- is the value of A3
  3623.  
  3624.     If types  are involved,  multiple  actions  become  more
  3625. complicated.   If "action1" mentions $$, there is no way for
  3626. YAY to  guess what  type $$  has, since  it  is  not  really
  3627. associated with  a token  or non-terminal  symbol.  You must
  3628. therefore state  it explicitly by specifying the appropriate
  3629. type name  in angle brackets between the two $ signs.  If we
  3630. had
  3631.  
  3632.           %union {
  3633.               int intval;
  3634.               float realval;
  3635.           }
  3636.  
  3637. you might say
  3638.  
  3639.           $<realval>$
  3640.  
  3641. in place  of $$  in the  action, to show that the result had
  3642. type ffllooaatt.  In the same way, if "action2" refers to $2 (the
  3643. result of action1), you might say
  3644.  
  3645.           $<realval>2
  3646.  
  3647.     To deal  with multiple  actions, YAY changes the form of
  3648. the given  grammar rule  and creates grammar rules for dummy
  3649. symbols.   The dummy  symbols have  names made  up  of  a  $
  3650. followed by the rule number.  For example,
  3651.  
  3652.  
  3653.  
  3654.  
  3655. Page 58                                       November, 1995
  3656.  
  3657.  
  3658.  
  3659. Thinkage Ltd.                           YAY Reference Manual
  3660.  
  3661.  
  3662.  
  3663.           a : A1 {action1} A2 {action2} A3 {action3};
  3664.  
  3665. might be changed to the rules
  3666.  
  3667.           $21 : /* null */ {action1} ;
  3668.           $22 : /* null */ {action2} ;
  3669.           a : A1 $21 A2 $22 A3 {action3};
  3670.  
  3671. These rules will be shown in the Rules Summary of the Parser
  3672. Description report.
  3673.  
  3674.     Note that  this technique  can introduce conflicts.  For
  3675. example, suppose you have the definitions
  3676.  
  3677.           a : A1 {action1} A2 X;
  3678.           b : A1 A2 Y;
  3679.  
  3680. These are changed to
  3681.  
  3682.           $50 : /* null */ {action1};
  3683.           a : A1 $50 A2 X;
  3684.           b : A1 A2 Y;
  3685.  
  3686. The definitions  of "a" and "b" give a shift/reduce conflict
  3687. because the  parser can't tell whether A1 followed by A2 has
  3688. the null  string for  $50 in  the middle.   It has to decide
  3689. whether to Reduce $50 or to Shift to a state diagrammed by
  3690.  
  3691.           b : A1 A2.Y
  3692.  
  3693.     This particular  conflict could  be resolved by using an
  3694. LALR(2) parser  instead of LALR(1).  However, there are more
  3695. complicated examples in which this is not possible.
  3696.  
  3697.     There is  another situation  to watch for.  Consider the
  3698. grammar
  3699.  
  3700.           a : A1 c A2 X ;
  3701.           b : A1 c A2 Y ;
  3702.           c : /* nothing */ {action} ;
  3703.  
  3704. You might think that this is equivalent to
  3705.  
  3706.           a : A1 {action} A2 X;
  3707.           b : A1 {action} A2 Y;
  3708.  
  3709. but it  is not.   The first will not produce a conflict, but
  3710. the second one will.  The second is converted into
  3711.  
  3712.           a : A1 $50 A2 X;
  3713.           b : A1 $51 A2 Y;
  3714.  
  3715.  
  3716.  
  3717. November, 1995                                       Page 59
  3718.  
  3719.  
  3720.  
  3721. YAY Reference Manual                           Thinkage Ltd.
  3722.  
  3723.  
  3724.  
  3725.           $50 : {action} ;
  3726.           $51 : {action} ;
  3727.  
  3728. even when  the action  is the same for both "a" and "b".  If
  3729. the parser finds an A1 followed by a null string followed by
  3730. A2, it  doesn't know  if it should interpret the null string
  3731. as $50 or $51; therefore, it gets a conflict.  Obviously, it
  3732. is better  to use  the first  format,  where  the  identical
  3733. actions are associated with a separate rule.
  3734.  
  3735.  
  3736. 99..33  SSeelleeccttiioonn PPrreeffeerreennccee
  3737.  
  3738.     A _s_e_l_e_c_t_i_o_n_ _p_r_e_f_e_r_e_n_c_e can be added to a grammar rule to
  3739. help resolve  conflicts.  The following input shows a simple
  3740. example of  how a selection preference can resolve conflicts
  3741. between two rules.
  3742.  
  3743.           a1 : a b ['+' '-']
  3744.                { /* Action 1 */ } ;
  3745.           a2 : a b
  3746.                { /* Action 2 */ } ;
  3747.  
  3748. The selection preference is indicated by zero or more _t_o_k_e_n_s
  3749. inside square  brackets.   If the token that follows the "b"
  3750. is one  of the tokens inside the square brackets, the parser
  3751. will use  the grammar  rule for  "a1".   If the  token  that
  3752. follows the  "b" is  not one of the given tokens, the parser
  3753. will use  the rule  for "a2".   In  this way,  the  conflict
  3754. between the  two rules  is resolved  -- the preference tells
  3755. which one to select, depending on the value of the lookahead
  3756. token.
  3757.  
  3758.     Notice that  a selection  preference states  that a rule
  3759. _s_h_o_u_l_d be used when the next token is one of the ones listed
  3760. in the  brackets and  should _n_o_t be used if it is not in the
  3761. brackets.
  3762.  
  3763.     The lookahead  token is  merely used  to determine which
  3764. rule to  select.   It is  _n_o_t part  of the rule itself.  For
  3765. example, suppose you have
  3766.  
  3767.           a1 : a b ['+' '-'] ;
  3768.           a2 : a b ;
  3769.           xx : a1 op expr ;
  3770.  
  3771. and suppose  you have  an "a", a "b", and + as the lookahead
  3772. token.   The +  indicates that  the "a"  and "b"  should  be
  3773. reduced to  "a1".   The parser  does this and finds that the
  3774. "a1" is  part of  the "xx" rule.  The + lookahead token will
  3775. be associated  with the  "op" symbol  in the  "xx" rule.  In
  3776.  
  3777.  
  3778.  
  3779. Page 60                                       November, 1995
  3780.  
  3781.  
  3782.  
  3783. Thinkage Ltd.                           YAY Reference Manual
  3784.  
  3785.  
  3786.  
  3787. other words,  a selection  preference does  not "use  up" an
  3788. input token;  it just  looks at  the  token  value  to  help
  3789. resolve a conflict.
  3790.  
  3791.     The $end  symbol may  be used  inside square brackets to
  3792. indicate  end-of-file  in  the  input  being  parsed.    For
  3793. example,
  3794.  
  3795.           statement : line ['\n' $end]
  3796.  
  3797. shows that this rule is preferred if a "line" is followed by
  3798. a new-line character or the end of the file.
  3799.  
  3800.     The  square  brackets  of  a  selection  preference  may
  3801. contain no tokens, as in
  3802.  
  3803.           x : y z [];
  3804.  
  3805. This says  that the parser should never use this rule unless
  3806. it cannot be avoided.
  3807.  
  3808.     When there  are many  selection preferences  in the same
  3809. state, the  parser must compare them to check for conflicts.
  3810. To do  this, YAY  chooses the  most likely  rule  (based  on
  3811. preference) and  compares this  to the other possible rules.
  3812. In order  to understand  what we  mean by  "most likely", an
  3813. example will help.  Consider the grammar
  3814.  
  3815.           a : b [ 'x' ]
  3816.             | b [ 'y' ]
  3817.             | b [ ]
  3818.             ;
  3819.  
  3820. YAY must  consider what  happens when  a "b" symbol has been
  3821. encountered.   If the  "b" is  followed by  an 'x', the most
  3822. likely rule is
  3823.  
  3824.           a : b [ 'x' ]
  3825.  
  3826. If the "b" is followed by a 'y', the most likely rule is
  3827.  
  3828.           a : b [ 'y' ]
  3829.  
  3830. If the  "b" is  followed by any other token, the most likely
  3831. rule is
  3832.  
  3833.           a : b [ ]
  3834.  
  3835. Once the  most likely  rule has  been  chosen,  it  will  be
  3836. compared to  the other  rules in  the set  to make sure that
  3837. there are  no conflicts.   (In a previous release, YAY would
  3838.  
  3839.  
  3840.  
  3841. November, 1995                                       Page 61
  3842.  
  3843.  
  3844.  
  3845. YAY Reference Manual                           Thinkage Ltd.
  3846.  
  3847.  
  3848.  
  3849. compare every  pair of rules, without choosing a most likely
  3850. one.  In this case, the rules
  3851.  
  3852.           a : b [ 'x' ]
  3853.           a : b [ 'y' ]
  3854.  
  3855. would conflict  with each other, because there was no way to
  3856. choose between the two if the next token was not 'x' or 'y'.
  3857. In this  release, YAY  will compare  the most likely rule to
  3858. all the  others, but  will  not  compare  all  the  possible
  3859. pairs.)
  3860.  
  3861.     Selection preferences  can  also  be  stated  using  the
  3862. construct
  3863.  
  3864.           [^ T1 T2 T3 ...]
  3865.  
  3866. where the  first character  is a  caret (^) and T1, T2, etc.
  3867. are tokens.   When  this is  put on  the end  of a  rule, it
  3868. indicates that  the rule  should be  used if  the  lookahead
  3869. token is _n_o_t one of the listed tokens.  For example,
  3870.  
  3871.           a1 : a b
  3872.              { /* Action 1 */ } ;
  3873.           a2 : a b [^ '+' '-']
  3874.              { /* Action 2 */ } ;
  3875.  
  3876. says that  rule "a2"  should be  used if the token after the
  3877. "b" is  _n_o_t + or -.  If the token is + or -, "a2" should not
  3878. be used (so "a1" will be).
  3879.  
  3880.     The construct  [^] is  the reverse of [].  It is used to
  3881. indicate a  rule that should _a_l_w_a_y_s be taken unless there is
  3882. another rule  that must  be taken  because  of  a  selection
  3883. preference.
  3884.  
  3885.     Selection preference constructs can be put in the middle
  3886. of rules as well as on the end.  For example, we could write
  3887.  
  3888.           expr : expr ['+' '-'] op expr
  3889.                  { /* Action 1 */ }
  3890.                | expr op expr
  3891.                  { /* Action 2 */ } ;
  3892.  
  3893. This states  that if  the first "expr" is followed by + or -
  3894. you want  to use  the first rule; otherwise, you want to use
  3895. the second.   Note that the preference does not use up the +
  3896. or - token: you still need a symbol ("op") to represent such
  3897. tokens.
  3898.  
  3899.  
  3900.  
  3901.  
  3902.  
  3903. Page 62                                       November, 1995
  3904.  
  3905.  
  3906.  
  3907. Thinkage Ltd.                           YAY Reference Manual
  3908.  
  3909.  
  3910.  
  3911.     Selection preferences  that appear  in the  middle of  a
  3912. rule are  implemented in  the same  way as multiple actions,
  3913. using dummy  rules.   The  above  example  would  result  in
  3914. something like
  3915.  
  3916.           $23 : ['+' '-'] ;
  3917.           expr : expr $23 op expr
  3918.                  { /* Action 1 */ }
  3919.                | expr op expr
  3920.                  { /* Action 2 */ } ;
  3921.  
  3922. (where the  23 in  $23 is just a number we chose at random).
  3923. The dummy  rule that  is created  is a  null string with the
  3924. selection preference  on the  end.  The first token for "op"
  3925. will be the + or - that was the lookahead token in rule $23.
  3926.  
  3927.     If a  selection preference  in the  middle of  a rule is
  3928. immediately followed  by an  action, only  one dummy rule is
  3929. created to handle both the action and the preference.
  3930.  
  3931.     In most  cases, a  selection preference  counts as  a $N
  3932. symbol, but it has no associated value.  For example, in
  3933.  
  3934.           expr : expr ['+' '-'] op expr
  3935.  
  3936. we have
  3937.  
  3938.           $1 -- first "expr"
  3939.           $2 -- no value
  3940.           $3 -- "op"
  3941.           $4 -- second "expr"
  3942.  
  3943. If the  preference is  followed by an action, the preference
  3944. and the  action count  as a  single $N symbol whose value is
  3945. equal to the $$ value of the action.  For example, in
  3946.  
  3947.           expr : expr ['+' '-'] {action} op expr
  3948.  
  3949. we have
  3950.  
  3951.           $1 -- first "expr"
  3952.           $2 -- $$ of action
  3953.           $3 -- op
  3954.           $4 -- second "expr"
  3955.  
  3956.     The %%pprreecc  construct is  incompatible  with  rules  that
  3957. contain selection preferences, because the preference is all
  3958. that is  needed to  resolve conflicts.  For this reason, YAY
  3959. issues an error message if a rule contains both a preference
  3960. and the %%pprreecc construct.
  3961.  
  3962.  
  3963.  
  3964.  
  3965. November, 1995                                       Page 63
  3966.  
  3967.  
  3968.  
  3969. YAY Reference Manual                           Thinkage Ltd.
  3970.  
  3971.  
  3972.  
  3973.     Selection  preferences  can  be  used  to  resolve  most
  3974. conflicts.   Indeed, there  may  be  cases  where  the  most
  3975. practical  course   of  action  is  to  write  a  number  of
  3976. conflicting rules  that  contain  selection  preferences  to
  3977. resolve the conflicts, as in
  3978.  
  3979.           expr : expr ['+' '-'] op expr
  3980.                | expr ['*' '/' '%'] op expr
  3981.                | expr ['&' '|'] op expr
  3982.                         ...
  3983.  
  3984.     NNoottee:: selection preferences of the form
  3985.  
  3986.           [error]
  3987.           [^ error]
  3988.  
  3989. are not  useful.    Selection  preferences  are  implemented
  3990. through (dummy)  Reduce actions,  but  the  parser's  error-
  3991. handling routines  always look  for Shift actions and ignore
  3992. Reductions.
  3993.  
  3994.  
  3995. 99..44  NNeeggaattiivvee NNuummbbeerrss iinn $$NN CCoonnssttrruuccttss
  3996.  
  3997.     YAY lets you use constructs like $0, $-1, $-2, and so on
  3998. in recognition  actions.  These were once important, but the
  3999. techniques for  specifying multiple  actions have  made them
  4000. obsolete.     YAY   only   supports   the   constructs   for
  4001. compatibility with older grammars.
  4002.  
  4003.     To  understand   what  these   constructs  mean,  it  is
  4004. important to  think in  terms of  the state  stack.  Each $N
  4005. construct is associated with a state on the stack; the value
  4006. of $N  is the  value of  the token  or  non-terminal  symbol
  4007. associated with the state at the time of a Reduce operation.
  4008. (Recall that  recognition  actions  are  executed  when  the
  4009. appropriate Reduce action takes place.)
  4010.  
  4011.     $1 is the value associated with the state that found the
  4012. first component  of  the  grammar  rule;  $2  is  the  value
  4013. associated with the second state, and so on.
  4014.  
  4015.     $0 is  the value  associated with  the state that was on
  4016. top of  the stack  before the first component of the grammar
  4017. rule was found.
  4018.  
  4019.     $-1 is  the value associated with the state before that,
  4020. and so  on. All  of these states are still on the stack, and
  4021. their value can be obtained in this way.
  4022.  
  4023.  
  4024.  
  4025.  
  4026.  
  4027. Page 64                                       November, 1995
  4028.  
  4029.  
  4030.  
  4031. Thinkage Ltd.                           YAY Reference Manual
  4032.  
  4033.  
  4034.  
  4035.     As an artificial example, suppose that a grammar has the
  4036. rules
  4037.  
  4038.           stmt : IF condition stmt
  4039.                | WHILE condition stmt
  4040.           condition : /* something */
  4041.                     { /* action */ }
  4042.  
  4043. The action  associated with  the condition  can use  the $-1
  4044. construct to  find out  if the  preceding token  was  IF  or
  4045. WHILE.   (Of course,  this assumes  that the only items that
  4046. can precede a condition are the IF and WHILE tokens.)  There
  4047. are occasionally  times when  this sort  of  information  is
  4048. needed.
  4049.  
  4050.  
  4051. 99..55  LLiissttss aanndd HHaannddlliinngg NNuullll SSttrriinnggss
  4052.  
  4053.     Grammars often  define lists  of items.   There  are two
  4054. common ways to do this:
  4055.  
  4056.           list : item
  4057.                | list item ;
  4058.  
  4059. or
  4060.  
  4061.           list : /* null */
  4062.                | list item ;
  4063.  
  4064. The first  definition means  that every  "list" has at least
  4065. one item.  The second allows zero-length lists.
  4066.  
  4067.     Using the  second definition  is sometimes  necessary or
  4068. convenient, but  it can lead to difficulties.  To understand
  4069. why, consider a grammar with
  4070.  
  4071.           list1 : /* null */
  4072.                 | list1 item1 ;
  4073.           list2 : /* null */
  4074.                 | list2 item2 ;
  4075.           list  : list1
  4076.                 | list2 ;
  4077.  
  4078.     When the  parser is  in a position to look for a "list",
  4079. it automatically  finds a  null string, then gets a conflict
  4080. because it can't decide if the null string is an instance of
  4081. "list1" or  "list2".   This problem is less likely to happen
  4082. if you define
  4083.  
  4084.  
  4085.  
  4086.  
  4087.  
  4088.  
  4089. November, 1995                                       Page 65
  4090.  
  4091.  
  4092.  
  4093. YAY Reference Manual                           Thinkage Ltd.
  4094.  
  4095.  
  4096.  
  4097.           list1 : item1
  4098.                 | list1 item1 ;
  4099.           list2 : item2
  4100.                 | list2 item2 ;
  4101.           list  : /* null */
  4102.                 | list1
  4103.                 | list2
  4104.                 ;
  4105.  
  4106. The parser can determine if it has a "list1" or a "list2" by
  4107. seeing if the list starts with "item1" or "item2".
  4108.  
  4109.     A YAY-produced  parser avoids  infinite recursions  that
  4110. might result  from matching  the same  null string  over and
  4111. over again.   If  the parser  matches a  null  string  in  a
  4112. particular state,  goes through a few more states and shifts
  4113. once more  into the state where the null string was matched,
  4114. it will  not match  the null  string again.    Without  this
  4115. behaviour, you  get infinite  recursions  on  null  strings.
  4116. However, the  behaviour occasionally  gets in the way if you
  4117. _w_a_n_t to  match more  than one  null string  in a  row.   For
  4118. example, consider  how you might write the grammar rules for
  4119. types that may be used in a C cast operation, as in
  4120.  
  4121.           char_ptr = (char *) float_ptr;
  4122.  
  4123. The rules  for the  parenthesized cast  expression might  be
  4124. written as
  4125.  
  4126.           cast : '(' basic_type opt_abstract ')' ;
  4127.           opt_abstract : /* null */
  4128.                        | abstract;
  4129.           abstract : '(' abstract ')'
  4130.                    | opt_abstract '[' ']'
  4131.                    | opt_abstract '(' ')'
  4132.                    | '*' opt_abstract
  4133.                    ;
  4134.  
  4135. Consider what happens with a cast like
  4136.  
  4137.           (int *[])
  4138.  
  4139. This  will   be  interpreted   as  *   followed  by  a  null
  4140. "opt_abstract" followed by a null "opt_abstract" followed by
  4141. square brackets.   However,  the parser  will _n_o_t accept two
  4142. null "opt_abstracts"  in a  row, and  will take  some  other
  4143. course of action.
  4144.  
  4145.     To correct  this problem,  you must  rewrite the grammar
  4146. rules.   Instead of  using the  "opt_abstract"  rules,  have
  4147. rules with and without an "abstract".
  4148.  
  4149.  
  4150.  
  4151. Page 66                                       November, 1995
  4152.  
  4153.  
  4154.  
  4155. Thinkage Ltd.                           YAY Reference Manual
  4156.  
  4157.  
  4158.  
  4159.  
  4160.           cast : '(' basic_type abstract ')' ;
  4161.           abstract : /* null */
  4162.                    | abstract '[' ']'
  4163.                    | '[' ']'
  4164.                    | abstract '(' ')'
  4165.                    | '(' ')'
  4166.                    | '*' abstract
  4167.                    | '*'
  4168.                    ;
  4169.  
  4170.  
  4171. 99..66  RRiigghhtt vvss.. LLeefftt RReeccuurrssiioonn
  4172.  
  4173.     Chapter 3  mentioned left  and  right  recursion.    For
  4174. example, if  a program  consists of  a number  of statements
  4175. separated by  semicolons, we  might  define  it  with  right
  4176. recursion as
  4177.  
  4178.           program : statement
  4179.                   | statement ';' program ;
  4180.  
  4181. or with left recursion as
  4182.  
  4183.           program : statement
  4184.                   | program ';' statement ;
  4185.  
  4186. If you  think about  the way that the state stack works, you
  4187. will see  that the  second way  is  much  to  be  preferred.
  4188. Consider, for example, the way something like
  4189.  
  4190.           S1 ; S2 ; S3 ; S4
  4191.  
  4192. would be handled (where all the Sn's are statements).
  4193.  
  4194.     With right  recursion, the parser would gather "S1;" and
  4195. then go  looking for  a program.  To gather this program, it
  4196. would gather S2.  It would then look at the lookahead symbol
  4197. ; and see that this program had the form
  4198.  
  4199.           statement ';' program
  4200.  
  4201. The parser  would then go ahead and gather the program after
  4202. the  semicolon.    But  after  S3,  it  would  find  another
  4203. semicolon, so would begin gathering yet another program.  If
  4204. you work  the process  through, you will find that the state
  4205. stack grows  to seven  entries (one  for each Sn and one for
  4206. each ;) before the first Reduce takes place.
  4207.  
  4208.  
  4209.  
  4210.  
  4211.  
  4212.  
  4213. November, 1995                                       Page 67
  4214.  
  4215.  
  4216.  
  4217. YAY Reference Manual                           Thinkage Ltd.
  4218.  
  4219.  
  4220.  
  4221.     On the other hand, if you have the left recursion
  4222.  
  4223.           program : program ';' statement
  4224.  
  4225. and the same input, the parser will perform a Reduce as soon
  4226. as it sees
  4227.  
  4228.           S1 ; S2
  4229.  
  4230. This is  Reduced to a single state corresponding to the non-
  4231. terminal symbol  "program".   The  parser  reads  ";S3"  and
  4232. Reduces
  4233.  
  4234.           program ; S3
  4235.  
  4236. to "program"  again.   The  process  repeats  for  the  last
  4237. statement.
  4238.  
  4239.     If you  follow this through, the state stack never grows
  4240. longer than  three states, as compared to the seven that are
  4241. required  for   the  right   recursive  rule.    With  right
  4242. recursion, no reduction takes place until the entire list of
  4243. elements has  been read;  with left  recursion, a  reduction
  4244. takes place  as each  new list element is encountered.  Left
  4245. recursion can therefore save a lot of stack space.
  4246.  
  4247.     The choice  of left  or right  recursion can also affect
  4248. the  order  in  which  recognition  actions  are  performed.
  4249. Suppose T is a token.  If we define
  4250.  
  4251.           x : /* null */
  4252.             | y ',' x {a1} ;
  4253.           y : T {a2} ;
  4254.  
  4255. then the input
  4256.  
  4257.           T , T , T
  4258.  
  4259. would execute recognition actions in the order
  4260.  
  4261.           {a2} {a2} {a2} {a1} {a1} {a1}
  4262.  
  4263. The {a2}  actions are  performed each time a T is Reduced to
  4264. "y".   The {a1}  actions don't  happen until the entire list
  4265. has been read, because right recursion reads the entire list
  4266. before any Reduce actions take place.
  4267.  
  4268.  
  4269.  
  4270.  
  4271.  
  4272.  
  4273.  
  4274.  
  4275. Page 68                                       November, 1995
  4276.  
  4277.  
  4278.  
  4279. Thinkage Ltd.                           YAY Reference Manual
  4280.  
  4281.  
  4282.  
  4283.     On the other hand, if you define
  4284.  
  4285.           x : /* null */
  4286.             | x ',' y {a1} ;
  4287.           y : T {a2};
  4288.  
  4289. the recognition  actions for  the same input will take place
  4290. in the order
  4291.  
  4292.           {a2} {a1} {a2} {a1} {a2} {a1}
  4293.  
  4294. With left  recursion, Reduce actions take place every time a
  4295. new element is read in for the list.
  4296.  
  4297.     This means that if you want the action order
  4298.  
  4299.           {a2} {a2} {a2} {a1} {a1} {a1}
  4300.  
  4301. you must use right recursion even though it takes more stack
  4302. space.
  4303.  
  4304.  
  4305. 99..77  YYYYDDEEBBUUGG
  4306.  
  4307.     If  you   ##ddeeffiinnee  a   symbol  named   YYDEBUG  in   the
  4308. declarations section  and set  the variable  "yydebug" to  a
  4309. non-zero value,  your parser  will  print  a  good  deal  of
  4310. debugging  information   as  it   parses  input.    In  this
  4311. description, we will describe the output you may see.
  4312.  
  4313.     Every time "yylex" obtains a token, the parser prints
  4314.  
  4315.           read T (VALUE)
  4316.  
  4317. T is  the name  of the token and VALUE is the numeric value.
  4318. Thus if "yylex" has read an IF token, you might see
  4319.  
  4320.           read IF (257)
  4321.  
  4322.     Every time the parser enters a state, it will print out
  4323.  
  4324.           state N (X), char (C)
  4325.  
  4326. where  N   is  the  state  number  as  given  in  the  State
  4327. Description report,  and X  and C  are other integers.  X is
  4328. another number  for the  state -- YAY actually renumbers the
  4329. states and  grammar  rules  after  it  generates  the  State
  4330. Description  report   in  order   to  improve  the  parser's
  4331. efficiency, and  X gives the state number after renumbering.
  4332. C is the token type of the lookahead symbol if the symbol is
  4333.  
  4334.  
  4335.  
  4336.  
  4337. November, 1995                                       Page 69
  4338.  
  4339.  
  4340.  
  4341. YAY Reference Manual                           Thinkage Ltd.
  4342.  
  4343.  
  4344.  
  4345. a token.   If  the symbol  is not a token, or if there is no
  4346. lookahead symbol at the moment, C is -1.  As an example,
  4347.  
  4348.           state 6 (22), char (-1)
  4349.  
  4350. indicates that  the parser  has entered State 6 on the State
  4351. Description Report (State 22 after renumbering) and that the
  4352. current lookahead symbol is not a token.
  4353.  
  4354.     Every time the parser performs a Shift action, it prints
  4355.  
  4356.           shift N (X)
  4357.  
  4358. where N  is the  number of  the state to which the parser is
  4359. shifting and  X is  the  number  of  the  same  state  after
  4360. renumbering.
  4361.  
  4362.     Every time  the parser  performs  a  Reduce  action,  it
  4363. prints
  4364.  
  4365.           reduce N (X), pops M (Y)
  4366.  
  4367. This says  that the  parser has  Reduced by  grammar rule  N
  4368. (renumbered to X).  After the reduction, the state on top of
  4369. the state stack was State M (renumbered to Y).
  4370.  
  4371.  
  4372. 99..88  IImmppoorrttaanntt SSyymmbboollss
  4373.  
  4374.     Debugging a  parser  produced  by  YAY  can  be  a  very
  4375. difficult task,  since the  code is  only partly produced by
  4376. user  input.    The  remaining  code  is  standard  software
  4377. produced by  YAY itself.   The  situation is  aggravated  by
  4378. another problem:  the state  and rule  numbers shown  in the
  4379. State Description  report are  not the  same as  the numbers
  4380. used when  the parser  actually runs.   In  the interests of
  4381. optimization, the  parser  sorts  the  states  into  a  more
  4382. convenient order.   Thus  the _i_n_t_e_r_n_a_l  state number used by
  4383. the program  is usually  not the  same as the _e_x_t_e_r_n_a_l state
  4384. number known to the user.
  4385.  
  4386.     To help  those who  are examining  parser code  using  a
  4387. symbolic debugger, here are a few of the important variables
  4388. that the parser uses.
  4389.  
  4390. yyval
  4391.      holds the  value $$  at the  time of a reduction.  This
  4392.      has the type YYSTYPE.
  4393.  
  4394. yychar
  4395.      holds the most recent token value returned by "yylex".
  4396.  
  4397.  
  4398.  
  4399. Page 70                                       November, 1995
  4400.  
  4401.  
  4402.  
  4403. Thinkage Ltd.                           YAY Reference Manual
  4404.  
  4405.  
  4406.  
  4407.  
  4408. yystate
  4409.      is the _i_n_t_e_r_n_a_l number of the current state.
  4410.  
  4411. yyps
  4412.      points to  the current  top of  the state  stack.  Thus
  4413.      yyps[0] is  the internal  number of  the current state,
  4414.      yyps[-1] is  the internal number of the previous state,
  4415.      and so on.
  4416.  
  4417. yypv
  4418.      points to  the top  of the  current value  stack.   The
  4419.      entries in  this stack  have the  type YYSTYPE.  When a
  4420.      Reduce operation  executes a  recognition action,  this
  4421.      pointer is moved down the stack to the point where
  4422.  
  4423.           yypv[1] = $1
  4424.           yypv[2] = $2
  4425.               etc.
  4426.  
  4427. yyi
  4428.      is the  internal number  of the rule being reduced by a
  4429.      Reduce action.
  4430.  
  4431. yyrmap
  4432.      is an  array present  only when YYDEBUG is defined.  It
  4433.      is used  to convert  internal rule  numbers to external
  4434.      ones.  For example,
  4435.  
  4436.           yyrmap[yyi]
  4437.  
  4438.      is the  external number  of the rule being reduced by a
  4439.      Reduce action.
  4440.  
  4441. yysmap
  4442.      is an  array present  only when YYDEBUG is defined.  It
  4443.      is used  to convert  internal state numbers to external
  4444.      ones.  For example,
  4445.  
  4446.           yysmap[yystate]
  4447.  
  4448.      is the external number of the current state.
  4449.  
  4450.  
  4451. 99..99  HHooww YYYYEERRRROORR MMaayy BBee UUsseedd
  4452.  
  4453.     The YYERROR macro creates an artificial error condition.
  4454. To show  how this  can be useful, suppose we have a line-by-
  4455. line  desk   calculator  that   allows  parenthesization  of
  4456. expressions and  suppose we  have a  variable named  "depth"
  4457. that keeps  track of  how  deeply  parentheses  are  nested.
  4458.  
  4459.  
  4460.  
  4461. November, 1995                                       Page 71
  4462.  
  4463.  
  4464.  
  4465. YAY Reference Manual                           Thinkage Ltd.
  4466.  
  4467.  
  4468.  
  4469. Every time  the parser finds an opening parenthesis, it adds
  4470. 1 to "depth".  Every time it finds a closing parenthesis, it
  4471. subtracts 1.
  4472.  
  4473.     Consider how the following definitions will work.
  4474.  
  4475.           expr : lp expr ')'
  4476.                     {depth--;}
  4477.                | lp error
  4478.                     {depth--;}
  4479.                ;
  4480.           lp : '(' {depth++;};
  4481.  
  4482.     If no  error occurs, the "depth" variable is incremented
  4483. and decremented correctly.  If an error does occur, however,
  4484. what happens?   Your  "yyerror"  routine  is  called  on  to
  4485. recover from  the error  in the  middle  of  an  expression.
  4486. Often, it is more reasonable to postpone this recovery until
  4487. you reach  a  point  where  you  have  a  whole  expression.
  4488. Therefore, you might use the following alternate definition.
  4489.  
  4490.           expr : lp error
  4491.                     {depth--; YYERROR;}
  4492.                ;
  4493.           line : error '\n' prompt line
  4494.                  { $$ = $4; } ;
  4495.           prompt : /* null token */
  4496.                  {printf("Please re-enter line.\n");};
  4497.  
  4498. Now, what  happens when the grammar is asked to parse a line
  4499. like
  4500.  
  4501.           1 + (( a +
  4502.  
  4503. When  the  end  of  the  line  is  encountered,  the  parser
  4504. recognizes an  error has  occurred.  Going up the stack, the
  4505. first state ready to handle the error is
  4506.  
  4507.           expr : lp error ;
  4508.  
  4509. At this point, the parser will Reduce the input
  4510.  
  4511.           ( a +
  4512.  
  4513. into an  "expr".   The Reduction  executes  the  recognition
  4514. action: it  decrements "depth",  then signals  that an error
  4515. has taken  place.  The Error action begins popping the stack
  4516. again.   It will  find  the  previous  opening  parenthesis,
  4517. recognize another
  4518.  
  4519.           lp error
  4520.  
  4521.  
  4522.  
  4523. Page 72                                       November, 1995
  4524.  
  4525.  
  4526.  
  4527. Thinkage Ltd.                           YAY Reference Manual
  4528.  
  4529.  
  4530.  
  4531.  
  4532. construct and  perform another  reduction.   The parenthesis
  4533. count is  again decremented,  and  another  error  condition
  4534. generated.
  4535.  
  4536.     This time, the grammar rule that deals with the error is
  4537. the definition  of "line".  An error message is issued and a
  4538. new line  is requested.   In this way, the parser has worked
  4539. its way  back to  error-handling code that can deal with the
  4540. situation.   Along the way, the parser correctly decremented
  4541. the "depth" variable to account for the missing parentheses.
  4542.  
  4543.     This method  of dealing  with errors  decrements "depth"
  4544. for every  unbalanced opening parenthesis on the line.  This
  4545. corrects the  "depth" count  properly.  Our first definition
  4546. (without the  YYERROR  call)  would  only  have  decremented
  4547. "depth" once.
  4548.  
  4549.     This example  is somewhat  contrived, of  course --  you
  4550. could always just set "depth" to zero whenever you started a
  4551. new line  of input.  The usefulness of the technique is more
  4552. apparent in situations where you obtain memory with "malloc"
  4553. whenever you  get an  opening delimiter  and free the memory
  4554. with "free"  whenever you  get a closing delimiter.  In this
  4555. case, it  is obvious  that you  need to do precisely as many
  4556. "free" operations  as "malloc" operations, so you must raise
  4557. the error condition for each unbalanced opening delimiter.
  4558.  
  4559.     You might think that the symbol "lp" is unnecessary, and
  4560. you could just define
  4561.  
  4562.           expr : '(' {depth++;} expr ')' {depth--;}
  4563.                | '(' error {depth--;} ;
  4564.  
  4565. However, this  would not  work in  general.    There  is  no
  4566. guarantee that the action
  4567.  
  4568.           {depth++;}
  4569.  
  4570. would be  executed in  all cases,  particularly if the token
  4571. after the '(' was one that could not start an expression.
  4572.  
  4573.     As an interesting example of another way to use YYERROR,
  4574. consider the  following (taken  from a parser for the Pascal
  4575. programming language).
  4576.  
  4577. label_list : label_list ',' label
  4578.            | label
  4579.            | error
  4580.            | error [LABEL CONST VAR PROC FUNC BEGIN]
  4581.                 {YYERROR; /* more code */};
  4582.  
  4583.  
  4584.  
  4585. November, 1995                                       Page 73
  4586.  
  4587.  
  4588.  
  4589. YAY Reference Manual                           Thinkage Ltd.
  4590.  
  4591.  
  4592.  
  4593.  
  4594. This deals with errors in two different ways:
  4595.  
  4596. (a)  If an  error is  followed by  one of  the tokens LABEL,
  4597.      CONST,  etc.   (representing  the   beginning  of   new
  4598.      declaration sections  in Pascal),  the input is reduced
  4599.      to a  complete  "label_list"  input  is  Reduced  to  a
  4600.      complete "label_list"  and  an  appropriate  action  is
  4601.      taken.   This action  uses YYERROR  to raise  the error
  4602.      condition, but  only  _a_f_t_e_r  the  reduction  has  taken
  4603.      place.
  4604.  
  4605. (b)  The other  rule is  used when the parser finds an error
  4606.      which is  not followed  by one  of the  listed  tokens.
  4607.      This corresponds  to an  error in the middle of a label
  4608.      list and  requires a  different sort  of handling.   In
  4609.      this case,  error-handling is  allowed  to  take  place
  4610.      immediately, without  reduction, because  there may  be
  4611.      more "label_list" to come.
  4612.  
  4613.     This  kind  of  approach  can  be  used  to  distinguish
  4614. different  kinds   of  errors  that  may  take  place  in  a
  4615. particular situation.
  4616.  
  4617.  
  4618. 99..1100  TThhee DDeeffaauulltt AAccttiioonn
  4619.  
  4620.     The default  action is  the one  that is  taken when the
  4621. parser finds  a token  which has  no specified effect in the
  4622. current state.   Understanding how default actions work will
  4623. help you  understand what  is going  on when  a YAY-produced
  4624. parser encounters an error.
  4625.  
  4626.     In a  state diagram, the default action is marked with a
  4627. ".". The  default will  always be  a Reduce or Error action,
  4628. chosen according to the following rules.
  4629.  
  4630. (a)  If the  state has no Shift actions and only one Reduce,
  4631.      the default will be the Reduce action.
  4632.  
  4633. (b)  Apart from (a), an empty rule will never have Reduce as
  4634.      a default.
  4635.  
  4636. (c)  If a  state has more than one Reduce action, the parser
  4637.      examines the "popularity" of each Reduce.  For example,
  4638.      if Reduction  A is  used with  any of  three  different
  4639.      input tokens  and Reduction  B is  used with  only  one
  4640.      input token, Reduction A is three times as "popular" as
  4641.      B.   If one Reduce action is more than twice as popular
  4642.      as its  closest contender  (i.e. if it is taken on more
  4643.      than twice  as many  input tokens),  and if that Reduce
  4644.  
  4645.  
  4646.  
  4647. Page 74                                       November, 1995
  4648.  
  4649.  
  4650.  
  4651. Thinkage Ltd.                           YAY Reference Manual
  4652.  
  4653.  
  4654.  
  4655.      action  is   associated  with   a  rule  that  contains
  4656.      reductions on  at least _f_i_v_e tokens, the popular Reduce
  4657.      action is made the default.
  4658.  
  4659. (d)  In all other cases, the default action will be an Error
  4660.      action.   For example,  Error is chosen when a rule has
  4661.      more than  one Reduce  action, and  there is  no Reduce
  4662.      that is  more than  twice as  popular as  all the other
  4663.      contenders.
  4664.  
  4665.     Note: YAY's  predecessor YACC  always chooses  the  most
  4666. popular Reduce action as default (if there is one).  It does
  4667. not use  the same requirements as (c) above.  As a result of
  4668. this difference  YAY's parser  tables are  about 20%  larger
  4669. than YACC's,  but a  YAY-generated  parser  usually  detects
  4670. errors much earlier than a parser generated by YACC.
  4671.  
  4672.     Because of  the way  default actions are treated, a YAY-
  4673. produced  parser  will  sometimes  begin  reducing  when  it
  4674. encounters an  error.   Several reductions  may  take  place
  4675. before the  error state  is finally  triggered.   Thus  your
  4676. grammar may  need some  way to  determine what  actions have
  4677. taken place between the time the erroneous token was read in
  4678. and the time that the error was actually triggered.
  4679.  
  4680.  
  4681. 99..1111  IInnvvaalliidd TTookkeennss
  4682.  
  4683.     It is invalid to say either
  4684.  
  4685.           %token X 0
  4686.               or
  4687.           %token X 256
  4688.  
  4689. The value  0 is  reserved for  the end  marker  and  256  is
  4690. reserved for "error".
  4691.  
  4692.  
  4693. 99..1122  DDyynnaammiicc SSttaacckk AAllllooccaattiioonn
  4694.  
  4695.     The manifest  YYSSIZE is  used to  determine the size of
  4696. the state and value stacks used by "yyparse".  YYSSIZE gives
  4697. the maximum  number of  elements that  these stacks  will be
  4698. expected to hold; the size of each value element is dictated
  4699. by the  YYSTYPE type  and the  size of each state element is
  4700. determined by YAY.  The default value of YYSSIZE is 150.  By
  4701. increasing the  value of YYSSIZE, you can allow for grammars
  4702. with a larger number of pending states.
  4703.  
  4704.     If you  ##ddeeffiinnee YYALLOC in the declarations section, the
  4705. state and  value stacks  used by "yyparse" will be allocated
  4706.  
  4707.  
  4708.  
  4709. November, 1995                                       Page 75
  4710.  
  4711.  
  4712.  
  4713. YAY Reference Manual                           Thinkage Ltd.
  4714.  
  4715.  
  4716.  
  4717. dynamically via "malloc" and freed before "yyparse" returns.
  4718. What this  effectively means  is that "yyparse" makes itself
  4719. re-entrant by  saving a  number of  externals when it begins
  4720. execution and restoring them upon completion.  The externals
  4721. involved are
  4722.  
  4723.           yylval   yyval   yypvt
  4724.           yynerrs  yychar  yyerrflag
  4725.  
  4726. If you  "longjmp" out  of "yyparse"  (due to an action), the
  4727. externals are  _n_o_t restored,  and "yyparse"  will not be re-
  4728. entrant.
  4729.  
  4730.     If you use YYALLOC, "yyerror" will be called if "malloc"
  4731. fails to allocate space for the state and value stacks.
  4732.  
  4733.     If you ##ddeeffiinnee YYALLOC with a value greater than 10, the
  4734. parser allocates  the state  and value  stacks  dynamically,
  4735. beginning with a size of YYSSIZE.  If this is not big enough
  4736. to hold  the two stacks, "yyparse" attempts to use "realloc"
  4737. to grow  the stacks  by the  amount given  by YYALLOC.   For
  4738. example, if  YYALLOC is  20, "yyparse"  tries  to  grow  the
  4739. stacks to  a size  that will  allow 20  additional  elements
  4740. (whenever  "yyparse"  needs  more  space  for  the  stacks).
  4741. "yyerror" is  called if  the  call  to  "realloc"  fails  to
  4742. allocate additional space.
  4743.  
  4744.     If you set up your parser in such a way that it may grow
  4745. the stacks, you must be careful not to take a pointer into a
  4746. stack in  one action and use that pointer inside a different
  4747. action.   The reason  is that  the stack  may be grown using
  4748. "realloc" in  between the  two actions.  Since "realloc" may
  4749. actually move  the entire  stack, the pointer will no longer
  4750. be  valid.    Thus  you  should  not  create  pointers  with
  4751. expressions like
  4752.  
  4753.           &($1)
  4754.  
  4755. and expect  those pointers  to be  valid in  other  actions.
  4756. Within the  code of  a single action, however, such pointers
  4757. wwiillll remain valid.
  4758.  
  4759.     If you ##ddeeffiinnee YYSTATIC, both the state and value stacks
  4760. will be  static.   Otherwise, the state stack will be "auto"
  4761. (allocated on the program stack) and the value stack will be
  4762. static.   Defining YYALLOC saves both stack space and static
  4763. space; defining YYSTATIC saves stack space.
  4764.  
  4765.  
  4766.  
  4767.  
  4768.  
  4769.  
  4770.  
  4771. Page 76                                       November, 1995
  4772.  
  4773.  
  4774.  
  4775. Thinkage Ltd.                           YAY Reference Manual
  4776.  
  4777.  
  4778.  
  4779.  
  4780. 99..1133  SSyynncchhrroonniizziinngg tthhee LLooookkaahheeaadd
  4781.  
  4782.     If you  ##ddeeffiinnee YYSYNC,  the parser  will always  have a
  4783. lookahead token  when it  performs a shift or reduce action.
  4784. If the  symbol is not defined, the parser will only obtain a
  4785. lookahead token if the value of the token is needed.
  4786.  
  4787.     You would  define YYSYNC  in situations where you wanted
  4788. to keep track of the line number on which various situations
  4789. occurred (e.g. errors).  If "yylex" _a_l_w_a_y_s does a lookahead,
  4790. you know  that the  line number of the token you are working
  4791. with is  the line  number of the second last token read.  If
  4792. "yylex" sometimes does not do a lookahead, you don't know if
  4793. the current  line number  in "yylex"  is the line number for
  4794. the current token or for a lookahead token.
  4795.  
  4796.     You would avoid defining YYSYNC in situations where some
  4797. actions do  their own reading.  For example, suppose that /*
  4798. is a  token that  indicates the beginning of a comment.  You
  4799. could create  an action for that token which reads all input
  4800. up to a closing */.  With this kind of action, you would not
  4801. want "yylex"  to read  a lookahead  token, since  that token
  4802. would be  the first  token inside the comment, not the first
  4803. token after the comment.
  4804.  
  4805.  
  4806. 99..1144  YYYYSSHHIIFFTT
  4807.  
  4808.     The generated  parser  program  invokes  a  macro  named
  4809. YYSHIFT whenever  the parser  performs  a  shift  action  in
  4810. response  to   a  token.    The  macro  is  invoked  without
  4811. arguments.   By default,  YYSHIFT is  defined to do nothing;
  4812. however, users can redefine YYSHIFT if desired, in the token
  4813. definition part of the YAY input.
  4814.  
  4815.     As an  example of  how you might use YYSHIFT, consider a
  4816. situation where input is freeform and may be split over many
  4817. lines of text, including the insertion of blank lines in the
  4818. input.   You may want to keep a count of the number of lines
  4819. you've read  as you  parse the input so that you can provide
  4820. error messages like "Line 12: Syntax error".
  4821.  
  4822.     When the parser finishes reading a line, it often has to
  4823. read ahead to the next token before it can decide whether to
  4824. reduce what  it already  has or  keep on  reading additional
  4825. input.   Since there  may be  blank lines in the input, this
  4826. means that  the parser may actually read ahead several lines
  4827. before finding the next token.  When it sees the next token,
  4828. the parser  may decide  to reduce  what it  has seen already
  4829. before shifting in response to the token.
  4830.  
  4831.  
  4832.  
  4833. November, 1995                                       Page 77
  4834.  
  4835.  
  4836.  
  4837. YAY Reference Manual                           Thinkage Ltd.
  4838.  
  4839.  
  4840.  
  4841.  
  4842.     While the  reduction is  happening, you  want your  line
  4843. count to  reflect the  last line  of input.  You do not want
  4844. the line  count to  reflect the  line where the parser found
  4845. the new  token, because  the parser  isn't really using that
  4846. token yet;  it's working with older input.  You only want to
  4847. update the  line count  when the parser is ready to shift on
  4848. the new token.
  4849.  
  4850.     That's where  YYSHIFT comes  in.   You  can  define  the
  4851. YYSHIFT macro to update the line count at the point when the
  4852. token is actually used, not when it is first read.
  4853.  
  4854.     YYSHIFT is  _n_o_t invoked if a token is discarded (because
  4855. of error handling or some other reason).  It is only invoked
  4856. when the parser shifts on a token.
  4857.  
  4858.  
  4859.  
  4860.  
  4861.  
  4862.  
  4863.  
  4864.  
  4865.  
  4866.  
  4867.  
  4868.  
  4869.  
  4870.  
  4871.  
  4872.  
  4873.  
  4874.  
  4875.  
  4876.  
  4877.  
  4878.  
  4879.  
  4880.  
  4881.  
  4882.  
  4883.  
  4884.  
  4885.  
  4886.  
  4887.  
  4888.  
  4889.  
  4890.  
  4891.  
  4892.  
  4893.  
  4894.  
  4895. Page 78                                       November, 1995
  4896.  
  4897.  
  4898.  
  4899. Thinkage Ltd.                           YAY Reference Manual
  4900.  
  4901.  
  4902.  
  4903.                          AAppppeennddiixx AA
  4904.                          AAnn EExxaammppllee
  4905.  
  4906.     This appendix  gives a  simple example of YAY input.  We
  4907. have omitted the recognition actions of the grammar rules in
  4908. order to keep the example as simple as possible.
  4909.  
  4910.     The  parser  implements  a  simple  string  manipulation
  4911. language.    It  has  two  types  of  objects:  strings  and
  4912. variables.  Strings can have a maximum of 100 characters and
  4913. are enclosed in double quotes.  Variable names are a maximum
  4914. of eight characters long.
  4915.  
  4916.     There are three operations:
  4917.  
  4918. (a)  = assigns a string to a variable;
  4919.  
  4920. (b)  JOIN or  + concatenates  strings  or  the  contents  of
  4921.      variables;
  4922.  
  4923. (c)  PRINT outputs strings or the contents of variables.
  4924.  
  4925. Every statement  is a  single input line and blanks are used
  4926. to separate  tokens on the line.  Multiple = assignments are
  4927. permitted as in
  4928.  
  4929.           A = B = "hello"
  4930.  
  4931. The keyword PRINT can only appear once on the line.
  4932.  
  4933.     If a  line does  not contain an assignment, the value of
  4934. the expression  on the  line is  merely printed  out.   This
  4935. means that  it is  valid to have a line that only contains a
  4936. string or  a variable name.  The end of the input file marks
  4937. the end of input.
  4938.  
  4939.     Here are  the declarations  section of the YAY input and
  4940. the "yylex" routine (both written in C).
  4941.  
  4942. %{   /* declarations */
  4943. #include <stdio.h>
  4944. #define MAXSTRING 100
  4945. char str[MAXSTRING];
  4946. #define MAXVAR 8
  4947. char var[MAXVAR];
  4948. %}
  4949.  
  4950. %token VARIABLE STRING
  4951. %nonassoc PRINT
  4952. %right '='
  4953. %left JOIN
  4954.  
  4955.  
  4956.  
  4957. November, 1995                                       Page 79
  4958.  
  4959.  
  4960.  
  4961. YAY Reference Manual                           Thinkage Ltd.
  4962.  
  4963.  
  4964.  
  4965. %union {
  4966.      char *cstr;
  4967. }
  4968. %%
  4969.  
  4970. program : stat
  4971.         | program stat
  4972.         ;
  4973. stat : printexpr '\n'
  4974.      | expr '\n'
  4975.      ;
  4976. printexpr : PRINT expr ;
  4977. expr : VARIABLE '=' expr
  4978.      | JOIN expr expr
  4979.      | STRING
  4980.      | VARIABLE
  4981.      ;
  4982. %%
  4983.  
  4984. int yylex()
  4985. {
  4986.     char c, *stringet(), *wordget();
  4987.     extern YYSTYPE yylval;
  4988.     while ( (c=getchar()) == ' ' )
  4989.            /* skip blanks */;
  4990.     switch(c) {
  4991.       case '\n':    /* end of line */
  4992.           return('\n');
  4993.       case EOF:     /* end of file */
  4994.           return(0);
  4995.       case '+':     /* same as JOIN */
  4996.           return(JOIN);
  4997.       case '"':     /* start of string */
  4998.           yylval.cstr = stringet();
  4999.           return(STRING);
  5000.       default:      /* keyword or variable */
  5001.           yylval.cstr = wordget(c);
  5002.           if ( !strcmp("JOIN",yylval.cstr) )
  5003.               return(JOIN);
  5004.           else if ( !strcmp("PRINT",yylval.cstr) )
  5005.               return(PRINT);
  5006.           else return(VARIABLE);
  5007.     }
  5008. }
  5009.  
  5010. char *stringet()
  5011. {
  5012.     extern char str[];
  5013.     int i;
  5014.  
  5015.  
  5016.  
  5017.  
  5018.  
  5019. Page 80                                       November, 1995
  5020.  
  5021.  
  5022.  
  5023. Thinkage Ltd.                           YAY Reference Manual
  5024.  
  5025.  
  5026.  
  5027.     for ( i=0; i < MAXSTRING; i++ ) {
  5028.         str[i] = getchar();
  5029.         if ( (str[i]=='"') || (str[i]=='\n') )
  5030.             break;
  5031.     }
  5032.     str[i] = '\0';  /* mark end of string */
  5033.     return(str);
  5034. }
  5035.  
  5036. char *wordget(char c)
  5037. {
  5038.     extern char var[];
  5039.     int i;
  5040.     var[0] = c;  /* first letter obtained already */
  5041.     for ( i=1; i < MAXVAR; i++ ) {
  5042.         var[i] = getchar();
  5043.         if ( (var[i]==' ') || (var[i]=='\n') )
  5044.             break;
  5045.     }
  5046.     var[i] = '\0';
  5047.     return(var);
  5048. }
  5049.  
  5050. void yyerror(char *s)
  5051. {
  5052.     fprintf(stderr,s);
  5053. }
  5054.  
  5055.     Note that the lexical analyzer always flags the keywords
  5056. JOIN and  PRINT as  operations.   This means that you cannot
  5057. use JOIN  or PRINT  as variable  names.   In fact, this is a
  5058. general limitation of LALR(1) parsers.  It is very difficult
  5059. to have  names  that  are  keywords  in  some  contexts  and
  5060. variable names  in others, without a great deal of fiddling.
  5061. Therefore, we  recommend that  you resign yourself to having
  5062. _r_e_s_e_r_v_e_d  keywords,  i.e.  keywords  forbidden  for  use  as
  5063. variable names.
  5064.  
  5065.     The above  example omitted  recognition actions  in  the
  5066. Rules Section to make things easier to read.
  5067.  
  5068.  
  5069.  
  5070.  
  5071.  
  5072.  
  5073.  
  5074.  
  5075.  
  5076.  
  5077.  
  5078.  
  5079.  
  5080.  
  5081. November, 1995                                       Page 81
  5082.  
  5083.  
  5084.  
  5085. YAY Reference Manual                           Thinkage Ltd.
  5086.  
  5087.  
  5088.  
  5089.                          AAppppeennddiixx BB
  5090.                         YYAAYY vvss.. YYAACCCC
  5091.  
  5092.     YAY differs  from its  predecessor YACC  in a  number of
  5093. respects. These are summarized below.
  5094.  
  5095. (a)  YACC does not support the following.
  5096.  
  5097.      -- all the LALR(2) features described in 9.1
  5098.      -- selection preferences, as described in 9.3
  5099.      -- the use of YYSTATIC, YYSYNC, or YYALLOC (9.12)
  5100.  
  5101. (b)  If a  state has  several  Reduce  action,  YACC  always
  5102.      chooses the  most  popular  of  these  as  the  default
  5103.      action.   YAY's rules  for choosing a default are given
  5104.      in 9.10.  In general, YAY's approach will detect errors
  5105.      more quickly (sooner after they actually occur).
  5106.  
  5107. (c)  The two  programs  handle  YYERROR  differently.    YAY
  5108.      always reduces and pops the current state off the stack
  5109.      before generating the artificial error condition.  YACC
  5110.      doesn't do  this.   With YACC,  you cannot  use YYERROR
  5111.      inside a  rule with  "error" in  it; YAY, however, will
  5112.      resolve  the   current  rule  and  then  trigger  error
  5113.      handling.
  5114.  
  5115. (d)  Output from the two programs differs slightly.
  5116.  
  5117.     As a  rule of  thumb, YAY  accepts any  YACC grammar and
  5118. creates a  parser that  behaves the  same for correct input.
  5119. However, the YAY version usually detects errors earlier than
  5120. the YACC  parser, and  has more  Error actions  in the state
  5121. tables.
  5122.  
  5123.  
  5124.  
  5125.  
  5126.  
  5127.  
  5128.  
  5129.  
  5130.  
  5131.  
  5132.  
  5133.  
  5134.  
  5135.  
  5136.  
  5137.  
  5138.  
  5139.  
  5140.  
  5141.  
  5142.  
  5143. Page 82                                       November, 1995
  5144.  
  5145.  
  5146.  
  5147. Thinkage Ltd.                           YAY Reference Manual
  5148.  
  5149.  
  5150.  
  5151.                          AAppppeennddiixx CC
  5152.                    TThhee LLIINNTT CCoommmmaanndd LLiinnee
  5153.  
  5154. _S_y_n_t_a_x_:
  5155.           yay sourcefile Parser=outfile [option]*
  5156.  
  5157.           (+|-)LR2 (-)            (+|-)Verbose (-)
  5158.           (+|-)Warnings (+)       Description=file
  5159.           Header=file             INSTallation=file
  5160.           Language=C|C++ (C)      Parser=file
  5161.  
  5162. _E_x_a_m_p_l_e_s_:
  5163.           yay cgram.y parse=myparse.c
  5164.           c myparse.c
  5165.  
  5166.           yay ccgram.y lang=c++ pars=myparse.cpp
  5167.  
  5168. _O_p_t_i_o_n_s_:
  5169. sourcefile
  5170.      is a file containing YAY input.
  5171.  
  5172. Language=C
  5173.      produces parsing  tables in the C programming language.
  5174.      This is the default.
  5175.  
  5176. Language=C++
  5177.      produces  parsing   tables  in   the  C++   programming
  5178.      language.   Note that YAY only produces the tables; the
  5179.      routines  that  use  the  tables  to  parse  input  are
  5180.      predefined.
  5181.  
  5182. +LR2
  5183.      says that  the YAY  input describes an LALR(2) grammar.
  5184.      Without +LR2,  YAY assumes that the grammar is LALR(1).
  5185.      The manual describes modifications that need to be made
  5186.      for LALR(2) grammars.
  5187.  
  5188. Description=file
  5189.      translates the parsing tables into a format that humans
  5190.      can read, and writes this output into the given file.
  5191.  
  5192. Header=file
  5193.      writes  token   definitions   and   other   information
  5194.      necessary for separate compilation, to the named file.
  5195.  
  5196. INSTallation=file
  5197.      tells YAY  where to  find the  installation file.   The
  5198.      installation  file   tells   where   various   software
  5199.      components have  been installed.  For more information,
  5200.      see the section on _I_n_s_t_a_l_l_a_t_i_o_n_ _F_i_l_e_s below.
  5201.  
  5202.  
  5203.  
  5204.  
  5205. November, 1995                                       Page 83
  5206.  
  5207.  
  5208.  
  5209. YAY Reference Manual                           Thinkage Ltd.
  5210.  
  5211.  
  5212.  
  5213.      If you  do not  specify an  INSTallation= option on the
  5214.      command line,  YAY checks  for an  environment variable
  5215.      named YAY_INST  and uses  its value  as the name of the
  5216.      installation file.   If  this environment variable does
  5217.      not exist, YAY uses the default installation file.
  5218.  
  5219. Parser=file
  5220.      writes the  resulting source  code for  the parser into
  5221.      the named  file.   If this  option is omitted, YAY just
  5222.      checks the syntax of your input.
  5223.  
  5224. +Verbose
  5225.      produces verbose  output  --  everything  that  can  be
  5226.      flagged is flagged.
  5227.  
  5228. -Warnings
  5229.      suppresses  a  number  of  warning  messages  that  YAY
  5230.      normally issues.
  5231.  
  5232. _D_e_s_c_r_i_p_t_i_o_n_:
  5233.     YAY converts  your context-free  grammar into a C or C++
  5234. program that is written to the file specified by the Parser=
  5235. option.
  5236.  
  5237.     If you  use the  Description= option,  YAY writes a full
  5238. description of  the grammar to the specified file.  YAY only
  5239. displays a brief message on the standard output, summarizing
  5240. conflicts (and  other information  if you specify +Verbose).
  5241. On the  other hand,  if you  do  not  use  the  Description=
  5242. option, YAY  writes more  information  to  standard  output,
  5243. including descriptions  of the states where conflicts occur.
  5244. In this  case, YAY  actually provides additional information
  5245. to help you identify the source of the conflicts; if you ask
  5246. for a  description file,  YAY outputs  less information when
  5247. reporting the  conflicts because  it assumes  you can  track
  5248. down additional  information by  looking at  the description
  5249. file.  For this reason, you can sometimes get a quicker idea
  5250. of what  has gone  wrong if you do not ask for a description
  5251. file.
  5252.  
  5253. _C_+_+_ _P_a_r_s_e_r_s
  5254.     In general,  you only  need to  use Language=C++  if you
  5255. intend YYSTYPE  to contain  a C++  object with constructors.
  5256. If you  intend to compile the parser with C++ but the %union
  5257. statement does not have any elements that need constructors,
  5258. it's best to use Language=C to get more efficient C code.
  5259.  
  5260.     If YYSTYPE does contain elements that need constructors,
  5261. you need  to define an appropriate constructor-like function
  5262. for the  YYSTYPE  type.    This  function  should  have  the
  5263. prototype
  5264.  
  5265.  
  5266.  
  5267. Page 84                                       November, 1995
  5268.  
  5269.  
  5270.  
  5271. Thinkage Ltd.                           YAY Reference Manual
  5272.  
  5273.  
  5274.  
  5275.  
  5276.           void name(YYSTYPE *p)
  5277.  
  5278. where "name"  can be  any valid  name.   In the declarations
  5279. section of the grammar, you must then add the statement
  5280.  
  5281.           #define YYSTYPE_INIT name
  5282.  
  5283. where "name" is the name of the constructor-like function.
  5284.  
  5285.     With Language=C++,  the  %union  statement  generates  a
  5286. structure type rather than a union, since C++ does not allow
  5287. objects with constructors to belong to unions.
  5288.  
  5289.     In many  cases, the  same grammar  may be processed with
  5290. either Language=C or Language=C++.
  5291.  
  5292. _I_n_s_t_a_l_l_a_t_i_o_n_ _F_i_l_e_s_:
  5293.     An  installation   file  specifies   the  pathnames  for
  5294. software and data files used by YAY.  Installation files are
  5295. text files made up of comment lines and option lines.
  5296.  
  5297. Comment lines:
  5298.      Any line  whose first  non-blank character is # will be
  5299.      taken as  a comment.   Blank  lines are also considered
  5300.      comments.
  5301.  
  5302. Option lines:
  5303.      Option lines have the format
  5304.  
  5305.           Keyword=pathname
  5306.  
  5307.      In this  documentation, keywords  are written with some
  5308.      letters in  upper case and some in lower case.  You may
  5309.      abbreviate keywords  by omitting  any  or  all  of  the
  5310.      letters shown in lower case.  The remaining letters may
  5311.      be  entered   in  either   upper  or  lower  case;  the
  5312.      documentation simply  uses upper  case  to  show  which
  5313.      characters may not be omitted.
  5314.  
  5315.     In this  version of  YAY, there is only one valid option
  5316. line:
  5317.  
  5318.           Library=pathname
  5319.  
  5320. The pathname  should be  the directory  containing  the  YAY
  5321. parser template files (e.g. yyparse.c).
  5322.  
  5323.  
  5324.  
  5325.  
  5326.  
  5327.  
  5328.  
  5329. November, 1995                                       Page 85
  5330.  
  5331.  
  5332.  
  5333. YAY Reference Manual                           Thinkage Ltd.
  5334.  
  5335.  
  5336.  
  5337. _N_o_t_e_s_:
  5338.     If you  define YYALLOC,  the parser  allocates its state
  5339. and value  stacks dynamically  via malloc  and free.    This
  5340. shrinks your parser and helps prevent stack overflows.
  5341.  
  5342. Copyright 1995, Thinkage Ltd.
  5343.  
  5344.  
  5345.  
  5346.  
  5347.  
  5348.  
  5349.  
  5350.  
  5351.  
  5352.  
  5353.  
  5354.  
  5355.  
  5356.  
  5357.  
  5358.  
  5359.  
  5360.  
  5361.  
  5362.  
  5363.  
  5364.  
  5365.  
  5366.  
  5367.  
  5368.  
  5369.  
  5370.  
  5371.  
  5372.  
  5373.  
  5374.  
  5375.  
  5376.  
  5377.  
  5378.  
  5379.  
  5380.  
  5381.  
  5382.  
  5383.  
  5384.  
  5385.  
  5386.  
  5387.  
  5388.  
  5389.  
  5390.  
  5391. Page 86                                       November, 1995
  5392.