-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprego.go
366 lines (321 loc) · 7.95 KB
/
prego.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package prego
import . "fmt"
import (
"bufio"
"bytes"
"io"
"log"
"os"
"regexp"
"strings"
"text/scanner"
)
var MatchPlusBuildPrego = regexp.MustCompile(`^\s*//\s*[+]build\s+(prego)\s*$`)
var MatchPlusBuild = regexp.MustCompile(`^\s*//\s*[+]build\s+(.*)$`)
// MatchDirective looks for "//#word" (for some word) (as first nonwhite chars)
// possibly followed by other stuff.
var MatchDirective = regexp.MustCompile(`[ \t]*//\s*[#]\s*([a-z]+)[ \t]*(.*)*$`)
var MatchBeforeSlashSlash = regexp.MustCompile("(.*?)//")
var MatchBug = regexp.MustCompile("[\"'`\\\\]")
var MatchMacroDef = regexp.MustCompile(`^\s*func\s*[(]\s*(inline|macro)\s*[)]\s*([A-Za-z0-9_]+)\s*[(]([^()]*)[)]([^{}]*)[{]`)
var MatchMacroReturn = regexp.MustCompile(`^\s*return\s*(.*)$`)
var MatchMacroFinal = regexp.MustCompile(`^\s*[}]\s*$`)
var MatchMacroCall = regexp.MustCompile(`\b(?:inline|macro)\s*[.]\s*([A-Za-z0-9_]+)\s*[(]`)
var MatchIdentifier = regexp.MustCompile(`[A-Za-z0-9_]+`)
var MatchFormalArg = regexp.MustCompile(`([A-Za-z0-9_]+) *([^(),]*)`)
var MatchEndsWithOpenCurly = regexp.MustCompile(`.*{\s*`)
var MatchBeginsWithIf = regexp.MustCompile(`\s*if\s+.*`)
var MatchOneQuote = regexp.MustCompile(`^[^"]*["][^"]*$`)
var logWarning = log.New(os.Stderr, "", 0)
type Macro struct {
Inline bool // T if `inline`, F if `macro`
Args []string
Body []string
Result string
RetType string
}
type Po struct {
Macros map[string]*Macro
Switches map[string]bool
Stack []bool
W io.Writer
Serial int
Enabled bool
Lines []string
I int
Inlining bool
}
func (po *Po) Fatalf(s string, args ...interface{}) {
args = append(args, po.I+1)
log.Fatalf("prego preprocessor: ERROR: "+s+" (at line %d)", args...)
}
func (po *Po) Warningf(s string, args ...interface{}) {
args = append(args, po.I+1)
logWarning.Printf("prego preprocessor: WARNING: "+s+" (at line %d)", args...)
}
func (po *Po) replaceFromMap(s string, subs map[string]string, serial int) string {
if z, ok := subs[s]; ok {
return z
}
if strings.HasPrefix(s, "__") {
return Sprintf("_%d%s", serial, s)
}
return s
}
func (po *Po) SubstitueMacros(s string) string {
for {
z := po.SubstitueMacrosOnce(s)
if z == s {
return z
}
s = z
}
}
func (po *Po) SubstitueMacrosOnce(s string) string {
serial := po.Serial
po.Serial++
m := MatchMacroCall.FindStringSubmatchIndex(s)
if m == nil {
return s
}
if len(m) != 4 {
po.Fatalf("bad len from MatchMacroCall.FindStringSubmatchIndex")
}
front := s[:m[0]]
name := s[m[2]:m[3]]
rest := s[m[1]:]
if MatchOneQuote.FindStringSubmatch(front) != nil {
// Grand hack. We must be in a string, so don't expand what looked like a macro.
return s
}
var argwords []string
for {
n := ParseArg(rest)
// TODO: this needs work (what about white space, trailing `,` ... )
if n == 0 && rest[0] == ')' {
rest = rest[n+1:]
break
}
word := rest[:n]
argwords = append(argwords, word)
delim := rest[n]
rest = rest[n+1:]
if delim == ')' {
break
}
}
macro, ok := po.Macros[name]
if !ok {
po.Fatalf("unknown macro: %q", name)
}
if len(argwords) != len(macro.Args) {
po.Fatalf("got %d args for macro %q, but wanted %d args", len(argwords), name, len(macro.Args))
}
subs := make(map[string]string)
for i, arg := range macro.Args {
subs[arg] = argwords[i]
}
var z string
if !macro.Inline || po.Inlining {
replacer := func(word string) string { return po.replaceFromMap(word, subs, serial) }
Fprintf(po.W, " /*macro:%s{*/ ", name)
for _, line := range macro.Body {
if len(line) > 0 {
l2 := MatchIdentifier.ReplaceAllStringFunc(line, replacer)
l3 := po.SubstitueMacros(l2)
if MatchBeginsWithIf.FindStringSubmatch(l3) != nil {
Fprint(po.W, " ;;; ")
}
if MatchEndsWithOpenCurly.FindStringSubmatch(l3) == nil {
Fprint(po.W, l3+"; ")
} else {
// Helps with the newline between `switch` and `case`.
Fprint(po.W, l3+" ")
}
}
}
Fprintf(po.W, " /*macro}*/ ")
z = MatchIdentifier.ReplaceAllStringFunc(macro.Result, replacer)
} else {
z = Sprintf("/*noinline:*/%s(%s)", name, strings.Join(argwords, ", "))
}
return front + z + rest
}
func (po *Po) calculateIsEnabled() bool {
for _, e := range po.Stack {
if !e {
return false
}
}
return true
}
func Tidy(t string) string {
r := bytes.NewBufferString(t)
var s scanner.Scanner
s.Mode = scanner.GoTokens
s.Whitespace = scanner.GoWhitespace
s.Init(r)
var w bytes.Buffer
for {
r := s.Peek()
if r == scanner.EOF {
break
}
if r == ' ' || r == '\t' || r == '\n' || r == '\r' {
w.WriteRune(r)
s.Next()
continue
}
token := s.Scan()
if token == scanner.EOF {
break
}
if token < 0 {
w.WriteString(" ")
}
w.WriteString(s.TokenText())
if token < 0 {
w.WriteString(" ")
}
}
return w.String()
}
func (po *Po) DoLine(i int) int {
s := po.Lines[i]
lineNum := i + 1
mplusprego := MatchPlusBuildPrego.FindStringSubmatch(s)
if mplusprego != nil {
Fprintf(po.W, "//\n")
return i + 1
}
mplus := MatchPlusBuild.FindStringSubmatch(s)
if mplus != nil {
// Delete all "prego" from the +build line.
Fprintf(po.W, "// +build %s\n", strings.Replace(mplus[1], "prego", "", -1))
return i + 1
}
// First process cond (//#if & //#endif).
m := MatchDirective.FindStringSubmatch(s)
if m != nil {
switch m[1] {
case "if":
pred := false
for _, term := range strings.Split(m[2], "||") {
term = strings.Trim(term, " \t")
if MatchIdentifier.FindString(term) != term {
po.Fatalf("Line %d: not an identifier: %q", lineNum, term)
}
p, _ := po.Switches[term]
if p {
pred = true
}
}
po.Stack = append(po.Stack, pred)
case "endif":
n := len(po.Stack)
if n < 2 {
po.Fatalf("Line %d: Unmatched #endif", lineNum)
}
po.Stack = po.Stack[:n-1]
default:
po.Warningf("Line %d: Unknown control: %q", lineNum, m[1])
Fprintf(po.W, s+"\n")
return i + 1
}
// The directive becomes a blank line below.
s = ""
po.Enabled = po.calculateIsEnabled()
}
// Treat as a blank line, if not Enabled.
if !po.Enabled {
s = ""
}
// Next process macro definitions.
mm := MatchMacroDef.FindStringSubmatch(s)
if mm != nil {
inline := mm[1] == "inline" // inline or macro
name := mm[2]
arglist := mm[3]
retType := mm[4]
var argwords []string
for _, argword := range strings.Split(arglist, ",") {
a := strings.Trim(argword, " \t")
if len(a) == 0 {
continue
}
mfa := MatchFormalArg.FindStringSubmatch(a)
if mfa == nil {
po.Fatalf("MatchFormalArg fails on %q", a)
}
argwords = append(argwords, mfa[1])
}
if inline && !po.Inlining {
Fprintf(po.W, "func %s ( %s ) %s {\n", name, arglist, retType)
} else {
Fprintln(po.W, "")
}
var body []string
var result string
for {
i++
lineNum++
b := po.Lines[i]
if inline && !po.Inlining {
Fprintln(po.W, po.SubstitueMacros(b))
} else {
Fprintln(po.W, "")
}
mr := MatchMacroReturn.FindStringSubmatch(b)
if mr == nil {
// Just a body line.
body = append(body, b)
} else {
// It's the return line.
result = mr[1]
break
}
}
// Read one more line, which must close the macro.
i++
lineNum++
b := po.Lines[i]
if MatchMacroFinal.FindString(b) == "" {
panic("Expected final CloseBrace alone on a line after macro return line")
}
if inline && !po.Inlining {
Fprintln(po.W, "}")
} else {
Fprintln(po.W, "")
}
if _, ok := po.Macros[name]; ok {
panic("macro already defined: " + name)
}
po.Macros[name] = &Macro{
Inline: inline,
Args: argwords,
Body: body,
Result: result,
RetType: retType,
}
} else {
Fprintln(po.W, po.SubstitueMacros(Tidy(s)))
}
return i + 1
}
func (po *Po) Slurp(r io.Reader, w io.Writer) {
bs := bufio.NewScanner(r)
bs.Buffer(make([]byte, 100000), 100000000)
var lines []string
for bs.Scan() {
lines = append(lines, bs.Text())
}
if err := bs.Err(); err != nil {
panic(err)
}
po.W = w
po.Lines = lines
po.I = 0
for po.I < len(lines) {
po.I = po.DoLine(po.I)
}
}