forked from xrlin/goscheme
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
49 lines (44 loc) · 998 Bytes
/
parser.go
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
package goscheme
import "fmt"
// Parse read and parse the tokens to construct a syntax tree represents in nested slices.
func Parse(tokens *[]string) (ret []Expression, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%s", r)
}
}()
for len(*tokens) > 0 {
ret = append(ret, readTokens(tokens))
}
return
}
func readTokens(tokens *[]string) Expression {
if len(*tokens) == 0 {
return nil
}
token := (*tokens)[0]
*tokens = (*tokens)[1:]
switch token {
case "(":
ret := make([]Expression, 0)
for len(*tokens) >= 0 && (*tokens)[0] != ")" {
nextPart := readTokens(tokens)
ret = append(ret, nextPart)
}
if len(*tokens) == 0 {
panic("syntax error: missing ')'")
}
*tokens = (*tokens)[1:]
return ret
case ")":
panic("syntax error: unexpected ')'")
case "'":
ret := make([]Expression, 0, 4)
ret = append(ret, "quote")
nextPart := readTokens(tokens)
ret = append(ret, nextPart)
return ret
default:
return token
}
}