-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsyntax.go
More file actions
111 lines (92 loc) · 2.14 KB
/
syntax.go
File metadata and controls
111 lines (92 loc) · 2.14 KB
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
package mist
import "fmt"
func consume(tokens *TokenIterator, types ...int) Token {
if !tokens.HasNext() {
panic("incomplete code")
}
next := tokens.Peek()
for _, tokenType := range types {
if next.Type == tokenType {
return tokens.Next()
}
}
panic("TODO")
}
func consumeExcept(tokens *TokenIterator, types ...int) Token {
if !tokens.HasNext() {
panic("TODO")
}
next := tokens.Peek()
for _, tokenType := range types {
if next.Type == tokenType {
panic(fmt.Sprintf("%v: unexpected token %s", next.Origin, next.Short()))
}
}
return tokens.Next()
}
func parseAtom(tokens *TokenIterator) Node {
next := consumeExcept(tokens, TokenLeftParen, TokenRightParen, TokenQuote)
switch next.Type {
case TokenLeftParen:
fallthrough
case TokenRightParen:
fallthrough
case TokenQuote:
panic("TODO")
case TokenNumber:
return NewNodeU256(next.ValueNumber, next.Origin)
case TokenString:
return NewNodeString(next.ValueString, next.Origin)
case TokenSymbol:
return NewNodeSymbol(next.ValueString, next.Origin)
default:
panic("TODO")
}
}
func parseList(tokens *TokenIterator) Node {
left := consume(tokens, TokenLeftParen)
defer consume(tokens, TokenRightParen)
root := NewNodeList(left.Origin)
for tokens.HasNext() {
next := tokens.Peek()
if next.Type == TokenLeftParen {
// That's a nested list, go deeper.
root.AddChild(parseList(tokens))
} else if next.Type == TokenRightParen {
break
} else {
root.AddChild(parse(tokens))
}
}
return root
}
func parse(tokens *TokenIterator) Node {
for tokens.HasNext() {
next := tokens.Peek()
switch next.Type {
case TokenLeftParen:
return parseList(tokens)
case TokenRightParen:
panic("unbalanced parentheses")
case TokenQuote:
tokens.Next() // Consume the quote token.
child := parse(tokens)
quote := NewNodeQuote(child, next.Origin)
return quote
case TokenNumber:
fallthrough
case TokenString:
fallthrough
case TokenSymbol:
return parseAtom(tokens)
}
}
panic("unreachable")
}
func Parse(tokens *TokenIterator) Node {
progn := NewNodeProgn()
for tokens.HasNext() {
progn.AddChild(parse(tokens))
}
return progn
}