forked from erh/scheme
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast.go
125 lines (99 loc) · 2.05 KB
/
ast.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
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
122
123
124
125
package scheme
import (
"fmt"
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer/stateful"
)
type Boolean bool
func (b *Boolean) Capture(values []string) error {
*b = values[0] == "true"
return nil
}
type Value struct {
Float *float64 ` @Float`
Bool *Boolean `| @("true" | "false")`
AString *string `| @String`
Func SchemeFunction
}
func (v Value) ToFloat() (float64, error) {
if v.Float != nil {
return *v.Float, nil
}
return 0, fmt.Errorf("not a number (%s)", v.String())
}
func (v Value) Primitive() interface{} {
if v.Float != nil {
return *v.Float
}
if v.Bool != nil {
return *v.Bool
}
if v.AString != nil {
s := *v.AString
return s
}
panic("help")
}
func (v Value) String() string {
if v.Float != nil {
return fmt.Sprintf("%v", *v.Float)
}
if v.AString != nil {
return *v.AString
}
if v.Bool != nil {
return fmt.Sprintf("%v", *v.Bool)
}
if v.Func != nil {
return "func"
}
panic("what am i!")
}
type Expression struct {
Call []*Expression `"(" @@+ ")"|`
Val *Value `@@|`
Var *string `@Ident|`
Symbol *string `@Symbol`
}
func (e Expression) String() string {
if e.Val != nil {
return e.Val.String()
}
if e.Var != nil {
return *e.Var
}
if e.Symbol != nil {
return *e.Symbol
}
if len(e.Call) > 0 {
s := "("
for _, x := range e.Call {
s += x.String() + " "
}
s += ")"
return s
}
panic("why am i alive")
}
var (
schemeLexer = stateful.MustSimple([]stateful.Rule{
{"Ident", `[a-zA-Z]\w*`, nil},
{"Float", `[-+]?\d*\.?\d+([eE][-+]?\d+)?`, nil},
{"String", `"(\\"|[^"])*"`, nil},
{"Whitespace", `[ \t\n\r]+`, nil},
{"Symbol", "(=|<=|\\+|\\*|-|/)", nil},
{"EOL", `[\n\r]+`, nil},
{"Punct", `[-[!@#$%^&*()+_={}\|:;"'<,>.?/]|]`, nil},
})
schemeParser = participle.MustBuild(
&Expression{},
participle.Lexer(schemeLexer),
participle.Unquote("String"),
participle.Elide("Whitespace"),
)
)
func Parse(s string) (*Expression, error) {
e := &Expression{}
err := schemeParser.ParseString("", s, e)
return e, err
}