home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / pascal / compcomp / tpyacc / expr.y < prev    next >
Text File  |  1991-05-01  |  2KB  |  71 lines

  1.  
  2. /* Sample Yacc grammar for a simple desktop calculator; derived from a
  3.    grammar in Aho et al: Compilers. Principles, Techniques and Tools (sect.
  4.    4.9).
  5.  
  6.    Lexical analyzer is in Lex program ExprLex.l.
  7.  
  8.    To compile parser and lexical analyzer, issue the following commands:
  9.  
  10.      yacc expr
  11.      lex  exprlex
  12.      tpc  expr
  13.  
  14.    Description: This program reads simple arithmetic expressions, constructed
  15.    with real constants, operators +, -, *, /, unary - and parentheses
  16.    (operators have their usual precedence, unary minus is highest), from
  17.    standard input (one per line) and prints the result on standard output.
  18.    Variables are denoted by a single letter (no distinction between upper and
  19.    lowercase letters); they are assigned values through an assignment of the
  20.    form <var>=<expr>.
  21.    The program is terminated by entering an empty line. */
  22.  
  23. %{
  24.  
  25. uses YaccLib, LexLib;
  26.  
  27. var x : array [1..26] of Real;
  28.  
  29. %}
  30.  
  31. %token <Real> NUM       /* constants */
  32. %token <Integer> ID     /* variables */
  33. %type <Real> expr    /* expressions */
  34.  
  35. %left '+' '-'          /* operators */
  36. %left '*' '/'
  37. %right UMINUS
  38.  
  39. %token ILLEGAL         /* illegal token */
  40.  
  41. %%
  42.  
  43. input    : /* empty */
  44.     | input '\n'         { yyaccept; }
  45.     | input expr '\n'     { writeln($2:10:2); }
  46.     | input ID '=' expr '\n' { x[$2] := $4; writeln($4:10:2); }
  47.     | error '\n'             { yyerrok; }
  48.     ;
  49.  
  50. expr    :  expr '+' expr     { $$ := $1 + $3; }
  51.     |  expr '-' expr     { $$ := $1 - $3; }
  52.     |  expr '*' expr     { $$ := $1 * $3; }
  53.     |  expr '/' expr     { $$ := $1 / $3; }
  54.     |  '(' expr ')'         { $$ := $2; }
  55.     |  '-' expr              { $$ := -$2; }
  56.            %prec UMINUS
  57.     |  NUM                   { $$ := $1; }
  58.         |  ID                    { $$ := x[$1]; }
  59.     ;
  60.  
  61. %%
  62.  
  63. {$I ExprLex}
  64.  
  65. var i : Integer;
  66.  
  67. begin
  68.   for i := 1 to 26 do x[i] := 0.0;
  69.   if yyparse=0 then { done };
  70. end.
  71.