Sophie

Sophie

distrib > Fedora > 17 > i386 > media > updates > by-pkgid > 675c8c8167236dfcf8d66da674f931e8 > files > 1166

erlang-doc-R15B-03.3.fc17.noarch.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns:fn="http://www.w3.org/2005/02/xpath-functions">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../../doc/otp_doc.css" type="text/css">
<title>Erlang -- yecc</title>
</head>
<body bgcolor="white" text="#000000" link="#0000ff" vlink="#ff00ff" alink="#ff0000"><div id="container">
<script id="js" type="text/javascript" language="JavaScript" src="../../../../doc/js/flipmenu/flipmenu.js"></script><script id="js2" type="text/javascript" src="../../../../doc/js/erlresolvelinks.js"></script><script language="JavaScript" type="text/javascript">
            <!--
              function getWinHeight() {
                var myHeight = 0;
                if( typeof( window.innerHeight ) == 'number' ) {
                  //Non-IE
                  myHeight = window.innerHeight;
                } else if( document.documentElement && ( document.documentElement.clientWidth ||
                                                         document.documentElement.clientHeight ) ) {
                  //IE 6+ in 'standards compliant mode'
                  myHeight = document.documentElement.clientHeight;
                } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                  //IE 4 compatible
                  myHeight = document.body.clientHeight;
                }
                return myHeight;
              }

              function setscrollpos() {
                var objf=document.getElementById('loadscrollpos');
                 document.getElementById("leftnav").scrollTop = objf.offsetTop - getWinHeight()/2;
              }

              function addEvent(obj, evType, fn){
                if (obj.addEventListener){
                obj.addEventListener(evType, fn, true);
                return true;
              } else if (obj.attachEvent){
                var r = obj.attachEvent("on"+evType, fn);
                return r;
              } else {
                return false;
              }
             }

             addEvent(window, 'load', setscrollpos);

             //--></script><div id="leftnav"><div class="innertube">
<img alt="Erlang logo" src="../../../../doc/erlang-logo.png"><br><small><a href="index.html">Reference Manual</a><br><a href="release_notes.html">Release Notes</a><br><a href="../pdf/parsetools-2.0.7.pdf">PDF</a><br><a href="../../../../doc/index.html">Top</a></small><p><strong>Parse Tools</strong><br><strong>Reference Manual</strong><br><small>Version 2.0.7</small></p>
<br><a href="javascript:openAllFlips()">Expand All</a><br><a href="javascript:closeAllFlips()">Contract All</a><p><small><strong>Table of Contents</strong></small></p>
<ul class="flipMenu">
<li id="loadscrollpos" title="yecc " expanded="true">yecc<ul>
<li><a href="yecc.html">
                  Top of manual page
                </a></li>
<li title="file-1"><a href="yecc.html#file-1">file/1</a></li>
<li title="format_error-1"><a href="yecc.html#format_error-1">format_error/1</a></li>
</ul>
</li>
<li id="no" title="leex " expanded="false">leex<ul>
<li><a href="leex.html">
                  Top of manual page
                </a></li>
<li title="file-1"><a href="leex.html#file-1">file/1</a></li>
<li title="file-2"><a href="leex.html#file-2">file/2</a></li>
<li title="format_error-1"><a href="leex.html#format_error-1">format_error/1</a></li>
<li title="string-1"><a href="leex.html#string-1">string/1</a></li>
<li title="string-2"><a href="leex.html#string-2">string/2</a></li>
<li title="token-2"><a href="leex.html#token-2">token/2</a></li>
<li title="token-3"><a href="leex.html#token-3">token/3</a></li>
<li title="tokens-2"><a href="leex.html#tokens-2">tokens/2</a></li>
<li title="tokens-3"><a href="leex.html#tokens-3">tokens/3</a></li>
</ul>
</li>
</ul>
</div></div>
<div id="content">
<div class="innertube">
<!-- refpage --><center><h1>yecc</h1></center>
  
  <h3>MODULE</h3>
<div class="REFBODY">yecc</div>
  <h3>MODULE SUMMARY</h3>
<div class="REFBODY">LALR-1 Parser Generator</div>
  <h3>DESCRIPTION</h3>
<div class="REFBODY"><p>
    <p>An LALR-1 parser generator for Erlang, similar to <span class="code">yacc</span>.
      Takes a BNF grammar definition as input, and produces Erlang code
      for a parser. </p>
    <p>To understand this text, you also have to
      look at the <span class="code">yacc</span> documentation in the UNIX(TM) manual. This
      is most probably necessary in order to understand the idea of a
      parser generator, and the principle and problems of LALR parsing
      with finite look-ahead.</p>
  </p></div>
  <h3>EXPORTS</h3>
    <p><a name="file-1"><span class="bold_code">file(Grammarfile [, Options]) -&gt; YeccRet</span></a><br></p>
<div class="REFBODY">
<p>Types:</p>
        <div class="REFTYPES">
<span class="bold_code">Grammarfile = filename()</span><br>
</div>
        <div class="REFTYPES">
<span class="bold_code">Options = Option | [Option]</span><br>
</div>
        <div class="REFTYPES">
<span class="bold_code">Option = - see below -</span><br>
</div>
        <div class="REFTYPES">
<span class="bold_code">YeccRet = {ok, Parserfile}  | {ok, Parserfile, Warnings}  | error  | {error, Warnings, Errors}</span><br>
</div>
        <div class="REFTYPES">
<span class="bold_code">Parserfile = filename()</span><br>
</div>
        <div class="REFTYPES">
<span class="bold_code">Warnings = Errors = [{filename(), [ErrorInfo]}]</span><br>
</div>
        <div class="REFTYPES">
<span class="bold_code">ErrorInfo  = {ErrorLine, module(), Reason}</span><br>
</div>
        <div class="REFTYPES">
<span class="bold_code">ErrorLine = integer()</span><br>
</div>
        <div class="REFTYPES">
<span class="bold_code">Reason = - formatable by format_error/1 -</span><br>
</div>
      </div>
<div class="REFBODY"><p>
        <p><span class="code">Grammarfile</span> is the file of declarations and grammar
          rules. Returns <span class="code">ok</span> upon success, or <span class="code">error</span> if
          there are errors. An Erlang file containing the parser is
          created if there are no errors. The options are:
          </p>
        <dl>
          <dt><strong><span class="code">{parserfile, Parserfile}</span>.</strong></dt>
          <dd>
<span class="code">Parserfile</span> is the name of the file that will
           contain the Erlang parser code that is generated. The
           default (<span class="code">""</span>) is to add the extension <span class="code">.erl</span>
           to <span class="code">Grammarfile</span> stripped of the <span class="code">.yrl</span>
           extension.
          </dd>
          <dt><strong><span class="code">{includefile, Includefile}</span>.</strong></dt>
          <dd>Indicates a customized prologue file which the user
           may want to use instead of the default file
          <span class="code">lib/parsetools/include/yeccpre.hrl</span> which is
           otherwise included at the beginning of the resulting
           parser file. <strong>N.B.</strong> The <span class="code">Includefile</span> is
           included 'as is' in the parser file, so it must not have a
           module declaration of its own, and it should not be
           compiled. It must, however, contain the necessary export
           declarations. The default is indicated by <span class="code">""</span>.
          </dd>
          <dt><strong><span class="code">{report_errors, bool()}</span>.</strong></dt>
          <dd>Causes errors to be printed as they occur. Default is
          <span class="code">true</span>.
          </dd>
          <dt><strong><span class="code">{report_warnings, bool()}</span>.</strong></dt>
          <dd>Causes warnings to be printed as they occur. Default is
          <span class="code">true</span>.
          </dd>
          <dt><strong><span class="code">{report, bool()}</span>.</strong></dt>
          <dd>This is a short form for both <span class="code">report_errors</span> and
          <span class="code">report_warnings</span>.
          </dd>
          <dt><strong><span class="code">warnings_as_errors</span></strong></dt>
          <dd>
            <p>Causes warnings to be treated as errors.</p>
          </dd>
          <dt><strong><span class="code">{return_errors, bool()}</span>.</strong></dt>
          <dd>If this flag is set, <span class="code">{error, Errors, Warnings}</span>
           is returned when there are errors. Default is
          <span class="code">false</span>.
          </dd>
          <dt><strong><span class="code">{return_warnings, bool()}</span>.</strong></dt>
          <dd>If this flag is set, an extra field containing
          <span class="code">Warnings</span> is added to the tuple returned upon
           success. Default is <span class="code">false</span>.
          </dd>
          <dt><strong><span class="code">{return, bool()}</span>.</strong></dt>
          <dd>This is a short form for both <span class="code">return_errors</span> and
          <span class="code">return_warnings</span>.
          </dd>
          <dt><strong><span class="code">{verbose, bool()}</span>. </strong></dt>
          <dd>Determines whether the parser generator should give
           full information about resolved and unresolved parse
           action conflicts (<span class="code">true</span>), or only about those
           conflicts that prevent a parser from being generated from
           the input grammar (<span class="code">false</span>, the default).
          </dd>
        </dl>
        <p>Any of the Boolean options can be set to <span class="code">true</span> by 
          stating the name of the option. For example, <span class="code">verbose</span>
          is equivalent to <span class="code">{verbose, true}</span>.
          </p>
        <p>The value of the <span class="code">Parserfile</span> option stripped of the
          <span class="code">.erl</span> extension is used by Yecc as the module name of
          the generated parser file.</p>
        <p>Yecc will add the extension <span class="code">.yrl</span> to the
          <span class="code">Grammarfile</span> name, the extension <span class="code">.hrl</span> to the
          <span class="code">Includefile</span> name, and the extension <span class="code">.erl</span> to
          the <span class="code">Parserfile</span> name, unless the extension is already
          there.</p>
      </p></div>
    <p><a name="format_error-1"><span class="bold_code">format_error(Reason) -&gt; Chars</span></a><br></p>
<div class="REFBODY">
<p>Types:</p>
        <div class="REFTYPES">
<span class="bold_code">Reason = - as returned by yecc:file/1,2 -</span><br>
</div>
        <div class="REFTYPES">
<span class="bold_code">Chars = [char() | Chars]</span><br>
</div>
      </div>
<div class="REFBODY"><p>
        <p>Returns a descriptive string in English of an error tuple
          returned by <span class="code">yecc:file/1,2</span>. This function is mainly
          used by the compiler invoking Yecc.</p>
      </p></div>
  

  <h3><a name="id60823">Pre-Processing</a></h3>
<div class="REFBODY">
    
    <p>A <span class="code">scanner</span> to pre-process the text (program, etc.) to be
      parsed is not provided in the <span class="code">yecc</span> module. The scanner
      serves as a kind of lexicon look-up routine. It is possible to
      write a grammar that uses only character tokens as terminal
      symbols, thereby eliminating the need for a scanner, but this
      would make the parser larger and slower.</p>
    <p>The user should implement a scanner that segments the input
      text, and turns it into one or more lists of tokens. Each token
      should be a tuple containing information about syntactic
      category, position in the text (e.g. line number), and the
      actual terminal symbol found in the text: <span class="code">{Category, LineNumber, Symbol}</span>.</p>
    <p>If a terminal symbol is the only member of a category, and the
      symbol name is identical to the category name, the token format
      may be <span class="code">{Symbol, LineNumber}</span>.</p>
    <p>A list of tokens produced by the scanner should end with a
      special <span class="code">end_of_input</span> tuple which the parser is looking
      for. The format of this tuple should be <span class="code">{Endsymbol, LastLineNumber}</span>, where <span class="code">Endsymbol</span> is an identifier
      that is distinguished from all the terminal and non-terminal
      categories of the syntax rules. The <span class="code">Endsymbol</span> may be
      declared in the grammar file (see below).</p>
    <p>The simplest case is to segment the input string into a list of
      identifiers (atoms) and use those atoms both as categories and
      values of the tokens. For example, the input string <span class="code">aaa bbb 777, X</span> may be scanned (tokenized) as:</p>
    <div class="example"><pre>
[{aaa, 1}, {bbb, 1}, {777, 1}, {',' , 1}, {'X', 1},
 {'$end', 1}].    </pre></div>
    <p>This assumes that this is the first line of the input text, and
      that <span class="code">'$end'</span> is the distinguished <span class="code">end_of_input</span>
      symbol.</p>
    <p>The Erlang scanner in the <span class="code">io</span> module can be used as a
      starting point when writing a new scanner. Study
      <span class="code">yeccscan.erl</span> in order to see how a filter can be added on
      top of <span class="code">io:scan_erl_form/3</span> to provide a scanner for
      Yecc that tokenizes grammar files before parsing them
      with the Yecc parser. A more general approach to scanner
      implementation is to use a scanner generator. A scanner
      generator in Erlang called <span class="code">leex</span> is under development.</p>
  </div>

  <h3><a name="id60976">Grammar Definition Format</a></h3>
<div class="REFBODY">
    
    <p>Erlang style <span class="code">comments</span>, starting with a <span class="code">'%'</span>, are
      allowed in grammar files.</p>
    <p>Each <span class="code">declaration</span> or <span class="code">rule</span> ends with a dot (the
      character <span class="code">'.'</span>).</p>
    <p>The grammar starts with an optional <span class="code">header</span> section. The
      header is put first in the generated file, before the module
      declaration. The purpose of the header is to provide a means to
      make the documentation generated by <span class="code">EDoc</span> look nicer. Each
      header line should be enclosed in double quotes, and newlines
      will be inserted between the lines. For example:</p>
    <div class="example"><pre>
Header "%% Copyright (C)"
"%% @private"
"%% @Author John"</pre></div>
    <p>Next comes a declaration of the <span class="code">nonterminal categories</span>
      to be used in the rules. For example:</p>
    <div class="example"><pre>
Nonterminals sentence nounphrase verbphrase.    </pre></div>
    <p>A non-terminal category can be used at the left hand side (=
      <span class="code">lhs</span>, or <span class="code">head</span>) of a grammar rule. It can also
      appear at the right hand side of rules.</p>
    <p>Next comes a declaration of the <span class="code">terminal categories</span>,
      which are the categories of tokens produced by the scanner. For
      example:</p>
    <div class="example"><pre>
Terminals article adjective noun verb.    </pre></div>
    <p>Terminal categories may only appear in the right hand sides (=
      <span class="code">rhs</span>) of grammar rules.</p>
    <p>Next comes a declaration of the <span class="code">rootsymbol</span>, or start
      category of the grammar. For example:</p>
    <div class="example"><pre>
Rootsymbol sentence.    </pre></div>
    <p>This symbol should appear in the lhs of at least one grammar
      rule. This is the most general syntactic category which the
      parser ultimately will parse every input string into.</p>
    <p>After the rootsymbol declaration comes an optional declaration
      of the <span class="code">end_of_input</span> symbol that your scanner is expected
      to use. For example:</p>
    <div class="example"><pre>
Endsymbol '$end'.    </pre></div>
    <p>Next comes one or more declarations of <span class="code">operator precedences</span>, if needed. These are used to resolve
      shift/reduce conflicts (see <span class="code">yacc</span> documentation).</p>
    <p>Examples of operator declarations:</p>
    <div class="example"><pre>
Right 100 '='.
Nonassoc 200 '==' '=/='.
Left 300 '+'.
Left 400 '*'.
Unary 500 '-'.    </pre></div>
    <p>These declarations mean that <span class="code">'='</span> is defined as a
      <span class="code">right associative binary</span> operator with precedence 100,
      <span class="code">'=='</span> and <span class="code">'=/='</span> are operators with <span class="code">no associativity</span>, <span class="code">'+'</span> and <span class="code">'*'</span> are <span class="code">left associative binary</span> operators, where <span class="code">'*'</span> takes
      precedence over <span class="code">'+'</span> (the normal case), and <span class="code">'-'</span> is
      a <span class="code">unary</span> operator of higher precedence than <span class="code">'*'</span>.
      The fact that '==' has no associativity means that an expression
      like <span class="code">a == b == c</span> is considered a syntax error.</p>
    <p>Certain rules are assigned precedence: each rule gets its
      precedence from the last terminal symbol mentioned in the right
      hand side of the rule. It is also possible to declare precedence
      for non-terminals, "one level up". This is practical when an
      operator is overloaded (see also example 3 below).</p>
    <p>Next come the <span class="code">grammar rules</span>. Each rule has the general
      form</p>
    <div class="example"><pre>
Left_hand_side -&gt; Right_hand_side : Associated_code.    </pre></div>
    <p>The left hand side is a non-terminal category. The right hand
      side is a sequence of one or more non-terminal or terminal
      symbols with spaces between. The associated code is a sequence
      of zero or more Erlang expressions (with commas <span class="code">','</span> as
      separators). If the associated code is empty, the separating
      colon <span class="code">':'</span> is also omitted. A final dot marks the end of
      the rule.</p>
    <p>Symbols such as <span class="code">'{'</span>, <span class="code">'.'</span>, etc., have to be
      enclosed in single quotes when used as terminal or non-terminal
      symbols in grammar rules. The use of the symbols
      <span class="code">'$empty'</span>, <span class="code">'$end'</span>, and <span class="code">'$undefined'</span> should
      be avoided.</p>
    <p>The last part of the grammar file is an optional section with
      Erlang code (= function definitions) which is included 'as is'
      in the resulting parser file. This section must start with the
      pseudo declaration, or key words</p>
    <div class="example"><pre>
Erlang code.    </pre></div>
    <p>No syntax rule definitions or other declarations may follow
      this section. To avoid conflicts with internal variables, do not
      use variable names beginning with two underscore characters
      ('__') in the Erlang code in this section, or in the code
      associated with the individual syntax rules.</p>
    <p>The optional <span class="code">expect</span> declaration can be placed anywhere
      before the last optional section with Erlang code. It is used
      for suppressing the warning about conflicts that is ordinarily
      given if the grammar is ambiguous. An example:</p>
    <div class="example"><pre>
Expect 2.    </pre></div>
    <p>The warning is given if the number of shift/reduce conflicts
      differs from 2, or if there are reduce/reduce conflicts.
      </p>
  </div>

  <h3><a name="id62438">Examples</a></h3>
<div class="REFBODY">
    
    <p>A grammar to parse list expressions (with empty associated
      code):</p>
    <div class="example"><pre>
Nonterminals list elements element.
Terminals atom '(' ')'.
Rootsymbol list.
list -&gt; '(' ')'.
list -&gt; '(' elements ')'.
elements -&gt; element.
elements -&gt; element elements.
element -&gt; atom.
element -&gt; list.    </pre></div>
    <p>This grammar can be used to generate a parser which parses list
      expressions, such as <span class="code">(), (a), (peter charles), (a (b c) d (())), ...</span> provided that your scanner tokenizes, for
      example, the input <span class="code">(peter charles)</span> as follows:</p>
    <div class="example"><pre>
[{'(', 1} , {atom, 1, peter}, {atom, 1, charles}, {')', 1}, 
 {'$end', 1}]    </pre></div>
    <p>When a grammar rule is used by the parser to parse (part of)
      the input string as a grammatical phrase, the associated code is
      evaluated, and the value of the last expression becomes the
      value of the parsed phrase. This value may be used by the parser
      later to build structures that are values of higher phrases of
      which the current phrase is a part. The values initially
      associated with terminal category phrases, i.e. input tokens,
      are the token tuples themselves.</p>
    <p>Below is an example of the grammar above with structure
      building code added:</p>
    <div class="example"><pre>
list -&gt; '(' ')' : nil.
list -&gt; '(' elements ')' : '$2'.
elements -&gt; element : {cons, '$1', nil}.
elements -&gt; element elements : {cons, '$1', '$2'}.
element -&gt; atom : '$1'.
element -&gt; list : '$1'.    </pre></div>
    <p>With this code added to the grammar rules, the parser produces
      the following value (structure) when parsing the input string
      <span class="code">(a b c).</span>. This still assumes that this was the first
      input line that the scanner tokenized:</p>
    <div class="example"><pre>
{cons, {atom, 1, a,} {cons, {atom, 1, b},
                            {cons, {atom, 1, c}, nil}}}    </pre></div>
    <p>The associated code contains <span class="code">pseudo variables</span> <span class="code">'$1'</span>, <span class="code">'$2'</span>, <span class="code">'$3'</span>, etc. which refer to (are
      bound to) the values associated previously by the parser with
      the symbols of the right hand side of the rule. When these
      symbols are terminal categories, the values are token tuples of
      the input string (see above).</p>
    <p>The associated code may not only be used to build structures
      associated with phrases, but may also be used for syntactic and
      semantic tests, printout actions (for example for tracing), etc.
      during the parsing process. Since tokens contain positional
      (line number) information, it is possible to produce error
      messages which contain line numbers. If there is no associated
      code after the right hand side of the rule, the value
      <span class="code">'$undefined'</span> is associated with the phrase.</p>
    <p>The right hand side of a grammar rule may be empty. This is
      indicated by using the special symbol <span class="code">'$empty'</span> as rhs.
      Then the list grammar above may be simplified to:</p>
    <div class="example"><pre>
list -&gt; '(' elements ')' : '$2'.
elements -&gt; element elements : {cons, '$1', '$2'}.
elements -&gt; '$empty' : nil.
element -&gt; atom : '$1'.
element -&gt; list : '$1'.    </pre></div>
  </div>

  <h3><a name="id62048">Generating a Parser</a></h3>
<div class="REFBODY">
    
    <p>To call the parser generator, use the following command:</p>
    <div class="example"><pre>
yecc:file(Grammarfile).    </pre></div>
    <p>An error message from Yecc will be shown if the grammar
      is not of the LALR type (for example too ambiguous).
      Shift/reduce conflicts are resolved in favor of shifting if
      there are no operator precedence declarations. Refer to the
      <span class="code">yacc</span> documentation on the use of operator precedence.</p>
    <p>The output file contains Erlang source code for a parser module
      with module name equal to the <span class="code">Parserfile</span> parameter. After
      compilation, the parser can be called as follows (the module
      name is assumed to be <span class="code">myparser</span>):</p>
    <div class="example"><pre>
myparser:parse(myscanner:scan(Inport))    </pre></div>
    <p>The call format may be different if a customized prologue file
      has been included when generating the parser instead of the
      default file <span class="code">lib/parsetools/include/yeccpre.hrl</span>.</p>
    <p>With the standard prologue, this call will return either
      <span class="code">{ok, Result}</span>, where <span class="code">Result</span> is a structure that the
      Erlang code of the grammar file has built, or <span class="code">{error, {Line_number, Module, Message}}</span> if there was a syntax error
      in the input.</p>
    <p><span class="code">Message</span> is something which may be converted into a
      string by calling <span class="code">Module:format_error(Message)</span>
      and printed with <span class="code">io:format/3</span>.</p>
    <div class="note">
<div class="label">Note</div>
<div class="content"><p>
      <p>By default, the parser that was generated will not print out
        error messages to the screen. The user will have to do this
        either by printing the returned error messages, or by
        inserting tests and print instructions in the Erlang code
        associated with the syntax rules of the grammar file.</p>
    </p></div>
</div>
    <p>It is also possible to make the parser ask for more input
      tokens when needed if the following call format is used:</p>
    <div class="example"><pre>
myparser:parse_and_scan({Function, Args})
myparser:parse_and_scan({Mod, Tokenizer, Args})    </pre></div>
    <p>The tokenizer <span class="code">Function</span> is either a fun or a tuple
      <span class="code">{Mod, Tokenizer}</span>. The call <span class="code">apply(Function, Args)</span>
      or <span class="code">apply({Mod, Tokenizer}, Args)</span> is executed whenever a
      new token is needed. This, for example, makes it possible to
      parse from a file, token by token.</p>
    <p>The tokenizer used above has to be implemented so as to return
      one of the following:</p>
    <div class="example"><pre>
{ok, Tokens, Endline}
{eof, Endline}
{error, Error_description, Endline}    </pre></div>
    <p>This conforms to the format used by the scanner in the Erlang
      <span class="code">io</span> library module.</p>
    <p>If <span class="code">{eof, Endline}</span> is returned immediately, the call to
      <span class="code">parse_and_scan/1</span> returns <span class="code">{ok, eof}</span>. If <span class="code">{eof, Endline}</span> is returned before the parser expects end of input,
      <span class="code">parse_and_scan/1</span> will, of course, return an error message
      (see above). Otherwise <span class="code">{ok, Result}</span> is returned.</p>
  </div>

  <h3><a name="id61037">More Examples</a></h3>
<div class="REFBODY">
    
    <p>1. A grammar for parsing infix arithmetic expressions into
      prefix notation, without operator precedence:</p>
    <div class="example"><pre>
Nonterminals E T F.
Terminals '+' '*' '(' ')' number.
Rootsymbol E.
E -&gt; E '+' T: ['$2', '$1', '$3'].
E -&gt; T : '$1'.
T -&gt; T '*' F: ['$2', '$1', '$3'].
T -&gt; F : '$1'.
F -&gt; '(' E ')' : '$2'.
F -&gt; number : '$1'.    </pre></div>
    <p>2. The same with operator precedence becomes simpler:</p>
    <div class="example"><pre>
Nonterminals E.
Terminals '+' '*' '(' ')' number.
Rootsymbol E.
Left 100 '+'.
Left 200 '*'.
E -&gt; E '+' E : ['$2', '$1', '$3'].
E -&gt; E '*' E : ['$2', '$1', '$3'].
E -&gt; '(' E ')' : '$2'.
E -&gt; number : '$1'.    </pre></div>
    <p>3. An overloaded minus operator:</p>
    <div class="example"><pre>
Nonterminals E uminus.
Terminals '*' '-' number.
Rootsymbol E.

Left 100 '-'.
Left 200 '*'.
Unary 300 uminus.

E -&gt; E '-' E.
E -&gt; E '*' E.
E -&gt; uminus.
E -&gt; number.

uminus -&gt; '-' E.    </pre></div>
    <p>4. The Yecc grammar that is used for parsing grammar
      files, including itself:</p>
    <div class="example"><pre>
Nonterminals
grammar declaration rule head symbol symbols attached_code
token tokens.
Terminals
atom float integer reserved_symbol reserved_word string char var
'-&gt;' ':' dot.
Rootsymbol grammar.
Endsymbol '$end'.
grammar -&gt; declaration : '$1'.
grammar -&gt; rule : '$1'.
declaration -&gt; symbol symbols dot: {'$1', '$2'}.
rule -&gt; head '-&gt;' symbols attached_code dot: {rule, ['$1' | '$3'], 
        '$4'}.
head -&gt; symbol : '$1'.
symbols -&gt; symbol : ['$1'].
symbols -&gt; symbol symbols : ['$1' | '$2'].
attached_code -&gt; ':' tokens : {erlang_code, '$2'}.
attached_code -&gt; '$empty' : {erlang_code, 
                 [{atom, 0, '$undefined'}]}.
tokens -&gt; token : ['$1'].
tokens -&gt; token tokens : ['$1' | '$2'].
symbol -&gt; var : value_of('$1').
symbol -&gt; atom : value_of('$1').
symbol -&gt; integer : value_of('$1').
symbol -&gt; reserved_word : value_of('$1').
token -&gt; var : '$1'.
token -&gt; atom : '$1'.
token -&gt; float : '$1'.
token -&gt; integer : '$1'.
token -&gt; string : '$1'.
token -&gt; char : '$1'.
token -&gt; reserved_symbol : {value_of('$1'), line_of('$1')}.
token -&gt; reserved_word : {value_of('$1'), line_of('$1')}.
token -&gt; '-&gt;' : {'-&gt;', line_of('$1')}.
token -&gt; ':' : {':', line_of('$1')}.
Erlang code.
value_of(Token) -&gt;
    element(3, Token).
line_of(Token) -&gt;
    element(2, Token).    </pre></div>
    <div class="note">
<div class="label">Note</div>
<div class="content"><p>
      <p>The symbols <span class="code">'-&gt;'</span>, and <span class="code">':'</span> have to be treated in
        a special way, as they are meta symbols of the grammar
        notation, as well as terminal symbols of the Yecc
        grammar.</p>
    </p></div>
</div>
    <p>5. The file <span class="code">erl_parse.yrl</span> in the <span class="code">lib/stdlib/src</span>
      directory contains the grammar for Erlang.</p>
    <div class="note">
<div class="label">Note</div>
<div class="content"><p>
      <p>Syntactic tests are used in the code associated with some
        rules, and an error is thrown (and caught by the generated
        parser to produce an error message) when a test fails. The
        same effect can be achieved with a call to
        <span class="code">return_error(Error_line, Message_string)</span>, which is
        defined in the <span class="code">yeccpre.hrl</span> default header file.</p>
    </p></div>
</div>
  </div>

  <h3><a name="id61730">Files</a></h3>
<div class="REFBODY">
    
    <div class="example"><pre>
lib/parsetools/include/yeccpre.hrl    </pre></div>
  </div>

  <h3><a name="id61744">See Also</a></h3>
<div class="REFBODY">
    
    <p>Aho &amp; Johnson: 'LR Parsing', ACM Computing Surveys, vol. 6:2, 1974.</p>
  </div>
</div>
<div class="footer">
<hr>
<p>Copyright © 1997-2012 Ericsson AB. All Rights Reserved.</p>
</div>
</div>
</div></body>
</html>