home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / bison-1.25-bin.lha / info / bison.info-4 (.txt) < prev    next >
GNU Info File  |  1996-10-12  |  49KB  |  988 lines

  1. This is Info file bison.info, produced by Makeinfo-1.64 from the input
  2. file /ade-src/fsf/bison/bison.texinfo.
  3.    This file documents the Bison parser generator.
  4.    Copyright (C) 1988, 89, 90, 91, 92, 93, 1995 Free Software
  5. Foundation, Inc.
  6.    Permission is granted to make and distribute verbatim copies of this
  7. manual provided the copyright notice and this permission notice are
  8. preserved on all copies.
  9.    Permission is granted to copy and distribute modified versions of
  10. this manual under the conditions for verbatim copying, provided also
  11. that the sections entitled "GNU General Public License" and "Conditions
  12. for Using Bison" are included exactly as in the original, and provided
  13. that the entire resulting derived work is distributed under the terms
  14. of a permission notice identical to this one.
  15.    Permission is granted to copy and distribute translations of this
  16. manual into another language, under the above conditions for modified
  17. versions, except that the sections entitled "GNU General Public
  18. License", "Conditions for Using Bison" and this permission notice may be
  19. included in translations approved by the Free Software Foundation
  20. instead of in the original English.
  21. File: bison.info,  Node: Contextual Precedence,  Next: Parser States,  Prev: Precedence,  Up: Algorithm
  22. Context-Dependent Precedence
  23. ============================
  24.    Often the precedence of an operator depends on the context.  This
  25. sounds outlandish at first, but it is really very common.  For example,
  26. a minus sign typically has a very high precedence as a unary operator,
  27. and a somewhat lower precedence (lower than multiplication) as a binary
  28. operator.
  29.    The Bison precedence declarations, `%left', `%right' and
  30. `%nonassoc', can only be used once for a given token; so a token has
  31. only one precedence declared in this way.  For context-dependent
  32. precedence, you need to use an additional mechanism: the `%prec'
  33. modifier for rules.
  34.    The `%prec' modifier declares the precedence of a particular rule by
  35. specifying a terminal symbol whose precedence should be used for that
  36. rule.  It's not necessary for that symbol to appear otherwise in the
  37. rule.  The modifier's syntax is:
  38.      %prec TERMINAL-SYMBOL
  39. and it is written after the components of the rule.  Its effect is to
  40. assign the rule the precedence of TERMINAL-SYMBOL, overriding the
  41. precedence that would be deduced for it in the ordinary way.  The
  42. altered rule precedence then affects how conflicts involving that rule
  43. are resolved (*note Operator Precedence: Precedence.).
  44.    Here is how `%prec' solves the problem of unary minus.  First,
  45. declare a precedence for a fictitious terminal symbol named `UMINUS'.
  46. There are no tokens of this type, but the symbol serves to stand for its
  47. precedence:
  48.      ...
  49.      %left '+' '-'
  50.      %left '*'
  51.      %left UMINUS
  52.    Now the precedence of `UMINUS' can be used in specific rules:
  53.      exp:    ...
  54.              | exp '-' exp
  55.              ...
  56.              | '-' exp %prec UMINUS
  57. File: bison.info,  Node: Parser States,  Next: Reduce/Reduce,  Prev: Contextual Precedence,  Up: Algorithm
  58. Parser States
  59. =============
  60.    The function `yyparse' is implemented using a finite-state machine.
  61. The values pushed on the parser stack are not simply token type codes;
  62. they represent the entire sequence of terminal and nonterminal symbols
  63. at or near the top of the stack.  The current state collects all the
  64. information about previous input which is relevant to deciding what to
  65. do next.
  66.    Each time a look-ahead token is read, the current parser state
  67. together with the type of look-ahead token are looked up in a table.
  68. This table entry can say, "Shift the look-ahead token."  In this case,
  69. it also specifies the new parser state, which is pushed onto the top of
  70. the parser stack.  Or it can say, "Reduce using rule number N." This
  71. means that a certain number of tokens or groupings are taken off the
  72. top of the stack, and replaced by one grouping.  In other words, that
  73. number of states are popped from the stack, and one new state is pushed.
  74.    There is one other alternative: the table can say that the
  75. look-ahead token is erroneous in the current state.  This causes error
  76. processing to begin (*note Error Recovery::.).
  77. File: bison.info,  Node: Reduce/Reduce,  Next: Mystery Conflicts,  Prev: Parser States,  Up: Algorithm
  78. Reduce/Reduce Conflicts
  79. =======================
  80.    A reduce/reduce conflict occurs if there are two or more rules that
  81. apply to the same sequence of input.  This usually indicates a serious
  82. error in the grammar.
  83.    For example, here is an erroneous attempt to define a sequence of
  84. zero or more `word' groupings.
  85.      sequence: /* empty */
  86.                      { printf ("empty sequence\n"); }
  87.              | maybeword
  88.              | sequence word
  89.                      { printf ("added word %s\n", $2); }
  90.              ;
  91.      
  92.      maybeword: /* empty */
  93.                      { printf ("empty maybeword\n"); }
  94.              | word
  95.                      { printf ("single word %s\n", $1); }
  96.              ;
  97. The error is an ambiguity: there is more than one way to parse a single
  98. `word' into a `sequence'.  It could be reduced to a `maybeword' and
  99. then into a `sequence' via the second rule.  Alternatively,
  100. nothing-at-all could be reduced into a `sequence' via the first rule,
  101. and this could be combined with the `word' using the third rule for
  102. `sequence'.
  103.    There is also more than one way to reduce nothing-at-all into a
  104. `sequence'.  This can be done directly via the first rule, or
  105. indirectly via `maybeword' and then the second rule.
  106.    You might think that this is a distinction without a difference,
  107. because it does not change whether any particular input is valid or
  108. not.  But it does affect which actions are run.  One parsing order runs
  109. the second rule's action; the other runs the first rule's action and
  110. the third rule's action.  In this example, the output of the program
  111. changes.
  112.    Bison resolves a reduce/reduce conflict by choosing to use the rule
  113. that appears first in the grammar, but it is very risky to rely on
  114. this.  Every reduce/reduce conflict must be studied and usually
  115. eliminated.  Here is the proper way to define `sequence':
  116.      sequence: /* empty */
  117.                      { printf ("empty sequence\n"); }
  118.              | sequence word
  119.                      { printf ("added word %s\n", $2); }
  120.              ;
  121.    Here is another common error that yields a reduce/reduce conflict:
  122.      sequence: /* empty */
  123.              | sequence words
  124.              | sequence redirects
  125.              ;
  126.      
  127.      words:    /* empty */
  128.              | words word
  129.              ;
  130.      
  131.      redirects:/* empty */
  132.              | redirects redirect
  133.              ;
  134. The intention here is to define a sequence which can contain either
  135. `word' or `redirect' groupings.  The individual definitions of
  136. `sequence', `words' and `redirects' are error-free, but the three
  137. together make a subtle ambiguity: even an empty input can be parsed in
  138. infinitely many ways!
  139.    Consider: nothing-at-all could be a `words'.  Or it could be two
  140. `words' in a row, or three, or any number.  It could equally well be a
  141. `redirects', or two, or any number.  Or it could be a `words' followed
  142. by three `redirects' and another `words'.  And so on.
  143.    Here are two ways to correct these rules.  First, to make it a
  144. single level of sequence:
  145.      sequence: /* empty */
  146.              | sequence word
  147.              | sequence redirect
  148.              ;
  149.    Second, to prevent either a `words' or a `redirects' from being
  150. empty:
  151.      sequence: /* empty */
  152.              | sequence words
  153.              | sequence redirects
  154.              ;
  155.      
  156.      words:    word
  157.              | words word
  158.              ;
  159.      
  160.      redirects:redirect
  161.              | redirects redirect
  162.              ;
  163. File: bison.info,  Node: Mystery Conflicts,  Next: Stack Overflow,  Prev: Reduce/Reduce,  Up: Algorithm
  164. Mysterious Reduce/Reduce Conflicts
  165. ==================================
  166.    Sometimes reduce/reduce conflicts can occur that don't look
  167. warranted.  Here is an example:
  168.      %token ID
  169.      
  170.      %%
  171.      def:    param_spec return_spec ','
  172.              ;
  173.      param_spec:
  174.                   type
  175.              |    name_list ':' type
  176.              ;
  177.      return_spec:
  178.                   type
  179.              |    name ':' type
  180.              ;
  181.      type:        ID
  182.              ;
  183.      name:        ID
  184.              ;
  185.      name_list:
  186.                   name
  187.              |    name ',' name_list
  188.              ;
  189.    It would seem that this grammar can be parsed with only a single
  190. token of look-ahead: when a `param_spec' is being read, an `ID' is a
  191. `name' if a comma or colon follows, or a `type' if another `ID'
  192. follows.  In other words, this grammar is LR(1).
  193.    However, Bison, like most parser generators, cannot actually handle
  194. all LR(1) grammars.  In this grammar, two contexts, that after an `ID'
  195. at the beginning of a `param_spec' and likewise at the beginning of a
  196. `return_spec', are similar enough that Bison assumes they are the same.
  197. They appear similar because the same set of rules would be active--the
  198. rule for reducing to a `name' and that for reducing to a `type'.  Bison
  199. is unable to determine at that stage of processing that the rules would
  200. require different look-ahead tokens in the two contexts, so it makes a
  201. single parser state for them both.  Combining the two contexts causes a
  202. conflict later.  In parser terminology, this occurrence means that the
  203. grammar is not LALR(1).
  204.    In general, it is better to fix deficiencies than to document them.
  205. But this particular deficiency is intrinsically hard to fix; parser
  206. generators that can handle LR(1) grammars are hard to write and tend to
  207. produce parsers that are very large.  In practice, Bison is more useful
  208. as it is now.
  209.    When the problem arises, you can often fix it by identifying the two
  210. parser states that are being confused, and adding something to make them
  211. look distinct.  In the above example, adding one rule to `return_spec'
  212. as follows makes the problem go away:
  213.      %token BOGUS
  214.      ...
  215.      %%
  216.      ...
  217.      return_spec:
  218.                   type
  219.              |    name ':' type
  220.              /* This rule is never used.  */
  221.              |    ID BOGUS
  222.              ;
  223.    This corrects the problem because it introduces the possibility of an
  224. additional active rule in the context after the `ID' at the beginning of
  225. `return_spec'.  This rule is not active in the corresponding context in
  226. a `param_spec', so the two contexts receive distinct parser states.  As
  227. long as the token `BOGUS' is never generated by `yylex', the added rule
  228. cannot alter the way actual input is parsed.
  229.    In this particular example, there is another way to solve the
  230. problem: rewrite the rule for `return_spec' to use `ID' directly
  231. instead of via `name'.  This also causes the two confusing contexts to
  232. have different sets of active rules, because the one for `return_spec'
  233. activates the altered rule for `return_spec' rather than the one for
  234. `name'.
  235.      param_spec:
  236.                   type
  237.              |    name_list ':' type
  238.              ;
  239.      return_spec:
  240.                   type
  241.              |    ID ':' type
  242.              ;
  243. File: bison.info,  Node: Stack Overflow,  Prev: Mystery Conflicts,  Up: Algorithm
  244. Stack Overflow, and How to Avoid It
  245. ===================================
  246.    The Bison parser stack can overflow if too many tokens are shifted
  247. and not reduced.  When this happens, the parser function `yyparse'
  248. returns a nonzero value, pausing only to call `yyerror' to report the
  249. overflow.
  250.    By defining the macro `YYMAXDEPTH', you can control how deep the
  251. parser stack can become before a stack overflow occurs.  Define the
  252. macro with a value that is an integer.  This value is the maximum number
  253. of tokens that can be shifted (and not reduced) before overflow.  It
  254. must be a constant expression whose value is known at compile time.
  255.    The stack space allowed is not necessarily allocated.  If you
  256. specify a large value for `YYMAXDEPTH', the parser actually allocates a
  257. small stack at first, and then makes it bigger by stages as needed.
  258. This increasing allocation happens automatically and silently.
  259. Therefore, you do not need to make `YYMAXDEPTH' painfully small merely
  260. to save space for ordinary inputs that do not need much stack.
  261.    The default value of `YYMAXDEPTH', if you do not define it, is 10000.
  262.    You can control how much stack is allocated initially by defining the
  263. macro `YYINITDEPTH'.  This value too must be a compile-time constant
  264. integer.  The default is 200.
  265. File: bison.info,  Node: Error Recovery,  Next: Context Dependency,  Prev: Algorithm,  Up: Top
  266. Error Recovery
  267. **************
  268.    It is not usually acceptable to have a program terminate on a parse
  269. error.  For example, a compiler should recover sufficiently to parse the
  270. rest of the input file and check it for errors; a calculator should
  271. accept another expression.
  272.    In a simple interactive command parser where each input is one line,
  273. it may be sufficient to allow `yyparse' to return 1 on error and have
  274. the caller ignore the rest of the input line when that happens (and
  275. then call `yyparse' again).  But this is inadequate for a compiler,
  276. because it forgets all the syntactic context leading up to the error.
  277. A syntax error deep within a function in the compiler input should not
  278. cause the compiler to treat the following line like the beginning of a
  279. source file.
  280.    You can define how to recover from a syntax error by writing rules to
  281. recognize the special token `error'.  This is a terminal symbol that is
  282. always defined (you need not declare it) and reserved for error
  283. handling.  The Bison parser generates an `error' token whenever a
  284. syntax error happens; if you have provided a rule to recognize this
  285. token in the current context, the parse can continue.
  286.    For example:
  287.      stmnts:  /* empty string */
  288.              | stmnts '\n'
  289.              | stmnts exp '\n'
  290.              | stmnts error '\n'
  291.    The fourth rule in this example says that an error followed by a
  292. newline makes a valid addition to any `stmnts'.
  293.    What happens if a syntax error occurs in the middle of an `exp'?  The
  294. error recovery rule, interpreted strictly, applies to the precise
  295. sequence of a `stmnts', an `error' and a newline.  If an error occurs in
  296. the middle of an `exp', there will probably be some additional tokens
  297. and subexpressions on the stack after the last `stmnts', and there will
  298. be tokens to read before the next newline.  So the rule is not
  299. applicable in the ordinary way.
  300.    But Bison can force the situation to fit the rule, by discarding
  301. part of the semantic context and part of the input.  First it discards
  302. states and objects from the stack until it gets back to a state in
  303. which the `error' token is acceptable.  (This means that the
  304. subexpressions already parsed are discarded, back to the last complete
  305. `stmnts'.)  At this point the `error' token can be shifted.  Then, if
  306. the old look-ahead token is not acceptable to be shifted next, the
  307. parser reads tokens and discards them until it finds a token which is
  308. acceptable.  In this example, Bison reads and discards input until the
  309. next newline so that the fourth rule can apply.
  310.    The choice of error rules in the grammar is a choice of strategies
  311. for error recovery.  A simple and useful strategy is simply to skip the
  312. rest of the current input line or current statement if an error is
  313. detected:
  314.      stmnt: error ';'  /* on error, skip until ';' is read */
  315.    It is also useful to recover to the matching close-delimiter of an
  316. opening-delimiter that has already been parsed.  Otherwise the
  317. close-delimiter will probably appear to be unmatched, and generate
  318. another, spurious error message:
  319.      primary:  '(' expr ')'
  320.              | '(' error ')'
  321.              ...
  322.              ;
  323.    Error recovery strategies are necessarily guesses.  When they guess
  324. wrong, one syntax error often leads to another.  In the above example,
  325. the error recovery rule guesses that an error is due to bad input
  326. within one `stmnt'.  Suppose that instead a spurious semicolon is
  327. inserted in the middle of a valid `stmnt'.  After the error recovery
  328. rule recovers from the first error, another syntax error will be found
  329. straightaway, since the text following the spurious semicolon is also
  330. an invalid `stmnt'.
  331.    To prevent an outpouring of error messages, the parser will output
  332. no error message for another syntax error that happens shortly after
  333. the first; only after three consecutive input tokens have been
  334. successfully shifted will error messages resume.
  335.    Note that rules which accept the `error' token may have actions, just
  336. as any other rules can.
  337.    You can make error messages resume immediately by using the macro
  338. `yyerrok' in an action.  If you do this in the error rule's action, no
  339. error messages will be suppressed.  This macro requires no arguments;
  340. `yyerrok;' is a valid C statement.
  341.    The previous look-ahead token is reanalyzed immediately after an
  342. error.  If this is unacceptable, then the macro `yyclearin' may be used
  343. to clear this token.  Write the statement `yyclearin;' in the error
  344. rule's action.
  345.    For example, suppose that on a parse error, an error handling
  346. routine is called that advances the input stream to some point where
  347. parsing should once again commence.  The next symbol returned by the
  348. lexical scanner is probably correct.  The previous look-ahead token
  349. ought to be discarded with `yyclearin;'.
  350.    The macro `YYRECOVERING' stands for an expression that has the value
  351. 1 when the parser is recovering from a syntax error, and 0 the rest of
  352. the time.  A value of 1 indicates that error messages are currently
  353. suppressed for new syntax errors.
  354. File: bison.info,  Node: Context Dependency,  Next: Debugging,  Prev: Error Recovery,  Up: Top
  355. Handling Context Dependencies
  356. *****************************
  357.    The Bison paradigm is to parse tokens first, then group them into
  358. larger syntactic units.  In many languages, the meaning of a token is
  359. affected by its context.  Although this violates the Bison paradigm,
  360. certain techniques (known as "kludges") may enable you to write Bison
  361. parsers for such languages.
  362. * Menu:
  363. * Semantic Tokens::   Token parsing can depend on the semantic context.
  364. * Lexical Tie-ins::   Token parsing can depend on the syntactic context.
  365. * Tie-in Recovery::   Lexical tie-ins have implications for how
  366.                         error recovery rules must be written.
  367.    (Actually, "kludge" means any technique that gets its job done but is
  368. neither clean nor robust.)
  369. File: bison.info,  Node: Semantic Tokens,  Next: Lexical Tie-ins,  Up: Context Dependency
  370. Semantic Info in Token Types
  371. ============================
  372.    The C language has a context dependency: the way an identifier is
  373. used depends on what its current meaning is.  For example, consider
  374. this:
  375.      foo (x);
  376.    This looks like a function call statement, but if `foo' is a typedef
  377. name, then this is actually a declaration of `x'.  How can a Bison
  378. parser for C decide how to parse this input?
  379.    The method used in GNU C is to have two different token types,
  380. `IDENTIFIER' and `TYPENAME'.  When `yylex' finds an identifier, it
  381. looks up the current declaration of the identifier in order to decide
  382. which token type to return: `TYPENAME' if the identifier is declared as
  383. a typedef, `IDENTIFIER' otherwise.
  384.    The grammar rules can then express the context dependency by the
  385. choice of token type to recognize.  `IDENTIFIER' is accepted as an
  386. expression, but `TYPENAME' is not.  `TYPENAME' can start a declaration,
  387. but `IDENTIFIER' cannot.  In contexts where the meaning of the
  388. identifier is *not* significant, such as in declarations that can
  389. shadow a typedef name, either `TYPENAME' or `IDENTIFIER' is
  390. accepted--there is one rule for each of the two token types.
  391.    This technique is simple to use if the decision of which kinds of
  392. identifiers to allow is made at a place close to where the identifier is
  393. parsed.  But in C this is not always so: C allows a declaration to
  394. redeclare a typedef name provided an explicit type has been specified
  395. earlier:
  396.      typedef int foo, bar, lose;
  397.      static foo (bar);        /* redeclare `bar' as static variable */
  398.      static int foo (lose);   /* redeclare `foo' as function */
  399.    Unfortunately, the name being declared is separated from the
  400. declaration construct itself by a complicated syntactic structure--the
  401. "declarator".
  402.    As a result, the part of Bison parser for C needs to be duplicated,
  403. with all the nonterminal names changed: once for parsing a declaration
  404. in which a typedef name can be redefined, and once for parsing a
  405. declaration in which that can't be done.  Here is a part of the
  406. duplication, with actions omitted for brevity:
  407.      initdcl:
  408.                declarator maybeasm '='
  409.                init
  410.              | declarator maybeasm
  411.              ;
  412.      
  413.      notype_initdcl:
  414.                notype_declarator maybeasm '='
  415.                init
  416.              | notype_declarator maybeasm
  417.              ;
  418. Here `initdcl' can redeclare a typedef name, but `notype_initdcl'
  419. cannot.  The distinction between `declarator' and `notype_declarator'
  420. is the same sort of thing.
  421.    There is some similarity between this technique and a lexical tie-in
  422. (described next), in that information which alters the lexical analysis
  423. is changed during parsing by other parts of the program.  The
  424. difference is here the information is global, and is used for other
  425. purposes in the program.  A true lexical tie-in has a special-purpose
  426. flag controlled by the syntactic context.
  427. File: bison.info,  Node: Lexical Tie-ins,  Next: Tie-in Recovery,  Prev: Semantic Tokens,  Up: Context Dependency
  428. Lexical Tie-ins
  429. ===============
  430.    One way to handle context-dependency is the "lexical tie-in": a flag
  431. which is set by Bison actions, whose purpose is to alter the way tokens
  432. are parsed.
  433.    For example, suppose we have a language vaguely like C, but with a
  434. special construct `hex (HEX-EXPR)'.  After the keyword `hex' comes an
  435. expression in parentheses in which all integers are hexadecimal.  In
  436. particular, the token `a1b' must be treated as an integer rather than
  437. as an identifier if it appears in that context.  Here is how you can do
  438.      %{
  439.      int hexflag;
  440.      %}
  441.      %%
  442.      ...
  443.      expr:   IDENTIFIER
  444.              | constant
  445.              | HEX '('
  446.                      { hexflag = 1; }
  447.                expr ')'
  448.                      { hexflag = 0;
  449.                         $$ = $4; }
  450.              | expr '+' expr
  451.                      { $$ = make_sum ($1, $3); }
  452.              ...
  453.              ;
  454.      
  455.      constant:
  456.                INTEGER
  457.              | STRING
  458.              ;
  459. Here we assume that `yylex' looks at the value of `hexflag'; when it is
  460. nonzero, all integers are parsed in hexadecimal, and tokens starting
  461. with letters are parsed as integers if possible.
  462.    The declaration of `hexflag' shown in the C declarations section of
  463. the parser file is needed to make it accessible to the actions (*note
  464. The C Declarations Section: C Declarations.).  You must also write the
  465. code in `yylex' to obey the flag.
  466. File: bison.info,  Node: Tie-in Recovery,  Prev: Lexical Tie-ins,  Up: Context Dependency
  467. Lexical Tie-ins and Error Recovery
  468. ==================================
  469.    Lexical tie-ins make strict demands on any error recovery rules you
  470. have.  *Note Error Recovery::.
  471.    The reason for this is that the purpose of an error recovery rule is
  472. to abort the parsing of one construct and resume in some larger
  473. construct.  For example, in C-like languages, a typical error recovery
  474. rule is to skip tokens until the next semicolon, and then start a new
  475. statement, like this:
  476.      stmt:   expr ';'
  477.              | IF '(' expr ')' stmt { ... }
  478.              ...
  479.              error ';'
  480.                      { hexflag = 0; }
  481.              ;
  482.    If there is a syntax error in the middle of a `hex (EXPR)'
  483. construct, this error rule will apply, and then the action for the
  484. completed `hex (EXPR)' will never run.  So `hexflag' would remain set
  485. for the entire rest of the input, or until the next `hex' keyword,
  486. causing identifiers to be misinterpreted as integers.
  487.    To avoid this problem the error recovery rule itself clears
  488. `hexflag'.
  489.    There may also be an error recovery rule that works within
  490. expressions.  For example, there could be a rule which applies within
  491. parentheses and skips to the close-parenthesis:
  492.      expr:   ...
  493.              | '(' expr ')'
  494.                      { $$ = $2; }
  495.              | '(' error ')'
  496.              ...
  497.    If this rule acts within the `hex' construct, it is not going to
  498. abort that construct (since it applies to an inner level of parentheses
  499. within the construct).  Therefore, it should not clear the flag: the
  500. rest of the `hex' construct should be parsed with the flag still in
  501. effect.
  502.    What if there is an error recovery rule which might abort out of the
  503. `hex' construct or might not, depending on circumstances?  There is no
  504. way you can write the action to determine whether a `hex' construct is
  505. being aborted or not.  So if you are using a lexical tie-in, you had
  506. better make sure your error recovery rules are not of this kind.  Each
  507. rule must be such that you can be sure that it always will, or always
  508. won't, have to clear the flag.
  509. File: bison.info,  Node: Debugging,  Next: Invocation,  Prev: Context Dependency,  Up: Top
  510. Debugging Your Parser
  511. *********************
  512.    If a Bison grammar compiles properly but doesn't do what you want
  513. when it runs, the `yydebug' parser-trace feature can help you figure
  514. out why.
  515.    To enable compilation of trace facilities, you must define the macro
  516. `YYDEBUG' when you compile the parser.  You could use `-DYYDEBUG=1' as
  517. a compiler option or you could put `#define YYDEBUG 1' in the C
  518. declarations section of the grammar file (*note The C Declarations
  519. Section: C Declarations.).  Alternatively, use the `-t' option when you
  520. run Bison (*note Invoking Bison: Invocation.).  We always define
  521. `YYDEBUG' so that debugging is always possible.
  522.    The trace facility uses `stderr', so you must add
  523. `#include <stdio.h>' to the C declarations section unless it is already
  524. there.
  525.    Once you have compiled the program with trace facilities, the way to
  526. request a trace is to store a nonzero value in the variable `yydebug'.
  527. You can do this by making the C code do it (in `main', perhaps), or you
  528. can alter the value with a C debugger.
  529.    Each step taken by the parser when `yydebug' is nonzero produces a
  530. line or two of trace information, written on `stderr'.  The trace
  531. messages tell you these things:
  532.    * Each time the parser calls `yylex', what kind of token was read.
  533.    * Each time a token is shifted, the depth and complete contents of
  534.      the state stack (*note Parser States::.).
  535.    * Each time a rule is reduced, which rule it is, and the complete
  536.      contents of the state stack afterward.
  537.    To make sense of this information, it helps to refer to the listing
  538. file produced by the Bison `-v' option (*note Invoking Bison:
  539. Invocation.).  This file shows the meaning of each state in terms of
  540. positions in various rules, and also what each state will do with each
  541. possible input token.  As you read the successive trace messages, you
  542. can see that the parser is functioning according to its specification
  543. in the listing file.  Eventually you will arrive at the place where
  544. something undesirable happens, and you will see which parts of the
  545. grammar are to blame.
  546.    The parser file is a C program and you can use C debuggers on it,
  547. but it's not easy to interpret what it is doing.  The parser function
  548. is a finite-state machine interpreter, and aside from the actions it
  549. executes the same code over and over.  Only the values of variables
  550. show where in the grammar it is working.
  551.    The debugging information normally gives the token type of each token
  552. read, but not its semantic value.  You can optionally define a macro
  553. named `YYPRINT' to provide a way to print the value.  If you define
  554. `YYPRINT', it should take three arguments.  The parser will pass a
  555. standard I/O stream, the numeric code for the token type, and the token
  556. value (from `yylval').
  557.    Here is an example of `YYPRINT' suitable for the multi-function
  558. calculator (*note Declarations for `mfcalc': Mfcalc Decl.):
  559.      #define YYPRINT(file, type, value)   yyprint (file, type, value)
  560.      
  561.      static void
  562.      yyprint (file, type, value)
  563.           FILE *file;
  564.           int type;
  565.           YYSTYPE value;
  566.      {
  567.        if (type == VAR)
  568.          fprintf (file, " %s", value.tptr->name);
  569.        else if (type == NUM)
  570.          fprintf (file, " %d", value.val);
  571.      }
  572. File: bison.info,  Node: Invocation,  Next: Table of Symbols,  Prev: Debugging,  Up: Top
  573. Invoking Bison
  574. **************
  575.    The usual way to invoke Bison is as follows:
  576.      bison INFILE
  577.    Here INFILE is the grammar file name, which usually ends in `.y'.
  578. The parser file's name is made by replacing the `.y' with `.tab.c'.
  579. Thus, the `bison foo.y' filename yields `foo.tab.c', and the `bison
  580. hack/foo.y' filename yields `hack/foo.tab.c'.
  581. * Menu:
  582. * Bison Options::     All the options described in detail,
  583.             in alphabetical order by short options.
  584. * Option Cross Key::  Alphabetical list of long options.
  585. * VMS Invocation::    Bison command syntax on VMS.
  586. File: bison.info,  Node: Bison Options,  Next: Option Cross Key,  Up: Invocation
  587. Bison Options
  588. =============
  589.    Bison supports both traditional single-letter options and mnemonic
  590. long option names.  Long option names are indicated with `--' instead of
  591. `-'.  Abbreviations for option names are allowed as long as they are
  592. unique.  When a long option takes an argument, like `--file-prefix',
  593. connect the option name and the argument with `='.
  594.    Here is a list of options that can be used with Bison, alphabetized
  595. by short option.  It is followed by a cross key alphabetized by long
  596. option.
  597. `-b FILE-PREFIX'
  598. `--file-prefix=PREFIX'
  599.      Specify a prefix to use for all Bison output file names.  The
  600.      names are chosen as if the input file were named `PREFIX.c'.
  601. `--defines'
  602.      Write an extra output file containing macro definitions for the
  603.      token type names defined in the grammar and the semantic value type
  604.      `YYSTYPE', as well as a few `extern' variable declarations.
  605.      If the parser output file is named `NAME.c' then this file is
  606.      named `NAME.h'.
  607.      This output file is essential if you wish to put the definition of
  608.      `yylex' in a separate source file, because `yylex' needs to be
  609.      able to refer to token type codes and the variable `yylval'.
  610.      *Note Semantic Values of Tokens: Token Values.
  611. `--no-lines'
  612.      Don't put any `#line' preprocessor commands in the parser file.
  613.      Ordinarily Bison puts them in the parser file so that the C
  614.      compiler and debuggers will associate errors with your source
  615.      file, the grammar file.  This option causes them to associate
  616.      errors with the parser file, treating it as an independent source
  617.      file in its own right.
  618. `--no-parser'
  619.      Do not include any C code in the parser file; generate tables
  620.      only.  The parser file contains just `#define' directives and
  621.      static variable declarations.
  622.      This option also tells Bison to write the C code for the grammar
  623.      actions into a file named `FILENAME.act', in the form of a
  624.      brace-surrounded body fit for a `switch' statement.
  625. `-o OUTFILE'
  626. `--output-file=OUTFILE'
  627.      Specify the name OUTFILE for the parser file.
  628.      The other output files' names are constructed from OUTFILE as
  629.      described under the `-v' and `-d' options.
  630. `-p PREFIX'
  631. `--name-prefix=PREFIX'
  632.      Rename the external symbols used in the parser so that they start
  633.      with PREFIX instead of `yy'.  The precise list of symbols renamed
  634.      is `yyparse', `yylex', `yyerror', `yynerrs', `yylval', `yychar'
  635.      and `yydebug'.
  636.      For example, if you use `-p c', the names become `cparse', `clex',
  637.      and so on.
  638.      *Note Multiple Parsers in the Same Program: Multiple Parsers.
  639. `--raw'
  640.      Pretend that `%raw' was specified.  *Note Decl Summary::.
  641. `--debug'
  642.      Output a definition of the macro `YYDEBUG' into the parser file,
  643.      so that the debugging facilities are compiled.  *Note Debugging
  644.      Your Parser: Debugging.
  645. `--verbose'
  646.      Write an extra output file containing verbose descriptions of the
  647.      parser states and what is done for each type of look-ahead token in
  648.      that state.
  649.      This file also describes all the conflicts, both those resolved by
  650.      operator precedence and the unresolved ones.
  651.      The file's name is made by removing `.tab.c' or `.c' from the
  652.      parser output file name, and adding `.output' instead.
  653.      Therefore, if the input file is `foo.y', then the parser file is
  654.      called `foo.tab.c' by default.  As a consequence, the verbose
  655.      output file is called `foo.output'.
  656. `--version'
  657.      Print the version number of Bison and exit.
  658. `--help'
  659.      Print a summary of the command-line options to Bison and exit.
  660. `--yacc'
  661. `--fixed-output-files'
  662.      Equivalent to `-o y.tab.c'; the parser output file is called
  663.      `y.tab.c', and the other outputs are called `y.output' and
  664.      `y.tab.h'.  The purpose of this option is to imitate Yacc's output
  665.      file name conventions.  Thus, the following shell script can
  666.      substitute for Yacc:
  667.           bison -y $*
  668. File: bison.info,  Node: Option Cross Key,  Next: VMS Invocation,  Prev: Bison Options,  Up: Invocation
  669. Option Cross Key
  670. ================
  671.    Here is a list of options, alphabetized by long option, to help you
  672. find the corresponding short option.
  673.      --debug                               -t
  674.      --defines                             -d
  675.      --file-prefix=PREFIX                  -b FILE-PREFIX
  676.      --fixed-output-files --yacc           -y
  677.      --help                                -h
  678.      --name-prefix=PREFIX                  -p NAME-PREFIX
  679.      --no-lines                            -l
  680.      --no-parser                           -n
  681.      --output-file=OUTFILE                 -o OUTFILE
  682.      --raw                                 -r
  683.      --token-table                         -k
  684.      --verbose                             -v
  685.      --version                             -V
  686. File: bison.info,  Node: VMS Invocation,  Prev: Option Cross Key,  Up: Invocation
  687. Invoking Bison under VMS
  688. ========================
  689.    The command line syntax for Bison on VMS is a variant of the usual
  690. Bison command syntax--adapted to fit VMS conventions.
  691.    To find the VMS equivalent for any Bison option, start with the long
  692. option, and substitute a `/' for the leading `--', and substitute a `_'
  693. for each `-' in the name of the long option.  For example, the
  694. following invocation under VMS:
  695.      bison /debug/name_prefix=bar foo.y
  696. is equivalent to the following command under POSIX.
  697.      bison --debug --name-prefix=bar foo.y
  698.    The VMS file system does not permit filenames such as `foo.tab.c'.
  699. In the above example, the output file would instead be named
  700. `foo_tab.c'.
  701. File: bison.info,  Node: Table of Symbols,  Next: Glossary,  Prev: Invocation,  Up: Top
  702. Bison Symbols
  703. *************
  704. `error'
  705.      A token name reserved for error recovery.  This token may be used
  706.      in grammar rules so as to allow the Bison parser to recognize an
  707.      error in the grammar without halting the process.  In effect, a
  708.      sentence containing an error may be recognized as valid.  On a
  709.      parse error, the token `error' becomes the current look-ahead
  710.      token.  Actions corresponding to `error' are then executed, and
  711.      the look-ahead token is reset to the token that originally caused
  712.      the violation.  *Note Error Recovery::.
  713. `YYABORT'
  714.      Macro to pretend that an unrecoverable syntax error has occurred,
  715.      by making `yyparse' return 1 immediately.  The error reporting
  716.      function `yyerror' is not called.  *Note The Parser Function
  717.      `yyparse': Parser Function.
  718. `YYACCEPT'
  719.      Macro to pretend that a complete utterance of the language has been
  720.      read, by making `yyparse' return 0 immediately.  *Note The Parser
  721.      Function `yyparse': Parser Function.
  722. `YYBACKUP'
  723.      Macro to discard a value from the parser stack and fake a
  724.      look-ahead token.  *Note Special Features for Use in Actions:
  725.      Action Features.
  726. `YYERROR'
  727.      Macro to pretend that a syntax error has just been detected: call
  728.      `yyerror' and then perform normal error recovery if possible
  729.      (*note Error Recovery::.), or (if recovery is impossible) make
  730.      `yyparse' return 1.  *Note Error Recovery::.
  731. `YYERROR_VERBOSE'
  732.      Macro that you define with `#define' in the Bison declarations
  733.      section to request verbose, specific error message strings when
  734.      `yyerror' is called.
  735. `YYINITDEPTH'
  736.      Macro for specifying the initial size of the parser stack.  *Note
  737.      Stack Overflow::.
  738. `YYLEX_PARAM'
  739.      Macro for specifying an extra argument (or list of extra
  740.      arguments) for `yyparse' to pass to `yylex'.  *Note Calling
  741.      Conventions for Pure Parsers: Pure Calling.
  742. `YYLTYPE'
  743.      Macro for the data type of `yylloc'; a structure with four
  744.      members.  *Note Textual Positions of Tokens: Token Positions.
  745. `yyltype'
  746.      Default value for YYLTYPE.
  747. `YYMAXDEPTH'
  748.      Macro for specifying the maximum size of the parser stack.  *Note
  749.      Stack Overflow::.
  750. `YYPARSE_PARAM'
  751.      Macro for specifying the name of a parameter that `yyparse' should
  752.      accept.  *Note Calling Conventions for Pure Parsers: Pure Calling.
  753. `YYRECOVERING'
  754.      Macro whose value indicates whether the parser is recovering from a
  755.      syntax error.  *Note Special Features for Use in Actions: Action
  756.      Features.
  757. `YYSTYPE'
  758.      Macro for the data type of semantic values; `int' by default.
  759.      *Note Data Types of Semantic Values: Value Type.
  760. `yychar'
  761.      External integer variable that contains the integer value of the
  762.      current look-ahead token.  (In a pure parser, it is a local
  763.      variable within `yyparse'.)  Error-recovery rule actions may
  764.      examine this variable.  *Note Special Features for Use in Actions:
  765.      Action Features.
  766. `yyclearin'
  767.      Macro used in error-recovery rule actions.  It clears the previous
  768.      look-ahead token.  *Note Error Recovery::.
  769. `yydebug'
  770.      External integer variable set to zero by default.  If `yydebug' is
  771.      given a nonzero value, the parser will output information on input
  772.      symbols and parser action.  *Note Debugging Your Parser: Debugging.
  773. `yyerrok'
  774.      Macro to cause parser to recover immediately to its normal mode
  775.      after a parse error.  *Note Error Recovery::.
  776. `yyerror'
  777.      User-supplied function to be called by `yyparse' on error.  The
  778.      function receives one argument, a pointer to a character string
  779.      containing an error message.  *Note The Error Reporting Function
  780.      `yyerror': Error Reporting.
  781. `yylex'
  782.      User-supplied lexical analyzer function, called with no arguments
  783.      to get the next token.  *Note The Lexical Analyzer Function
  784.      `yylex': Lexical.
  785. `yylval'
  786.      External variable in which `yylex' should place the semantic value
  787.      associated with a token.  (In a pure parser, it is a local
  788.      variable within `yyparse', and its address is passed to `yylex'.)
  789.      *Note Semantic Values of Tokens: Token Values.
  790. `yylloc'
  791.      External variable in which `yylex' should place the line and
  792.      column numbers associated with a token.  (In a pure parser, it is a
  793.      local variable within `yyparse', and its address is passed to
  794.      `yylex'.)  You can ignore this variable if you don't use the `@'
  795.      feature in the grammar actions.  *Note Textual Positions of
  796.      Tokens: Token Positions.
  797. `yynerrs'
  798.      Global variable which Bison increments each time there is a parse
  799.      error.  (In a pure parser, it is a local variable within
  800.      `yyparse'.)  *Note The Error Reporting Function `yyerror': Error
  801.      Reporting.
  802. `yyparse'
  803.      The parser function produced by Bison; call this function to start
  804.      parsing.  *Note The Parser Function `yyparse': Parser Function.
  805. `%left'
  806.      Bison declaration to assign left associativity to token(s).  *Note
  807.      Operator Precedence: Precedence Decl.
  808. `%no_lines'
  809.      Bison declaration to avoid generating `#line' directives in the
  810.      parser file.  *Note Decl Summary::.
  811. `%nonassoc'
  812.      Bison declaration to assign nonassociativity to token(s).  *Note
  813.      Operator Precedence: Precedence Decl.
  814. `%prec'
  815.      Bison declaration to assign a precedence to a specific rule.
  816.      *Note Context-Dependent Precedence: Contextual Precedence.
  817. `%pure_parser'
  818.      Bison declaration to request a pure (reentrant) parser.  *Note A
  819.      Pure (Reentrant) Parser: Pure Decl.
  820. `%raw'
  821.      Bison declaration to use Bison internal token code numbers in token
  822.      tables instead of the usual Yacc-compatible token code numbers.
  823.      *Note Decl Summary::.
  824. `%right'
  825.      Bison declaration to assign right associativity to token(s).
  826.      *Note Operator Precedence: Precedence Decl.
  827. `%start'
  828.      Bison declaration to specify the start symbol.  *Note The
  829.      Start-Symbol: Start Decl.
  830. `%token'
  831.      Bison declaration to declare token(s) without specifying
  832.      precedence.  *Note Token Type Names: Token Decl.
  833. `%token_table'
  834.      Bison declaration to include a token name table in the parser file.
  835.      *Note Decl Summary::.
  836. `%type'
  837.      Bison declaration to declare nonterminals.  *Note Nonterminal
  838.      Symbols: Type Decl.
  839. `%union'
  840.      Bison declaration to specify several possible data types for
  841.      semantic values.  *Note The Collection of Value Types: Union Decl.
  842.    These are the punctuation and delimiters used in Bison input:
  843.      Delimiter used to separate the grammar rule section from the Bison
  844.      declarations section or the additional C code section.  *Note The
  845.      Overall Layout of a Bison Grammar: Grammar Layout.
  846. `%{ %}'
  847.      All code listed between `%{' and `%}' is copied directly to the
  848.      output file uninterpreted.  Such code forms the "C declarations"
  849.      section of the input file.  *Note Outline of a Bison Grammar:
  850.      Grammar Outline.
  851. `/*...*/'
  852.      Comment delimiters, as in C.
  853.      Separates a rule's result from its components.  *Note Syntax of
  854.      Grammar Rules: Rules.
  855.      Terminates a rule.  *Note Syntax of Grammar Rules: Rules.
  856.      Separates alternate rules for the same result nonterminal.  *Note
  857.      Syntax of Grammar Rules: Rules.
  858. File: bison.info,  Node: Glossary,  Next: Index,  Prev: Table of Symbols,  Up: Top
  859. Glossary
  860. ********
  861. Backus-Naur Form (BNF)
  862.      Formal method of specifying context-free grammars.  BNF was first
  863.      used in the `ALGOL-60' report, 1963.  *Note Languages and
  864.      Context-Free Grammars: Language and Grammar.
  865. Context-free grammars
  866.      Grammars specified as rules that can be applied regardless of
  867.      context.  Thus, if there is a rule which says that an integer can
  868.      be used as an expression, integers are allowed *anywhere* an
  869.      expression is permitted.  *Note Languages and Context-Free
  870.      Grammars: Language and Grammar.
  871. Dynamic allocation
  872.      Allocation of memory that occurs during execution, rather than at
  873.      compile time or on entry to a function.
  874. Empty string
  875.      Analogous to the empty set in set theory, the empty string is a
  876.      character string of length zero.
  877. Finite-state stack machine
  878.      A "machine" that has discrete states in which it is said to exist
  879.      at each instant in time.  As input to the machine is processed, the
  880.      machine moves from state to state as specified by the logic of the
  881.      machine.  In the case of the parser, the input is the language
  882.      being parsed, and the states correspond to various stages in the
  883.      grammar rules.  *Note The Bison Parser Algorithm: Algorithm.
  884. Grouping
  885.      A language construct that is (in general) grammatically divisible;
  886.      for example, `expression' or `declaration' in C.  *Note Languages
  887.      and Context-Free Grammars: Language and Grammar.
  888. Infix operator
  889.      An arithmetic operator that is placed between the operands on
  890.      which it performs some operation.
  891. Input stream
  892.      A continuous flow of data between devices or programs.
  893. Language construct
  894.      One of the typical usage schemas of the language.  For example,
  895.      one of the constructs of the C language is the `if' statement.
  896.      *Note Languages and Context-Free Grammars: Language and Grammar.
  897. Left associativity
  898.      Operators having left associativity are analyzed from left to
  899.      right: `a+b+c' first computes `a+b' and then combines with `c'.
  900.      *Note Operator Precedence: Precedence.
  901. Left recursion
  902.      A rule whose result symbol is also its first component symbol; for
  903.      example, `expseq1 : expseq1 ',' exp;'.  *Note Recursive Rules:
  904.      Recursion.
  905. Left-to-right parsing
  906.      Parsing a sentence of a language by analyzing it token by token
  907.      from left to right.  *Note The Bison Parser Algorithm: Algorithm.
  908. Lexical analyzer (scanner)
  909.      A function that reads an input stream and returns tokens one by
  910.      one.  *Note The Lexical Analyzer Function `yylex': Lexical.
  911. Lexical tie-in
  912.      A flag, set by actions in the grammar rules, which alters the way
  913.      tokens are parsed.  *Note Lexical Tie-ins::.
  914. Literal string token
  915.      A token which constists of two or more fixed characters.  *Note
  916.      Symbols::.
  917. Look-ahead token
  918.      A token already read but not yet shifted.  *Note Look-Ahead
  919.      Tokens: Look-Ahead.
  920. LALR(1)
  921.      The class of context-free grammars that Bison (like most other
  922.      parser generators) can handle; a subset of LR(1).  *Note
  923.      Mysterious Reduce/Reduce Conflicts: Mystery Conflicts.
  924. LR(1)
  925.      The class of context-free grammars in which at most one token of
  926.      look-ahead is needed to disambiguate the parsing of any piece of
  927.      input.
  928. Nonterminal symbol
  929.      A grammar symbol standing for a grammatical construct that can be
  930.      expressed through rules in terms of smaller constructs; in other
  931.      words, a construct that is not a token.  *Note Symbols::.
  932. Parse error
  933.      An error encountered during parsing of an input stream due to
  934.      invalid syntax.  *Note Error Recovery::.
  935. Parser
  936.      A function that recognizes valid sentences of a language by
  937.      analyzing the syntax structure of a set of tokens passed to it
  938.      from a lexical analyzer.
  939. Postfix operator
  940.      An arithmetic operator that is placed after the operands upon
  941.      which it performs some operation.
  942. Reduction
  943.      Replacing a string of nonterminals and/or terminals with a single
  944.      nonterminal, according to a grammar rule.  *Note The Bison Parser
  945.      Algorithm: Algorithm.
  946. Reentrant
  947.      A reentrant subprogram is a subprogram which can be in invoked any
  948.      number of times in parallel, without interference between the
  949.      various invocations.  *Note A Pure (Reentrant) Parser: Pure Decl.
  950. Reverse polish notation
  951.      A language in which all operators are postfix operators.
  952. Right recursion
  953.      A rule whose result symbol is also its last component symbol; for
  954.      example, `expseq1: exp ',' expseq1;'.  *Note Recursive Rules:
  955.      Recursion.
  956. Semantics
  957.      In computer languages, the semantics are specified by the actions
  958.      taken for each instance of the language, i.e., the meaning of each
  959.      statement.  *Note Defining Language Semantics: Semantics.
  960. Shift
  961.      A parser is said to shift when it makes the choice of analyzing
  962.      further input from the stream rather than reducing immediately some
  963.      already-recognized rule.  *Note The Bison Parser Algorithm:
  964.      Algorithm.
  965. Single-character literal
  966.      A single character that is recognized and interpreted as is.
  967.      *Note From Formal Rules to Bison Input: Grammar in Bison.
  968. Start symbol
  969.      The nonterminal symbol that stands for a complete valid utterance
  970.      in the language being parsed.  The start symbol is usually listed
  971.      as the first nonterminal symbol in a language specification.
  972.      *Note The Start-Symbol: Start Decl.
  973. Symbol table
  974.      A data structure where symbol names and associated data are stored
  975.      during parsing to allow for recognition and use of existing
  976.      information in repeated uses of a symbol.  *Note Multi-function
  977.      Calc::.
  978. Token
  979.      A basic, grammatically indivisible unit of a language.  The symbol
  980.      that describes a token in the grammar is a terminal symbol.  The
  981.      input of the Bison parser is a stream of tokens which comes from
  982.      the lexical analyzer.  *Note Symbols::.
  983. Terminal symbol
  984.      A grammar symbol that has no rules in the grammar and therefore is
  985.      grammatically indivisible.  The piece of text it represents is a
  986.      token.  *Note Languages and Context-Free Grammars: Language and
  987.      Grammar.
  988.