-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
204 lines (185 loc) · 5.01 KB
/
Copy pathmain.go
File metadata and controls
204 lines (185 loc) · 5.01 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
194
195
196
197
198
199
200
201
202
203
204
package main
import (
"bytes"
"flag"
"fmt"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"strings"
"time"
"unicode/utf8"
"github.com/benhoyt/goawk/interp"
"github.com/benhoyt/goawk/lexer"
"github.com/benhoyt/goawk/parser"
)
const version = "1.0"
func main() {
// Main AWK arguments
var progFiles multiString
flag.Var(&progFiles, "f", "load AWK source from `progfile` (multiple allowed)")
fieldSep := flag.String("F", " ", "field `separator`")
var vars multiString
flag.Var(&vars, "v", "name=value variable `assignment` (multiple allowed)")
showVersion := flag.Bool("version", false, "show GoAWK version and exit")
// Debugging and profiling arguments
debug := flag.Bool("d", false, "debug mode (print parsed AST to stderr)")
debugTypes := flag.Bool("dt", false, "show variable types debug info")
cpuprofile := flag.String("cpuprofile", "", "write CPU profile to `file`")
memprofile := flag.String("memprofile", "", "write memory profile to `file`")
flag.Parse()
args := flag.Args()
if *showVersion {
fmt.Printf("TroutAWK %s\n", version)
return
}
var src []byte
if len(progFiles) > 0 {
// Read source: the concatenation of all source files specified
buf := &bytes.Buffer{}
for _, progFile := range progFiles {
if progFile == "-" {
_, err := buf.ReadFrom(os.Stdin)
if err != nil {
errorExit("%s", err)
}
} else {
f, err := os.Open(progFile)
if err != nil {
errorExit("%s", err)
}
_, err = buf.ReadFrom(f)
if err != nil {
f.Close()
errorExit("%s", err)
}
f.Close()
}
// Append newline to file in case it doesn't end with one
buf.WriteByte('\n')
}
src = buf.Bytes()
} else {
if len(args) < 1 {
errorExit("usage: tawk [-F fs] [-v var=value] [-f progfile | 'prog'] [file ...]")
}
src = []byte(args[0])
args = args[1:]
}
// Parse source code and setup interpreter
parserConfig := &parser.ParserConfig{
DebugTypes: *debugTypes,
DebugWriter: os.Stderr,
Funcs: map[string]interface{}{
"sum": func(args ...float64) float64 {
sum := 0.0
for _, a := range args {
sum += a
}
return sum
},
"repeat": strings.Repeat,
"isodate": func(arg int64) string { return time.UnixMilli(arg).Format(time.RFC3339) },
},
}
prog, err := parser.ParseProgram(src, parserConfig)
if err != nil {
errMsg := fmt.Sprintf("%s", err)
if err, ok := err.(*parser.ParseError); ok {
showSourceLine(src, err.Position, len(errMsg))
}
errorExit("%s", errMsg)
}
if *debug {
fmt.Fprintln(os.Stderr, prog)
}
config := &interp.Config{
Argv0: filepath.Base(os.Args[0]),
Args: args,
Vars: []string{"FS", *fieldSep},
Funcs: map[string]interface{}{
"sum": func(args ...float64) float64 {
sum := 0.0
for _, a := range args {
sum += a
}
return sum
},
"repeat": strings.Repeat,
"isodate": func(arg int64) string { return time.UnixMilli(arg).Format(time.RFC3339) },
},
}
for _, v := range vars {
parts := strings.SplitN(v, "=", 2)
if len(parts) != 2 {
errorExit("-v flag must be in format name=value")
}
config.Vars = append(config.Vars, parts[0], parts[1])
}
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
errorExit("could not create CPU profile: %v", err)
}
if err := pprof.StartCPUProfile(f); err != nil {
errorExit("could not start CPU profile: %v", err)
}
}
status, err := interp.ExecProgram(prog, config)
if err != nil {
errorExit("%s", err)
}
if *cpuprofile != "" {
pprof.StopCPUProfile()
}
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
errorExit("could not create memory profile: %v", err)
}
runtime.GC() // get up-to-date statistics
if err := pprof.WriteHeapProfile(f); err != nil {
errorExit("could not write memory profile: %v", err)
}
f.Close()
}
os.Exit(status)
}
// For parse errors, show source line and position of error, eg:
//
// -----------------------------------------------------
// BEGIN { x*; }
//
// ^
//
// -----------------------------------------------------
// parse error at 1:11: expected expression instead of ;
func showSourceLine(src []byte, pos lexer.Position, dividerLen int) {
divider := strings.Repeat("-", dividerLen)
if divider != "" {
fmt.Fprintln(os.Stderr, divider)
}
lines := bytes.Split(src, []byte{'\n'})
srcLine := string(lines[pos.Line-1])
numTabs := strings.Count(srcLine[:pos.Column-1], "\t")
runeColumn := utf8.RuneCountInString(srcLine[:pos.Column-1])
fmt.Fprintln(os.Stderr, strings.Replace(srcLine, "\t", " ", -1))
fmt.Fprintln(os.Stderr, strings.Repeat(" ", runeColumn)+strings.Repeat(" ", numTabs)+"^")
if divider != "" {
fmt.Fprintln(os.Stderr, divider)
}
}
func errorExit(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format+"\n", args...)
os.Exit(1)
}
// Helper type for flag parsing to allow multiple -f and -v arguments
type multiString []string
func (m *multiString) String() string {
return fmt.Sprintf("%v", []string(*m))
}
func (m *multiString) Set(value string) error {
*m = append(*m, value)
return nil
}