-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer.lisp
102 lines (85 loc) · 2.78 KB
/
tokenizer.lisp
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
(load "./lib/utils.lisp")
(load "./lib/globals.lisp")
(load "exceptions.lisp")
(defun lil-tokenize (str)
(let ((expr
(if (char= (char str 0) #\()
(subseq str 1 (nth 1 (utl-string-get-last-char str)))
nil
))
(tokens '()))
(dotimes (i (length expr))
(cond
((char= (char expr i) #\+)
(push (list token-symbol (char expr i)) tokens)
)
((char= (char expr i) #\/)
(push (list token-symbol (char expr i)) tokens)
)
((char= (char expr i) #\*)
(push (list token-symbol (char expr i)) tokens)
)
((char= (char expr i) #\-)
(push (list token-symbol (char expr i)) tokens)
)
((char= (char expr i) #\()
(push (list token-lp (char expr i)) tokens)
)
(
(and (digit-char-p (char expr i)) t)
(progn
(let ((num (subseq expr i (- (nth 0 (utl-find-next-space-or-end i expr)) 0))))
(push (list token-number (parse-integer num)) tokens)
(setq i (+ i (nth 1 (utl-find-next-space-or-end i expr))))
)
)
)
(t ()))
)
(reverse tokens)))
(defun lil-eval-stack (stack)
(let ((result 0) (local-stack '()))
(dotimes (i (length stack))
(cond
((numberp (nth i stack)) (push (nth i stack) local-stack))
((char= (nth i stack) #\+)
(let ((computed (reduce #'+ (mapcar #'identity local-stack))))
(setq local-stack '())
(push computed local-stack)
))
((char= (nth i stack) #\/)
(let ((computed (reduce #'/ (mapcar #'identity local-stack))))
(setq local-stack '())
(push computed local-stack)
))
((char= (nth i stack) #\*)
(let ((computed (reduce #'* (mapcar #'identity local-stack))))
(setq local-stack '())
(push computed local-stack)
))
((char= (nth i stack) #\-)
(let ((computed (reduce #'- (mapcar #'identity local-stack))))
(setq local-stack '())
(push computed local-stack)
))
))
local-stack))
(defun lil-parse (tokens) "Expects a list of tokens"
(let ((stack '()) (token nil) (token-type nil) (token-value nil) (paren-open t))
(dotimes (i (length tokens))
(setq token (nth i tokens))
(setq token-type (nth 0 token))
(setq token-value (nth 1 token))
(cond
((and (eql token-type #\() (not paren-open))
(setq paren-open t))
((and (eql token-type #\)) paren-open)
(setq paren-open nil))
((eql token-type 'SYMBOL)
(push token-value stack))
((eql token-type 'NUMBER)
(push token-value stack))
)
)
(lil-eval-stack stack))
)