Next: , Previous: , Up: Wisent Grammar [Contents][Index]


2.2 Example

Here is an example to parse simple infix arithmetic expressions. See (bison)Infix Calc, in the Bison manual for details.

'(
 ;; Terminals
 (NUM)
 ;; Terminal associativity & precedence
 ((nonassoc ?=)
 (left ?- ?+)
 (left ?* ?/)
 (left NEG)
 (right ?^))
 ;; Rules
 (input
 ((line))
 ((input line)
 (format "%s %s" 1ドル 2ドル))
 )
 (line
 ((?;)
 (progn ";"))
 ((exp ?;)
 (format "%s;" 1ドル))
 ((error ?;)
 (progn "Error;")))
 )
 (exp
 ((NUM)
 (string-to-number 1ドル))
 ((exp ?= exp)
 (= 1ドル 3ドル))
 ((exp ?+ exp)
 (+ 1ドル 3ドル))
 ((exp ?- exp)
 (- 1ドル 3ドル))
 ((exp ?* exp)
 (* 1ドル 3ドル))
 ((exp ?/ exp)
 (/ 1ドル 3ドル))
 ((?- exp) [NEG]
 (- 2ドル))
 ((exp ?^ exp)
 (expt 1ドル 3ドル))
 ((?\( exp ?\))
 (progn 2ドル))
 )
 )

In the bison-like WY format (see How to use Wisent with Semantic) the grammar looks like this:

%token <number> NUM
%nonassoc '=' ;; comparison
%left '-' '+'
%left '*' '/'
%left NEG ;; negation--unary minus
%right '^' ;; exponentiation
%%
input:
 line
 | input line
 (format "%s %s" 1ドル 2ドル)
 ;
line:
 ';'
 {";"}
 | exp ';'
 (format "%s;" 1ドル)
 | error ';'
 {"Error;"}
 ;
exp:
 NUM
 (string-to-number 1ドル)
 | exp '=' exp
 (= 1ドル 3ドル)
 | exp '+' exp
 (+ 1ドル 3ドル)
 | exp '-' exp
 (- 1ドル 3ドル)
 | exp '*' exp
 (* 1ドル 3ドル)
 | exp '/' exp
 (/ 1ドル 3ドル)
 | '-' exp %prec NEG
 (- 2ドル)
 | exp '^' exp
 (expt 1ドル 3ドル)
 | '(' exp ')'
 {2ドル}
 ;
%%

AltStyle によって変換されたページ (->オリジナル) /