-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.rkt
121 lines (95 loc) · 3.04 KB
/
parser.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#lang racket
(provide parse print-ast)
(require "lexer.rkt")
; defining our structure Abstract Syntax Tree (ast) to store the arithmetic exp.
; for example, if the expression is, 1 - 2 * 3
; with operator precedence the correct exp. should be, (1 - (2 * 3))
; we will store the exp. in the tree like below,
; so that operators with higher precedence is lower in the tree!
; (-)
; / \
; (1) (*)
; / \
; (2) (3)
(define-struct ast [left op right])
(define (print-ast a-tree [notation "lisp"])
(cond
[(number? a-tree) a-tree]
[(ast? a-tree)
(cond
[(eq? notation "lisp")
(list
(ast-op a-tree)
(print-ast (ast-left a-tree) notation)
(print-ast (ast-right a-tree) notation)
)]
[else
(list
(print-ast (ast-left a-tree) notation)
(ast-op a-tree)
(print-ast (ast-right a-tree) notation)
)]
)]))
(define (parse input-exp)
(define next_tkn (lex input-exp))
(define (exponent)
; exponent : Number | LP expr RP
(match next_tkn
[(or `(Int ,num) `(Dec ,num))
(set! next_tkn (lex input-exp))
num]
[`(LP)
(set! next_tkn (lex input-exp))
(define node (expr))
(set! next_tkn (lex input-exp))
node]
[_ (error "Error: unknown expression!")]))
(define (factor)
; factor : exponent [^ factor]*
(define node (exponent))
(let loop ([updated_node node])
(match next_tkn
[(or '(EOF) '(RP)) updated_node]
[`(Sym ,symb)
(match symb
['^ (set! next_tkn (lex input-exp))
(loop (make-ast updated_node 'expt (factor) ))]
[_ updated_node]
)]
[_ (error "Error: unknown expression!")])))
(define (term)
; term : factor ((* | /) factor)*
(define node (factor))
(let loop ([updated_node node])
(match next_tkn
[(or '(EOF) '(RP)) updated_node]
[`(Sym ,symb)
(match symb
['* (set! next_tkn (lex input-exp))
(loop (make-ast updated_node symb (factor)))]
['/ (set! next_tkn (lex input-exp))
(loop (make-ast updated_node symb (factor)))]
[_ updated_node]
)]
[_ (error "Error: unknown expression!")])))
(define (expr)
; --
; expr : term [(+ | -) term]*
; term : factor [(* | /) factor]*
; factor : exponent [^ factor]*
; exponent : Number | LP expr RP
; --
(define node (term))
(let loop ([updated_node node])
(match next_tkn
[(or '(EOF) '(RP)) updated_node]
[`(Sym ,symb)
(match symb
['+ (set! next_tkn (lex input-exp))
(loop (make-ast updated_node symb (term)))]
['- (set! next_tkn (lex input-exp))
(loop (make-ast updated_node symb (term)))]
[_ updated_node]
)]
[_ (error "Error: unknown expression!")])))
(expr))