blob: 4579b9337aaf053c71cdcecc6407cacfbe25574c (
plain)
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
|
#include "stdlib.lisp"
(define str-elem (ch str)
(if (= str "") 0
(if (= ch (substr 0 1 str)) 1
(str-elem ch (substr 1 -1 str)))))
(define isspace? (ch)
(str-elem ch " \n\t\r"))
(define isdigit? (ch)
(let ((n (ord ch))) (and (<= 48 n) (<= 57 n))))
(define lowercase? (ch)
(let ((n (ord ch))) (and (<= 97 n) (<= n 122))))
(define uppercase? (ch)
(let ((n (ord ch))) (and (<= 65 n) (<= n 90))))
(define iswordchar? (ch)
(or (str-elem ch "-_?")
(or (lowercase? ch) (uppercase? ch))))
(define isrestwordchar? (ch)
(or (iswordchar? ch) (isdigit? ch)))
(define parse-int (str)
(let ((helper (lambdarec rec (str n)
(let ((ch (substr 0 1 str))
(rest (substr 1 -1 str)))
(if (isdigit? ch)
(rec rest (+ (* 10 n) (- (ord ch) 48)))
n)))))
(helper str 0)))
(define next-token (str)
(let ((ch (substr 0 1 str))
(rest (substr 1 -1 str)))
(cond
(= ch "")
'()
(isspace? ch)
(next-token rest)
(= ch ";")
(next-token (drop-while (lambda (c) (not (= c "\n"))) rest))
(= ch "(")
(list "(" rest)
(= ch ")")
(list ")" rest)
(iswordchar? ch)
(let ((restword (take-while isrestwordchar? rest)))
(list (concat ch restword) (substr (length restword) -1 rest)))
(isdigit? ch)
(let ((word (concat ch (take-while isdigit? rest))))
(list (parse-int word) (substr (length word) -1 str)))
(do
(print (concat "Invalid token: " ch))
(exit)))))
; (define parse-sexpr (tokens)
; ...)
|