; -*- Hen -*- ;;; ;;;; Simple calculator in Scheme ;;; ;; Simple arithmetic calculator. ;; ;; This program illustrates the use of the lalr-scm parser generator ;; for Scheme. It is NOT robust, since calling a function with ;; the wrong number of arguments may generate an error that will ;; cause the calculator to crash. ;;; ;;;; The LALR(1) parser ;;; (import scheme (chicken base) lalr) (define calc-parser (lalr-parser ;; --- Options ;; output a parser, called calc-parser, in a separate file - calc.yy.scm, (output: calc-parser "calc.yy.scm") ;; output the LALR table to calc.out (out-table: "calc.out") ;; there should be no conflict (expect: 5) ;; --- token definitions (ID NUM = LPAREN RPAREN NEWLINE COMMA (left: + -) (left: * /) (nonassoc: uminus)) (lines (lines line) : (display-result $2) (line) : (display-result $1)) ;; --- rules (line (assign NEWLINE) : $1 (expr NEWLINE) : $1 (NEWLINE) : #f (error NEWLINE) : #f) (assign (ID = expr) : (add-binding $1 $3)) (expr (expr + expr) : (+ $1 $3) (expr - expr) : (- $1 $3) (expr * expr) : (* $1 $3) (expr / expr) : (/ $1 $3) (- expr (prec: uminus)) : (- $2) (ID) : (get-binding $1) (ID LPAREN args RPAREN) : (invoke-proc $1 $3) (NUM) : $1 (LPAREN expr RPAREN) : $2) (args () : '() (expr arg-rest) : (cons $1 $2)) (arg-rest (COMMA expr arg-rest) : (cons $2 $3) () : '())))