-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinline.go
More file actions
193 lines (168 loc) · 5.48 KB
/
inline.go
File metadata and controls
193 lines (168 loc) · 5.48 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
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
package main
import (
"bytes"
_ "embed"
"fmt"
"regexp"
"strings"
)
// Template markers
const (
markerInlineBody = "// {{INLINE_BODY}}"
markerPipeBefore = "// {{PIPE_BEFORE}}"
markerPipeBody = "// {{PIPE_BODY}}"
markerPipeAfter = "// {{PIPE_AFTER}}"
markerBatchBody = "// {{BATCH_BODY}}"
markerFields = "{{FIELDS_EXPR}}"
markerParallelN = "{{PARALLEL_N}}"
)
//go:embed script.go.template
var simpleTmpl []byte
//go:embed pipe.go.template
var pipeTmpl []byte
//go:embed batch.go.template
var batchTmpl []byte
//go:embed parallel.go.template
var parallelTmpl []byte
// InlineMode describes which template to use.
type InlineMode int
const (
ModeSimple InlineMode = iota // no magic vars
ModePipe // x/line/i/f referenced → per-line loop
ModeBatch // only lines referenced → pre-load all, no loop
)
// pipeVars are magic variables that trigger per-line loop mode.
var pipeVarNames = []string{"x", "line", "i", "idx", "index", "f", "fields"}
// batchVarNames trigger batch mode (all lines at once).
var batchVarNames = []string{"lines"}
// DetectInlineMode inspects the code snippet for magic variable references.
func DetectInlineMode(code string) InlineMode {
for _, v := range pipeVarNames {
if containsIdent(code, v) {
return ModePipe
}
}
for _, v := range batchVarNames {
if containsIdent(code, v) {
return ModeBatch
}
}
return ModeSimple
}
// containsIdent checks whether s contains identifier name as a whole word.
func containsIdent(s, name string) bool {
pattern := `\b` + regexp.QuoteMeta(name) + `\b`
matched, _ := regexp.MatchString(pattern, s)
return matched
}
// InlineToScript converts a code snippet to a complete Go source file.
// It auto-detects the appropriate template based on magic variable usage.
// parallel > 0 activates concurrent loop mode (pipe only).
// regexPat, when non-empty, compiles a regex and exposes r/m/n/sub/suball in pipe mode.
func InlineToScript(code string, fieldSep string, parallel int, regexPat string) ([]byte, InlineMode, error) {
mode := DetectInlineMode(code)
// -r always implies pipe mode (m/n/sub/suball only exist in the loop context)
if regexPat != "" && mode == ModeSimple {
mode = ModePipe
}
code = wrapLastExpr(code)
body := indentAsBlock(strings.TrimSpace(code), "\t")
switch mode {
case ModePipe:
return buildPipeScript(body, fieldSep, parallel, regexPat), mode, nil
case ModeBatch:
return buildBatchScript(body), mode, nil
default:
return buildSimpleScript(body), mode, nil
}
}
func buildParallelScript(body string, fieldSep string, n int, regexPat string) []byte {
var fieldsExpr string
if fieldSep == "" {
fieldsExpr = "strings.Fields(x)"
} else {
fieldsExpr = `strings.Split(x, "` + fieldSep + `")`
}
before := ""
if regexPat != "" {
body = indentAsBlock(regexLoopPrefix("return"), "\t") + "\n" + body
before = indentAsBlock(regexSetupBefore(regexPat), "\t")
}
out := parallelTmpl
out = bytes.Replace(out, []byte(markerFields), []byte(fieldsExpr), 1)
out = bytes.Replace(out, []byte(markerParallelN), []byte(fmt.Sprintf("%d", n)), 1)
out = bytes.Replace(out, []byte(markerPipeBefore), []byte(before), 1)
out = bytes.Replace(out, []byte(markerPipeBody), []byte(body), 1)
return out
}
func buildSimpleScript(body string) []byte {
return bytes.Replace(simpleTmpl, []byte(markerInlineBody), []byte(body), 1)
}
func buildBatchScript(body string) []byte {
return bytes.Replace(batchTmpl, []byte(markerBatchBody), []byte(body), 1)
}
func buildPipeScript(body string, fieldSep string, parallel int, regexPat string) []byte {
if parallel > 0 {
return buildParallelScript(body, fieldSep, parallel, regexPat)
}
var fieldsExpr string
if fieldSep == "" {
fieldsExpr = "strings.Fields(x)"
} else {
fieldsExpr = `strings.Split(x, "` + fieldSep + `")`
}
before := ""
if regexPat != "" {
body = indentAsBlock(regexLoopPrefix("continue"), "\t") + "\n" + body
before = indentAsBlock(regexSetupBefore(regexPat), "\t")
}
out := pipeTmpl
out = bytes.Replace(out, []byte(markerFields), []byte(fieldsExpr), 1)
out = bytes.Replace(out, []byte(markerPipeBefore), []byte(before), 1)
out = bytes.Replace(out, []byte(markerPipeBody), []byte(body), 1)
out = bytes.Replace(out, []byte(markerPipeAfter), []byte(""), 1)
return out
}
// regexSetupBefore generates the code placed before the pipe loop when -r is used.
// It compiles the regex into r and defines sub/suball as closures over r.
func regexSetupBefore(pat string) string {
return fmt.Sprintf(`r := regexp.MustCompile(%s)
sub := func(repl, s string) string {
loc := r.FindStringSubmatchIndex(s)
if loc == nil {
return s
}
var dst []byte
dst = r.ExpandString(dst, repl, s, loc)
return s[:loc[0]] + string(dst) + s[loc[1]:]
}
suball := func(repl, s string) string { return r.ReplaceAllString(s, repl) }
_ = sub; _ = suball`, fmt.Sprintf("%q", pat))
}
// regexLoopPrefix generates the per-line setup injected at the top of the loop body.
// jumpStmt is "continue" for pipe mode and "return" for parallel mode.
func regexLoopPrefix(jumpStmt string) string {
return `m := r.FindStringSubmatch(x)
if m == nil { ` + jumpStmt + ` }
n := map[string]string{}
for _i, _name := range r.SubexpNames() {
if _name != "" && _i < len(m) {
n[_name] = m[_i]
}
}
_ = m; _ = n`
}
func indentAsBlock(s, prefix string) string {
if s == "" {
return ""
}
lines := strings.Split(s, "\n")
for i, ln := range lines {
if strings.TrimSpace(ln) == "" {
lines[i] = ""
} else {
lines[i] = prefix + ln
}
}
return strings.Join(lines, "\n")
}