-
Notifications
You must be signed in to change notification settings - Fork 1
/
golf.go
234 lines (218 loc) · 6.12 KB
/
golf.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package main
import (
"bufio"
"fmt"
"github.com/traefik/yaegi/interp"
"github.com/traefik/yaegi/stdlib"
"io/ioutil"
"net/http"
"os"
"reflect"
"strings"
)
type golf struct {
interpreter *interp.Interpreter
}
const (
funcProcessingPrefix = " ### "
)
func NewGolf(gopath string) *golf {
interpreter := interp.New(interp.Options{
GoPath: gopath,
})
interpreter.Use(stdlib.Symbols)
// default imports
doDotImport(interpreter, "fmt")
doDotImport(interpreter, "strings")
doImport(interpreter, "os")
builtIns(interpreter)
return &golf{interpreter: interpreter}
}
func builtIns(interpreter *interp.Interpreter) {
statements := []string{
"var arg = make(map[string]interface{})",
"func isSet(key string) bool { _, ok := arg[key]; return ok }",
"var includes = []string{}",
"func include(resource string) { includes = append(includes, resource) }",
}
for _, statement := range statements {
_, err := interpreter.Eval(statement)
checkFail(err, "Failed to initialize the built-in variables and function. Detail: "+statement)
}
}
func doImport(interpreter *interp.Interpreter, pkg string) {
_, err := interpreter.Eval(`import "` + pkg + `"`)
checkFail(err, "Package not found: "+pkg)
}
func doDotImport(interpreter *interp.Interpreter, pkg string) {
_, err := interpreter.Eval(`import . "` + pkg + `"`)
checkFail(err, "Package not found: "+pkg)
}
func (g *golf) eval(call string, line string, fullLine string, verbose bool) (result string, ok bool, repeat bool, next int64, err error) {
// disable the repeat instruction
_, err = g.interpreter.Eval("includes = []string{}")
if err != nil {
return "", false, false, 0, err
}
_, err = g.interpreter.Eval("repeat := false")
if err != nil {
return "", false, false, 0, err
}
_, err = g.interpreter.Eval("next := 0")
if err != nil {
return "", false, false, 0, err
}
_, err = g.interpreter.Eval("line := `" + line + "`")
if err != nil {
return "", false, false, 0, err
}
_, err = g.interpreter.Eval("fline := `" + fullLine + "`")
if err != nil {
return "", false, false, 0, err
}
_, err = g.interpreter.Eval("token := Split(line, ` `)")
if err != nil {
return "", false, false, 0, err
}
_, err = g.interpreter.Eval("ftoken := Split(fline, ` `)")
if err != nil {
return "", false, false, 0, err
}
resultValue, err := g.interpreter.Eval(call)
result = resultValue.String()
ok = resultValue.Kind() == reflect.String
if err != nil {
return "", false, false, 0, err
}
repeatValue, err := g.interpreter.Eval("repeat")
repeat = repeatValue.Bool()
nextValue, err := g.interpreter.Eval("next")
next = nextValue.Int()
includesValue, erri := g.interpreter.Eval("includes")
if erri != nil {
return "", false, false, 0, erri
}
okIncludes := includesValue.Kind() == reflect.Slice
if okIncludes {
for i := 0; i < includesValue.Len(); i++ {
g.include(includesValue.Index(i).String(), verbose)
}
}
return
}
func (g *golf) processInitialize(initialize string, verbose bool) {
if verbose && len(initialize) > 0 {
fmt.Printf("Initialize: '%s'\n", initialize)
}
_, err := g.interpreter.Eval(initialize)
checkFail(err, "Initialization syntax error: '"+initialize+"'")
}
func (g *golf) processFile(filename string, verbose bool) string {
output := ""
file, err := os.Open(filename)
checkFail(err, "File "+filename+" not openable!")
defer file.Close()
scanner := bufio.NewScanner(file)
// start processing
lineCounter := 0
nextLines := 0
repeatFunction := ""
if verbose {
fmt.Printf("File: %s\n", filename)
}
for scanner.Scan() {
line := scanner.Text()
lineCounter++
function, arg := getGoLineFunction(line)
if len(function) == 0 && len(repeatFunction) > 0 {
function = repeatFunction
arg = line
if nextLines > 0 {
nextLines -= 1
}
} else {
nextLines = 0
}
if len(function) > 0 {
result, ok, repeat, next, err := g.eval(function, arg, line, verbose)
if err == nil {
if verbose {
fmt.Printf("[%4.0d] %s\n", lineCounter, line)
}
} else {
processFail(filename, lineCounter, line, function, verbose, err)
}
if !repeat && nextLines == 0 && repeatFunction == "" && next > 0 {
nextLines = int(next)
}
if repeat || nextLines > 0 {
repeatFunction = function
} else {
nextLines = 0
repeatFunction = ""
}
if ok {
line = processResult(result, verbose, line)
}
}
output += line + "\n"
}
checkFail(scanner.Err(), "File "+filename+" not readable!")
return output
}
func (g *golf) include(inc string, verbose bool) {
if verbose {
fmt.Printf("Including: %s\n", inc)
}
if strings.HasPrefix(strings.ToLower(inc), "https://") ||
strings.HasPrefix(strings.ToLower(inc), "http://") {
g.includeHttp(inc)
} else {
g.includeFile(inc)
}
}
func (g *golf) includeHttp(inc string) {
resp, err := http.Get(inc)
checkFail(err, "Include could not be loaded from " + inc)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
checkFail(err, "Include could not be read from " + inc)
_, err = g.interpreter.Eval(string(body))
checkFail(err, "File could not be included: "+inc)
}
func (g *golf) includeFile(inc string) {
checkFile(inc)
content, err := ioutil.ReadFile(inc)
checkFail(err, "File could not be loaded: "+inc)
_, err = g.interpreter.Eval(string(content))
checkFail(err, "File could not be included: "+inc)
}
func getGoLineFunction(line string) (function string, arg string) {
function = ""
prefix := funcProcessingPrefix
functionIdx := strings.Index(line, prefix)
if functionIdx >= 0 {
function = line[functionIdx+len(prefix):]
function = strings.TrimSpace(function)
arg = line[0:functionIdx]
}
return
}
func processResult(result string, verbose bool, line string) string {
processed := fmt.Sprintf("%s", result)
if verbose {
fmt.Printf(" ➥ %s\n", processed)
}
line = fmt.Sprintf("%s", processed)
return line
}
func processFail(filename string, lineCounter int, line string, function string, verbose bool, err error) {
if !verbose {
printTitle()
fmt.Printf("File: %s\n", filename)
}
fmt.Printf("[%4.0d] %s\n", lineCounter, line)
println()
fmt.Printf(" Code: %s\n", function)
checkFail(err, fmt.Sprintf("Check the golf syntax in %s:%d", filename, lineCounter))
}