The Interpreter(and more parsing)
Table of Contents
1. (More of)The parser
Flowchart once again
program -> [parser] -> AST -> [Interp] -> Result
Technichally alternative way out of the parser
- Syntax errors!
So lets add this…
[other (error 'parse "expected valid syntax, got ~e" other)]))
And test it…
(check-exn #rx"expected valid syntax"
(lambda () (parse '{+ 1}')))
#+name Parser From before but with syntax error handelling
;;1. Data Definitions
(define-type ExprC (U NumC PlusC MultC))
(struct NumC ([n : Real]) #:transparent)
(struct PlusC ([left : ExprC] [right : ExprC]) #:transparent)
(struct MultC ([left : ExprC] [right : ExprC]) #:transparent)
;;2. Purpose Statement and header
;;parse the given program into an AST
(define (parse [prog : Sexp]) : ExprC
(match prog
;;<num>
[(? real? n) (NumC n)]
;; {+ <expr> <expr>}
[(list '+ l r) (Plusc (parse l) (parse r))]
;; {* <expr> <expr>}
[(list '* l r) (MultC (parse l) (parse r))]
[other (error 'parse "expected valid syntax, got ~e" other)]))
;;3. tests
(check-equal? (parse '{* {+ 2 3} 7})
(MultC (PlusC (NumC 2) (NumC 3))
(NumC 7)))
(check-equal? (parse '2) (NumC 2))
(check-equal? (parse '{+ 3 4})
(PlusC (NumC 3) (NumC 4)))
(check-exn #rx"expected valid syntax"
(lambda () (parse '{+ 1}')))
2. The Interpreter
The interp function
(define (interp [exp : ExprC]) : Real
(match exp
[(NumC n) n]
[(PlusC l r) (+ (interp l) (interp r) )]
[(Mult l r) (* (interp l) (interp r) )])
)
;; We can test the interp with the result of parse
(check-equal? (interp (parse '{* {+ 2 3} 7}) ) 35)
(check-equal? (interp (parse '{2})) 2)
2.1. Adding functions
Functions are statements not expressions.
Function Definitions
- name
- arguments
- body
EX:
{def f {(x) =? …}}
Syntax for Function definitions
<defn>::={def <id> {(<id>) => <expr>}}
✓ ✓ {def f {(x) => 17}}
✓ {def double {(x) => {* 2 x}}} -> once we add <id>
Need to add expression to call functions…
#+name adding to expressions
<expr> ::= <num
| {+ <expr> <expr>}
| {* <expr> <expr>}
| {<id> <expr>} for function calls
| <id> for stuff like x
2.2. Back to the interpreter
{+ {double {f 4}} 7}
= {+ {double {+ {* 4 3} 1}} 7}
= {+ {double {+ { 12 } 1}} 7}
= {+ {double { 13 }} 7}
= {+ { * 2 13 } 7}
= {+ 26 7}
= 33