diff options
Diffstat (limited to 'src/pkg/testing')
-rw-r--r-- | src/pkg/testing/benchmark.go | 88 | ||||
-rw-r--r-- | src/pkg/testing/iotest/logger.go | 22 | ||||
-rw-r--r-- | src/pkg/testing/iotest/reader.go | 34 | ||||
-rw-r--r-- | src/pkg/testing/iotest/writer.go | 16 | ||||
-rw-r--r-- | src/pkg/testing/quick/quick.go | 188 | ||||
-rw-r--r-- | src/pkg/testing/quick/quick_test.go | 114 | ||||
-rw-r--r-- | src/pkg/testing/regexp.go | 680 | ||||
-rw-r--r-- | src/pkg/testing/regexp_test.go | 122 | ||||
-rw-r--r-- | src/pkg/testing/script/script.go | 190 | ||||
-rw-r--r-- | src/pkg/testing/script/script_test.go | 42 | ||||
-rw-r--r-- | src/pkg/testing/testing.go | 94 |
11 files changed, 795 insertions, 795 deletions
diff --git a/src/pkg/testing/benchmark.go b/src/pkg/testing/benchmark.go index b552a1320..6d95c90df 100644 --- a/src/pkg/testing/benchmark.go +++ b/src/pkg/testing/benchmark.go @@ -5,10 +5,10 @@ package testing import ( - "flag"; - "fmt"; - "os"; - "time"; + "flag" + "fmt" + "os" + "time" ) var matchBenchmarks = flag.String("benchmarks", "", "regular expression to select benchmarks to run") @@ -16,24 +16,24 @@ var matchBenchmarks = flag.String("benchmarks", "", "regular expression to selec // An internal type but exported because it is cross-package; part of the implementation // of gotest. type Benchmark struct { - Name string; - F func(b *B); + Name string + F func(b *B) } // B is a type passed to Benchmark functions to manage benchmark // timing and to specify the number of iterations to run. type B struct { - N int; - benchmark Benchmark; - ns int64; - bytes int64; - start int64; + N int + benchmark Benchmark + ns int64 + bytes int64 + start int64 } // StartTimer starts timing a test. This function is called automatically // before a benchmark starts, but it can also used to resume timing after // a call to StopTimer. -func (b *B) StartTimer() { b.start = time.Nanoseconds() } +func (b *B) StartTimer() { b.start = time.Nanoseconds() } // StopTimer stops timing a test. This can be used to pause the timer // while performing complex initialization that you don't @@ -42,68 +42,68 @@ func (b *B) StopTimer() { if b.start > 0 { b.ns += time.Nanoseconds() - b.start } - b.start = 0; + b.start = 0 } // ResetTimer stops the timer and sets the elapsed benchmark time to zero. func (b *B) ResetTimer() { - b.start = 0; - b.ns = 0; + b.start = 0 + b.ns = 0 } // SetBytes records the number of bytes processed in a single operation. // If this is called, the benchmark will report ns/op and MB/s. -func (b *B) SetBytes(n int64) { b.bytes = n } +func (b *B) SetBytes(n int64) { b.bytes = n } func (b *B) nsPerOp() int64 { if b.N <= 0 { return 0 } - return b.ns / int64(b.N); + return b.ns / int64(b.N) } // runN runs a single benchmark for the specified number of iterations. func (b *B) runN(n int) { - b.N = n; - b.ResetTimer(); - b.StartTimer(); - b.benchmark.F(b); - b.StopTimer(); + b.N = n + b.ResetTimer() + b.StartTimer() + b.benchmark.F(b) + b.StopTimer() } func min(x, y int) int { if x > y { return y } - return x; + return x } // roundDown10 rounds a number down to the nearest power of 10. func roundDown10(n int) int { - var tens = 0; + var tens = 0 // tens = floor(log_10(n)) for n > 10 { - n = n / 10; - tens++; + n = n / 10 + tens++ } // result = 10^tens - result := 1; + result := 1 for i := 0; i < tens; i++ { result *= 10 } - return result; + return result } // roundUp rounds x up to a number of the form [1eX, 2eX, 5eX]. func roundUp(n int) int { - base := roundDown10(n); + base := roundDown10(n) if n < (2 * base) { return 2 * base } if n < (5 * base) { return 5 * base } - return 10 * base; + return 10 * base } // run times the benchmark function. It gradually increases the number @@ -112,11 +112,11 @@ func roundUp(n int) int { // testing.BenchmarkHello 100000 19 ns/op func (b *B) run() { // Run the benchmark for a single iteration in case it's expensive. - n := 1; - b.runN(n); + n := 1 + b.runN(n) // Run the benchmark for at least a second. for b.ns < 1e9 && n < 1e9 { - last := n; + last := n // Predict iterations/sec. if b.nsPerOp() == 0 { n = 1e9 @@ -125,17 +125,17 @@ func (b *B) run() { } // Run more iterations than we think we'll need for a second (1.5x). // Don't grow too fast in case we had timing errors previously. - n = min(int(1.5*float(n)), 100*last); + n = min(int(1.5*float(n)), 100*last) // Round up to something easy to read. - n = roundUp(n); - b.runN(n); + n = roundUp(n) + b.runN(n) } - ns := b.nsPerOp(); - mb := ""; + ns := b.nsPerOp() + mb := "" if ns > 0 && b.bytes > 0 { mb = fmt.Sprintf("\t%7.2f MB/s", (float64(b.bytes)/1e6)/(float64(ns)/1e9)) } - fmt.Printf("%s\t%8d\t%10d ns/op%s\n", b.benchmark.Name, b.N, b.nsPerOp(), mb); + fmt.Printf("%s\t%8d\t%10d ns/op%s\n", b.benchmark.Name, b.N, b.nsPerOp(), mb) } // An internal function but exported because it is cross-package; part of the implementation @@ -145,16 +145,16 @@ func RunBenchmarks(benchmarks []Benchmark) { if len(*matchBenchmarks) == 0 { return } - re, err := CompileRegexp(*matchBenchmarks); + re, err := CompileRegexp(*matchBenchmarks) if err != "" { - println("invalid regexp for -benchmarks:", err); - os.Exit(1); + println("invalid regexp for -benchmarks:", err) + os.Exit(1) } for _, Benchmark := range benchmarks { if !re.MatchString(Benchmark.Name) { continue } - b := &B{benchmark: Benchmark}; - b.run(); + b := &B{benchmark: Benchmark} + b.run() } } diff --git a/src/pkg/testing/iotest/logger.go b/src/pkg/testing/iotest/logger.go index 86812d7e6..5e511bdf6 100644 --- a/src/pkg/testing/iotest/logger.go +++ b/src/pkg/testing/iotest/logger.go @@ -5,24 +5,24 @@ package iotest import ( - "io"; - "log"; - "os"; + "io" + "log" + "os" ) type writeLogger struct { - prefix string; - w io.Writer; + prefix string + w io.Writer } func (l *writeLogger) Write(p []byte) (n int, err os.Error) { - n, err = l.w.Write(p); + n, err = l.w.Write(p) if err != nil { log.Stdoutf("%s %x: %v", l.prefix, p[0:n], err) } else { log.Stdoutf("%s %x", l.prefix, p[0:n]) } - return; + return } // NewWriteLogger returns a writer that behaves like w except @@ -33,18 +33,18 @@ func NewWriteLogger(prefix string, w io.Writer) io.Writer { } type readLogger struct { - prefix string; - r io.Reader; + prefix string + r io.Reader } func (l *readLogger) Read(p []byte) (n int, err os.Error) { - n, err = l.r.Read(p); + n, err = l.r.Read(p) if err != nil { log.Stdoutf("%s %x: %v", l.prefix, p[0:n], err) } else { log.Stdoutf("%s %x", l.prefix, p[0:n]) } - return; + return } // NewReadLogger returns a reader that behaves like r except diff --git a/src/pkg/testing/iotest/reader.go b/src/pkg/testing/iotest/reader.go index 0a1a3f6b3..647520a09 100644 --- a/src/pkg/testing/iotest/reader.go +++ b/src/pkg/testing/iotest/reader.go @@ -7,31 +7,31 @@ package iotest import ( - "io"; - "os"; + "io" + "os" ) // OneByteReader returns a Reader that implements // each non-empty Read by reading one byte from r. -func OneByteReader(r io.Reader) io.Reader { return &oneByteReader{r} } +func OneByteReader(r io.Reader) io.Reader { return &oneByteReader{r} } type oneByteReader struct { - r io.Reader; + r io.Reader } func (r *oneByteReader) Read(p []byte) (int, os.Error) { if len(p) == 0 { return 0, nil } - return r.r.Read(p[0:1]); + return r.r.Read(p[0:1]) } // HalfReader returns a Reader that implements Read // by reading half as many requested bytes from r. -func HalfReader(r io.Reader) io.Reader { return &halfReader{r} } +func HalfReader(r io.Reader) io.Reader { return &halfReader{r} } type halfReader struct { - r io.Reader; + r io.Reader } func (r *halfReader) Read(p []byte) (int, os.Error) { @@ -42,12 +42,12 @@ func (r *halfReader) Read(p []byte) (int, os.Error) { // DataErrReader returns a Reader that returns the final // error with the last data read, instead of by itself with // zero bytes of data. -func DataErrReader(r io.Reader) io.Reader { return &dataErrReader{r, nil, make([]byte, 1024)} } +func DataErrReader(r io.Reader) io.Reader { return &dataErrReader{r, nil, make([]byte, 1024)} } type dataErrReader struct { - r io.Reader; - unread []byte; - data []byte; + r io.Reader + unread []byte + data []byte } func (r *dataErrReader) Read(p []byte) (n int, err os.Error) { @@ -55,15 +55,15 @@ func (r *dataErrReader) Read(p []byte) (n int, err os.Error) { // one to get data and a second to look for an error. for { if len(r.unread) == 0 { - n1, err1 := r.r.Read(r.data); - r.unread = r.data[0:n1]; - err = err1; + n1, err1 := r.r.Read(r.data) + r.unread = r.data[0:n1] + err = err1 } if n > 0 { break } - n = copy(p, r.unread); - r.unread = r.unread[n:]; + n = copy(p, r.unread) + r.unread = r.unread[n:] } - return; + return } diff --git a/src/pkg/testing/iotest/writer.go b/src/pkg/testing/iotest/writer.go index 54468a6fe..71f504ce2 100644 --- a/src/pkg/testing/iotest/writer.go +++ b/src/pkg/testing/iotest/writer.go @@ -5,8 +5,8 @@ package iotest import ( - "io"; - "os"; + "io" + "os" ) // TruncateWriter returns a Writer that writes to w @@ -16,8 +16,8 @@ func TruncateWriter(w io.Writer, n int64) io.Writer { } type truncateWriter struct { - w io.Writer; - n int64; + w io.Writer + n int64 } func (t *truncateWriter) Write(p []byte) (n int, err os.Error) { @@ -25,14 +25,14 @@ func (t *truncateWriter) Write(p []byte) (n int, err os.Error) { return len(p), nil } // real write - n = len(p); + n = len(p) if int64(n) > t.n { n = int(t.n) } - n, err = t.w.Write(p[0:n]); - t.n -= int64(n); + n, err = t.w.Write(p[0:n]) + t.n -= int64(n) if err == nil { n = len(p) } - return; + return } diff --git a/src/pkg/testing/quick/quick.go b/src/pkg/testing/quick/quick.go index 8fe895ee0..ae5cff6e2 100644 --- a/src/pkg/testing/quick/quick.go +++ b/src/pkg/testing/quick/quick.go @@ -6,13 +6,13 @@ package quick import ( - "flag"; - "fmt"; - "math"; - "os"; - "rand"; - "reflect"; - "strings"; + "flag" + "fmt" + "math" + "os" + "rand" + "reflect" + "strings" ) var defaultMaxCount *int = flag.Int("quickchecks", 100, "The default number of iterations for each check") @@ -21,29 +21,29 @@ var defaultMaxCount *int = flag.Int("quickchecks", 100, "The default number of i type Generator interface { // Generate returns a random instance of the type on which it is a // method using the size as a size hint. - Generate(rand *rand.Rand, size int) reflect.Value; + Generate(rand *rand.Rand, size int) reflect.Value } // randFloat32 generates a random float taking the full range of a float32. func randFloat32(rand *rand.Rand) float32 { - f := rand.Float64() * math.MaxFloat32; + f := rand.Float64() * math.MaxFloat32 if rand.Int()&1 == 1 { f = -f } - return float32(f); + return float32(f) } // randFloat64 generates a random float taking the full range of a float64. func randFloat64(rand *rand.Rand) float64 { - f := rand.Float64(); + f := rand.Float64() if rand.Int()&1 == 1 { f = -f } - return f; + return f } // randInt64 returns a random integer taking half the range of an int64. -func randInt64(rand *rand.Rand) int64 { return rand.Int63() - 1<<62 } +func randInt64(rand *rand.Rand) int64 { return rand.Int63() - 1<<62 } // complexSize is the maximum length of arbitrary values that contain other // values. @@ -81,53 +81,53 @@ func Value(t reflect.Type, rand *rand.Rand) (value reflect.Value, ok bool) { case *reflect.IntType: return reflect.NewValue(int(randInt64(rand))), true case *reflect.MapType: - numElems := rand.Intn(complexSize); - m := reflect.MakeMap(concrete); + numElems := rand.Intn(complexSize) + m := reflect.MakeMap(concrete) for i := 0; i < numElems; i++ { - key, ok1 := Value(concrete.Key(), rand); - value, ok2 := Value(concrete.Elem(), rand); + key, ok1 := Value(concrete.Key(), rand) + value, ok2 := Value(concrete.Elem(), rand) if !ok1 || !ok2 { return nil, false } - m.SetElem(key, value); + m.SetElem(key, value) } - return m, true; + return m, true case *reflect.PtrType: - v, ok := Value(concrete.Elem(), rand); + v, ok := Value(concrete.Elem(), rand) if !ok { return nil, false } - p := reflect.MakeZero(concrete); - p.(*reflect.PtrValue).PointTo(v); - return p, true; + p := reflect.MakeZero(concrete) + p.(*reflect.PtrValue).PointTo(v) + return p, true case *reflect.SliceType: - numElems := rand.Intn(complexSize); - s := reflect.MakeSlice(concrete, numElems, numElems); + numElems := rand.Intn(complexSize) + s := reflect.MakeSlice(concrete, numElems, numElems) for i := 0; i < numElems; i++ { - v, ok := Value(concrete.Elem(), rand); + v, ok := Value(concrete.Elem(), rand) if !ok { return nil, false } - s.Elem(i).SetValue(v); + s.Elem(i).SetValue(v) } - return s, true; + return s, true case *reflect.StringType: - numChars := rand.Intn(complexSize); - codePoints := make([]int, numChars); + numChars := rand.Intn(complexSize) + codePoints := make([]int, numChars) for i := 0; i < numChars; i++ { codePoints[i] = rand.Intn(0x10ffff) } - return reflect.NewValue(string(codePoints)), true; + return reflect.NewValue(string(codePoints)), true case *reflect.StructType: - s := reflect.MakeZero(t).(*reflect.StructValue); + s := reflect.MakeZero(t).(*reflect.StructValue) for i := 0; i < s.NumField(); i++ { - v, ok := Value(concrete.Field(i).Type, rand); + v, ok := Value(concrete.Field(i).Type, rand) if !ok { return nil, false } - s.Field(i).SetValue(v); + s.Field(i).SetValue(v) } - return s, true; + return s, true case *reflect.Uint16Type: return reflect.NewValue(uint16(randInt64(rand))), true case *reflect.Uint32Type: @@ -144,24 +144,24 @@ func Value(t reflect.Type, rand *rand.Rand) (value reflect.Value, ok bool) { return nil, false } - return; + return } // A Config structure contains options for running a test. type Config struct { // MaxCount sets the maximum number of iterations. If zero, // MaxCountScale is used. - MaxCount int; + MaxCount int // MaxCountScale is a non-negative scale factor applied to the default // maximum. If zero, the default is unchanged. - MaxCountScale float; + MaxCountScale float // If non-nil, rand is a source of random numbers. Otherwise a default // pseudo-random source will be used. - Rand *rand.Rand; + Rand *rand.Rand // If non-nil, Values is a function which generates a slice of arbitrary // Values that are congruent with the arguments to the function being // tested. Otherwise, Values is used to generate the values. - Values func([]reflect.Value, *rand.Rand); + Values func([]reflect.Value, *rand.Rand) } var defaultConfig Config @@ -171,13 +171,13 @@ func (c *Config) getRand() *rand.Rand { if c.Rand == nil { return rand.New(rand.NewSource(0)) } - return c.Rand; + return c.Rand } // getMaxCount returns the maximum number of iterations to run for a given // Config. func (c *Config) getMaxCount() (maxCount int) { - maxCount = c.MaxCount; + maxCount = c.MaxCount if maxCount == 0 { if c.MaxCountScale != 0 { maxCount = int(c.MaxCountScale * float(*defaultMaxCount)) @@ -186,19 +186,19 @@ func (c *Config) getMaxCount() (maxCount int) { } } - return; + return } // A SetupError is the result of an error in the way that check is being // used, independent of the functions being tested. type SetupError string -func (s SetupError) String() string { return string(s) } +func (s SetupError) String() string { return string(s) } // A CheckError is the result of Check finding an error. type CheckError struct { - Count int; - In []interface{}; + Count int + In []interface{} } func (s *CheckError) String() string { @@ -207,9 +207,9 @@ func (s *CheckError) String() string { // A CheckEqualError is the result CheckEqual finding an error. type CheckEqualError struct { - CheckError; - Out1 []interface{}; - Out2 []interface{}; + CheckError + Out1 []interface{} + Out2 []interface{} } func (s *CheckEqualError) String() string { @@ -236,38 +236,38 @@ func Check(function interface{}, config *Config) (err os.Error) { config = &defaultConfig } - f, fType, ok := functionAndType(function); + f, fType, ok := functionAndType(function) if !ok { - err = SetupError("argument is not a function"); - return; + err = SetupError("argument is not a function") + return } if fType.NumOut() != 1 { - err = SetupError("function returns more than one value."); - return; + err = SetupError("function returns more than one value.") + return } if _, ok := fType.Out(0).(*reflect.BoolType); !ok { - err = SetupError("function does not return a bool"); - return; + err = SetupError("function does not return a bool") + return } - arguments := make([]reflect.Value, fType.NumIn()); - rand := config.getRand(); - maxCount := config.getMaxCount(); + arguments := make([]reflect.Value, fType.NumIn()) + rand := config.getRand() + maxCount := config.getMaxCount() for i := 0; i < maxCount; i++ { - err = arbitraryValues(arguments, fType, config, rand); + err = arbitraryValues(arguments, fType, config, rand) if err != nil { return } if !f.Call(arguments)[0].(*reflect.BoolValue).Get() { - err = &CheckError{i + 1, toInterfaces(arguments)}; - return; + err = &CheckError{i + 1, toInterfaces(arguments)} + return } } - return; + return } // CheckEqual looks for an input on which f and g return different results. @@ -279,85 +279,85 @@ func CheckEqual(f, g interface{}, config *Config) (err os.Error) { config = &defaultConfig } - x, xType, ok := functionAndType(f); + x, xType, ok := functionAndType(f) if !ok { - err = SetupError("f is not a function"); - return; + err = SetupError("f is not a function") + return } - y, yType, ok := functionAndType(g); + y, yType, ok := functionAndType(g) if !ok { - err = SetupError("g is not a function"); - return; + err = SetupError("g is not a function") + return } if xType != yType { - err = SetupError("functions have different types"); - return; + err = SetupError("functions have different types") + return } - arguments := make([]reflect.Value, xType.NumIn()); - rand := config.getRand(); - maxCount := config.getMaxCount(); + arguments := make([]reflect.Value, xType.NumIn()) + rand := config.getRand() + maxCount := config.getMaxCount() for i := 0; i < maxCount; i++ { - err = arbitraryValues(arguments, xType, config, rand); + err = arbitraryValues(arguments, xType, config, rand) if err != nil { return } - xOut := toInterfaces(x.Call(arguments)); - yOut := toInterfaces(y.Call(arguments)); + xOut := toInterfaces(x.Call(arguments)) + yOut := toInterfaces(y.Call(arguments)) if !reflect.DeepEqual(xOut, yOut) { - err = &CheckEqualError{CheckError{i + 1, toInterfaces(arguments)}, xOut, yOut}; - return; + err = &CheckEqualError{CheckError{i + 1, toInterfaces(arguments)}, xOut, yOut} + return } } - return; + return } // arbitraryValues writes Values to args such that args contains Values // suitable for calling f. func arbitraryValues(args []reflect.Value, f *reflect.FuncType, config *Config, rand *rand.Rand) (err os.Error) { if config.Values != nil { - config.Values(args, rand); - return; + config.Values(args, rand) + return } for j := 0; j < len(args); j++ { - var ok bool; - args[j], ok = Value(f.In(j), rand); + var ok bool + args[j], ok = Value(f.In(j), rand) if !ok { - err = SetupError(fmt.Sprintf("cannot create arbitrary value of type %s for argument %d", f.In(j), j)); - return; + err = SetupError(fmt.Sprintf("cannot create arbitrary value of type %s for argument %d", f.In(j), j)) + return } } - return; + return } func functionAndType(f interface{}) (v *reflect.FuncValue, t *reflect.FuncType, ok bool) { - v, ok = reflect.NewValue(f).(*reflect.FuncValue); + v, ok = reflect.NewValue(f).(*reflect.FuncValue) if !ok { return } - t = v.Type().(*reflect.FuncType); - return; + t = v.Type().(*reflect.FuncType) + return } func toInterfaces(values []reflect.Value) []interface{} { - ret := make([]interface{}, len(values)); + ret := make([]interface{}, len(values)) for i, v := range values { ret[i] = v.Interface() } - return ret; + return ret } func toString(interfaces []interface{}) string { - s := make([]string, len(interfaces)); + s := make([]string, len(interfaces)) for i, v := range interfaces { s[i] = fmt.Sprintf("%#v", v) } - return strings.Join(s, ", "); + return strings.Join(s, ", ") } diff --git a/src/pkg/testing/quick/quick_test.go b/src/pkg/testing/quick/quick_test.go index b4037ab55..c7bff962b 100644 --- a/src/pkg/testing/quick/quick_test.go +++ b/src/pkg/testing/quick/quick_test.go @@ -5,60 +5,60 @@ package quick import ( - "rand"; - "reflect"; - "testing"; - "os"; + "rand" + "reflect" + "testing" + "os" ) -func fBool(a bool) bool { return a } +func fBool(a bool) bool { return a } -func fFloat32(a float32) float32 { return a } +func fFloat32(a float32) float32 { return a } -func fFloat64(a float64) float64 { return a } +func fFloat64(a float64) float64 { return a } -func fFloat(a float) float { return a } +func fFloat(a float) float { return a } -func fInt16(a int16) int16 { return a } +func fInt16(a int16) int16 { return a } -func fInt32(a int32) int32 { return a } +func fInt32(a int32) int32 { return a } -func fInt64(a int64) int64 { return a } +func fInt64(a int64) int64 { return a } -func fInt8(a int8) int8 { return a } +func fInt8(a int8) int8 { return a } -func fInt(a int) int { return a } +func fInt(a int) int { return a } -func fUInt8(a uint8) uint8 { return a } +func fUInt8(a uint8) uint8 { return a } -func fMap(a map[int]int) map[int]int { return a } +func fMap(a map[int]int) map[int]int { return a } -func fSlice(a []byte) []byte { return a } +func fSlice(a []byte) []byte { return a } -func fString(a string) string { return a } +func fString(a string) string { return a } type TestStruct struct { - A int; - B string; + A int + B string } -func fStruct(a TestStruct) TestStruct { return a } +func fStruct(a TestStruct) TestStruct { return a } -func fUint16(a uint16) uint16 { return a } +func fUint16(a uint16) uint16 { return a } -func fUint32(a uint32) uint32 { return a } +func fUint32(a uint32) uint32 { return a } -func fUint64(a uint64) uint64 { return a } +func fUint64(a uint64) uint64 { return a } -func fUint8(a uint8) uint8 { return a } +func fUint8(a uint8) uint8 { return a } -func fUint(a uint) uint { return a } +func fUint(a uint) uint { return a } -func fUintptr(a uintptr) uintptr { return a } +func fUintptr(a uintptr) uintptr { return a } func fIntptr(a *int) *int { - b := *a; - return &b; + b := *a + return &b } func reportError(property string, err os.Error, t *testing.T) { @@ -68,49 +68,49 @@ func reportError(property string, err os.Error, t *testing.T) { } func TestCheckEqual(t *testing.T) { - reportError("fBool", CheckEqual(fBool, fBool, nil), t); - reportError("fFloat32", CheckEqual(fFloat32, fFloat32, nil), t); - reportError("fFloat64", CheckEqual(fFloat64, fFloat64, nil), t); - reportError("fFloat", CheckEqual(fFloat, fFloat, nil), t); - reportError("fInt16", CheckEqual(fInt16, fInt16, nil), t); - reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t); - reportError("fInt64", CheckEqual(fInt64, fInt64, nil), t); - reportError("fInt8", CheckEqual(fInt8, fInt8, nil), t); - reportError("fInt", CheckEqual(fInt, fInt, nil), t); - reportError("fUInt8", CheckEqual(fUInt8, fUInt8, nil), t); - reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t); - reportError("fMap", CheckEqual(fMap, fMap, nil), t); - reportError("fSlice", CheckEqual(fSlice, fSlice, nil), t); - reportError("fString", CheckEqual(fString, fString, nil), t); - reportError("fStruct", CheckEqual(fStruct, fStruct, nil), t); - reportError("fUint16", CheckEqual(fUint16, fUint16, nil), t); - reportError("fUint32", CheckEqual(fUint32, fUint32, nil), t); - reportError("fUint64", CheckEqual(fUint64, fUint64, nil), t); - reportError("fUint8", CheckEqual(fUint8, fUint8, nil), t); - reportError("fUint", CheckEqual(fUint, fUint, nil), t); - reportError("fUintptr", CheckEqual(fUintptr, fUintptr, nil), t); - reportError("fIntptr", CheckEqual(fIntptr, fIntptr, nil), t); + reportError("fBool", CheckEqual(fBool, fBool, nil), t) + reportError("fFloat32", CheckEqual(fFloat32, fFloat32, nil), t) + reportError("fFloat64", CheckEqual(fFloat64, fFloat64, nil), t) + reportError("fFloat", CheckEqual(fFloat, fFloat, nil), t) + reportError("fInt16", CheckEqual(fInt16, fInt16, nil), t) + reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t) + reportError("fInt64", CheckEqual(fInt64, fInt64, nil), t) + reportError("fInt8", CheckEqual(fInt8, fInt8, nil), t) + reportError("fInt", CheckEqual(fInt, fInt, nil), t) + reportError("fUInt8", CheckEqual(fUInt8, fUInt8, nil), t) + reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t) + reportError("fMap", CheckEqual(fMap, fMap, nil), t) + reportError("fSlice", CheckEqual(fSlice, fSlice, nil), t) + reportError("fString", CheckEqual(fString, fString, nil), t) + reportError("fStruct", CheckEqual(fStruct, fStruct, nil), t) + reportError("fUint16", CheckEqual(fUint16, fUint16, nil), t) + reportError("fUint32", CheckEqual(fUint32, fUint32, nil), t) + reportError("fUint64", CheckEqual(fUint64, fUint64, nil), t) + reportError("fUint8", CheckEqual(fUint8, fUint8, nil), t) + reportError("fUint", CheckEqual(fUint, fUint, nil), t) + reportError("fUintptr", CheckEqual(fUintptr, fUintptr, nil), t) + reportError("fIntptr", CheckEqual(fIntptr, fIntptr, nil), t) } // This tests that ArbitraryValue is working by checking that all the arbitrary // values of type MyStruct have x = 42. type myStruct struct { - x int; + x int } func (m myStruct) Generate(r *rand.Rand, _ int) reflect.Value { return reflect.NewValue(myStruct{x: 42}) } -func myStructProperty(in myStruct) bool { return in.x == 42 } +func myStructProperty(in myStruct) bool { return in.x == 42 } func TestCheckProperty(t *testing.T) { reportError("myStructProperty", Check(myStructProperty, nil), t) } func TestFailure(t *testing.T) { - f := func(x int) bool { return false }; - err := Check(f, nil); + f := func(x int) bool { return false } + err := Check(f, nil) if err == nil { t.Errorf("Check didn't return an error") } @@ -118,7 +118,7 @@ func TestFailure(t *testing.T) { t.Errorf("Error was not a CheckError: %s", err) } - err = CheckEqual(fUint, fUint32, nil); + err = CheckEqual(fUint, fUint32, nil) if err == nil { t.Errorf("#1 CheckEqual didn't return an error") } @@ -126,7 +126,7 @@ func TestFailure(t *testing.T) { t.Errorf("#1 Error was not a SetupError: %s", err) } - err = CheckEqual(func(x, y int) {}, func(x int) {}, nil); + err = CheckEqual(func(x, y int) {}, func(x int) {}, nil) if err == nil { t.Errorf("#2 CheckEqual didn't return an error") } @@ -134,7 +134,7 @@ func TestFailure(t *testing.T) { t.Errorf("#2 Error was not a SetupError: %s", err) } - err = CheckEqual(func(x int) int { return 0 }, func(x int) int32 { return 0 }, nil); + err = CheckEqual(func(x int) int { return 0 }, func(x int) int32 { return 0 }, nil) if err == nil { t.Errorf("#3 CheckEqual didn't return an error") } diff --git a/src/pkg/testing/regexp.go b/src/pkg/testing/regexp.go index 3100136cd..a21d14e6b 100644 --- a/src/pkg/testing/regexp.go +++ b/src/pkg/testing/regexp.go @@ -26,137 +26,137 @@ package testing import ( - "utf8"; + "utf8" ) var debug = false // Error codes returned by failures to parse an expression. var ( - ErrInternal = "internal error"; - ErrUnmatchedLpar = "unmatched ''"; - ErrUnmatchedRpar = "unmatched ''"; - ErrUnmatchedLbkt = "unmatched '['"; - ErrUnmatchedRbkt = "unmatched ']'"; - ErrBadRange = "bad range in character class"; - ErrExtraneousBackslash = "extraneous backslash"; - ErrBadClosure = "repeated closure **, ++, etc."; - ErrBareClosure = "closure applies to nothing"; - ErrBadBackslash = "illegal backslash escape"; + ErrInternal = "internal error" + ErrUnmatchedLpar = "unmatched ''" + ErrUnmatchedRpar = "unmatched ''" + ErrUnmatchedLbkt = "unmatched '['" + ErrUnmatchedRbkt = "unmatched ']'" + ErrBadRange = "bad range in character class" + ErrExtraneousBackslash = "extraneous backslash" + ErrBadClosure = "repeated closure **, ++, etc." + ErrBareClosure = "closure applies to nothing" + ErrBadBackslash = "illegal backslash escape" ) // An instruction executed by the NFA type instr interface { - kind() int; // the type of this instruction: _CHAR, _ANY, etc. - next() instr; // the instruction to execute after this one - setNext(i instr); - index() int; - setIndex(i int); - print(); + kind() int // the type of this instruction: _CHAR, _ANY, etc. + next() instr // the instruction to execute after this one + setNext(i instr) + index() int + setIndex(i int) + print() } // Fields and methods common to all instructions type common struct { - _next instr; - _index int; + _next instr + _index int } -func (c *common) next() instr { return c._next } -func (c *common) setNext(i instr) { c._next = i } -func (c *common) index() int { return c._index } -func (c *common) setIndex(i int) { c._index = i } +func (c *common) next() instr { return c._next } +func (c *common) setNext(i instr) { c._next = i } +func (c *common) index() int { return c._index } +func (c *common) setIndex(i int) { c._index = i } // The representation of a compiled regular expression. // The public interface is entirely through methods. type Regexp struct { - expr string; // the original expression - inst []instr; - start instr; - nbra int; // number of brackets in expression, for subexpressions + expr string // the original expression + inst []instr + start instr + nbra int // number of brackets in expression, for subexpressions } const ( - _START = iota; // beginning of program - _END; // end of program: success - _BOT; // '^' beginning of text - _EOT; // '$' end of text - _CHAR; // 'a' regular character - _CHARCLASS; // [a-z] character class - _ANY; // '.' any character including newline - _NOTNL; // [^\n] special case: any character but newline - _BRA; // '(' parenthesized expression - _EBRA; // ')'; end of '(' parenthesized expression - _ALT; // '|' alternation - _NOP; // do nothing; makes it easy to link without patching + _START = iota // beginning of program + _END // end of program: success + _BOT // '^' beginning of text + _EOT // '$' end of text + _CHAR // 'a' regular character + _CHARCLASS // [a-z] character class + _ANY // '.' any character including newline + _NOTNL // [^\n] special case: any character but newline + _BRA // '(' parenthesized expression + _EBRA // ')'; end of '(' parenthesized expression + _ALT // '|' alternation + _NOP // do nothing; makes it easy to link without patching ) // --- START start of program type _Start struct { - common; + common } -func (start *_Start) kind() int { return _START } -func (start *_Start) print() { print("start") } +func (start *_Start) kind() int { return _START } +func (start *_Start) print() { print("start") } // --- END end of program type _End struct { - common; + common } -func (end *_End) kind() int { return _END } -func (end *_End) print() { print("end") } +func (end *_End) kind() int { return _END } +func (end *_End) print() { print("end") } // --- BOT beginning of text type _Bot struct { - common; + common } -func (bot *_Bot) kind() int { return _BOT } -func (bot *_Bot) print() { print("bot") } +func (bot *_Bot) kind() int { return _BOT } +func (bot *_Bot) print() { print("bot") } // --- EOT end of text type _Eot struct { - common; + common } -func (eot *_Eot) kind() int { return _EOT } -func (eot *_Eot) print() { print("eot") } +func (eot *_Eot) kind() int { return _EOT } +func (eot *_Eot) print() { print("eot") } // --- CHAR a regular character type _Char struct { - common; - char int; + common + char int } -func (char *_Char) kind() int { return _CHAR } -func (char *_Char) print() { print("char ", string(char.char)) } +func (char *_Char) kind() int { return _CHAR } +func (char *_Char) print() { print("char ", string(char.char)) } func newChar(char int) *_Char { - c := new(_Char); - c.char = char; - return c; + c := new(_Char) + c.char = char + return c } // --- CHARCLASS [a-z] type _CharClass struct { - common; - char int; - negate bool; // is character class negated? ([^a-z]) + common + char int + negate bool // is character class negated? ([^a-z]) // stored pairwise: [a-z] is (a,z); x is (x,x): - ranges []int; + ranges []int } -func (cclass *_CharClass) kind() int { return _CHARCLASS } +func (cclass *_CharClass) kind() int { return _CHARCLASS } func (cclass *_CharClass) print() { - print("charclass"); + print("charclass") if cclass.negate { print(" (negated)") } for i := 0; i < len(cclass.ranges); i += 2 { - l := cclass.ranges[i]; - r := cclass.ranges[i+1]; + l := cclass.ranges[i] + r := cclass.ranges[i+1] if l == r { print(" [", string(l), "]") } else { @@ -167,215 +167,215 @@ func (cclass *_CharClass) print() { func (cclass *_CharClass) addRange(a, b int) { // range is a through b inclusive - n := len(cclass.ranges); + n := len(cclass.ranges) if n >= cap(cclass.ranges) { - nr := make([]int, n, 2*n); + nr := make([]int, n, 2*n) for i, j := range nr { nr[i] = j } - cclass.ranges = nr; + cclass.ranges = nr } - cclass.ranges = cclass.ranges[0 : n+2]; - cclass.ranges[n] = a; - n++; - cclass.ranges[n] = b; - n++; + cclass.ranges = cclass.ranges[0 : n+2] + cclass.ranges[n] = a + n++ + cclass.ranges[n] = b + n++ } func (cclass *_CharClass) matches(c int) bool { for i := 0; i < len(cclass.ranges); i = i + 2 { - min := cclass.ranges[i]; - max := cclass.ranges[i+1]; + min := cclass.ranges[i] + max := cclass.ranges[i+1] if min <= c && c <= max { return !cclass.negate } } - return cclass.negate; + return cclass.negate } func newCharClass() *_CharClass { - c := new(_CharClass); - c.ranges = make([]int, 0, 20); - return c; + c := new(_CharClass) + c.ranges = make([]int, 0, 20) + return c } // --- ANY any character type _Any struct { - common; + common } -func (any *_Any) kind() int { return _ANY } -func (any *_Any) print() { print("any") } +func (any *_Any) kind() int { return _ANY } +func (any *_Any) print() { print("any") } // --- NOTNL any character but newline type _NotNl struct { - common; + common } -func (notnl *_NotNl) kind() int { return _NOTNL } -func (notnl *_NotNl) print() { print("notnl") } +func (notnl *_NotNl) kind() int { return _NOTNL } +func (notnl *_NotNl) print() { print("notnl") } // --- BRA parenthesized expression type _Bra struct { - common; - n int; // subexpression number + common + n int // subexpression number } -func (bra *_Bra) kind() int { return _BRA } -func (bra *_Bra) print() { print("bra", bra.n) } +func (bra *_Bra) kind() int { return _BRA } +func (bra *_Bra) print() { print("bra", bra.n) } // --- EBRA end of parenthesized expression type _Ebra struct { - common; - n int; // subexpression number + common + n int // subexpression number } -func (ebra *_Ebra) kind() int { return _EBRA } -func (ebra *_Ebra) print() { print("ebra ", ebra.n) } +func (ebra *_Ebra) kind() int { return _EBRA } +func (ebra *_Ebra) print() { print("ebra ", ebra.n) } // --- ALT alternation type _Alt struct { - common; - left instr; // other branch + common + left instr // other branch } -func (alt *_Alt) kind() int { return _ALT } -func (alt *_Alt) print() { print("alt(", alt.left.index(), ")") } +func (alt *_Alt) kind() int { return _ALT } +func (alt *_Alt) print() { print("alt(", alt.left.index(), ")") } // --- NOP no operation type _Nop struct { - common; + common } -func (nop *_Nop) kind() int { return _NOP } -func (nop *_Nop) print() { print("nop") } +func (nop *_Nop) kind() int { return _NOP } +func (nop *_Nop) print() { print("nop") } func (re *Regexp) add(i instr) instr { - n := len(re.inst); - i.setIndex(len(re.inst)); + n := len(re.inst) + i.setIndex(len(re.inst)) if n >= cap(re.inst) { - ni := make([]instr, n, 2*n); + ni := make([]instr, n, 2*n) for i, j := range re.inst { ni[i] = j } - re.inst = ni; + re.inst = ni } - re.inst = re.inst[0 : n+1]; - re.inst[n] = i; - return i; + re.inst = re.inst[0 : n+1] + re.inst[n] = i + return i } type parser struct { - re *Regexp; - error string; - nlpar int; // number of unclosed lpars - pos int; - ch int; + re *Regexp + error string + nlpar int // number of unclosed lpars + pos int + ch int } const endOfFile = -1 -func (p *parser) c() int { return p.ch } +func (p *parser) c() int { return p.ch } func (p *parser) nextc() int { if p.pos >= len(p.re.expr) { p.ch = endOfFile } else { - c, w := utf8.DecodeRuneInString(p.re.expr[p.pos:]); - p.ch = c; - p.pos += w; + c, w := utf8.DecodeRuneInString(p.re.expr[p.pos:]) + p.ch = c + p.pos += w } - return p.ch; + return p.ch } func newParser(re *Regexp) *parser { - p := new(parser); - p.re = re; - p.nextc(); // load p.ch - return p; + p := new(parser) + p.re = re + p.nextc() // load p.ch + return p } func special(c int) bool { - s := `\.+*?()|[]^$`; + s := `\.+*?()|[]^$` for i := 0; i < len(s); i++ { if c == int(s[i]) { return true } } - return false; + return false } func specialcclass(c int) bool { - s := `\-[]`; + s := `\-[]` for i := 0; i < len(s); i++ { if c == int(s[i]) { return true } } - return false; + return false } func (p *parser) charClass() instr { - cc := newCharClass(); + cc := newCharClass() if p.c() == '^' { - cc.negate = true; - p.nextc(); + cc.negate = true + p.nextc() } - left := -1; + left := -1 for { switch c := p.c(); c { case ']', endOfFile: if left >= 0 { - p.error = ErrBadRange; - return nil; + p.error = ErrBadRange + return nil } // Is it [^\n]? if cc.negate && len(cc.ranges) == 2 && cc.ranges[0] == '\n' && cc.ranges[1] == '\n' { - nl := new(_NotNl); - p.re.add(nl); - return nl; + nl := new(_NotNl) + p.re.add(nl) + return nl } - p.re.add(cc); - return cc; - case '-': // do this before backslash processing - p.error = ErrBadRange; - return nil; + p.re.add(cc) + return cc + case '-': // do this before backslash processing + p.error = ErrBadRange + return nil case '\\': - c = p.nextc(); + c = p.nextc() switch { case c == endOfFile: - p.error = ErrExtraneousBackslash; - return nil; + p.error = ErrExtraneousBackslash + return nil case c == 'n': c = '\n' case specialcclass(c): // c is as delivered default: - p.error = ErrBadBackslash; - return nil; + p.error = ErrBadBackslash + return nil } - fallthrough; + fallthrough default: - p.nextc(); + p.nextc() switch { - case left < 0: // first of pair - if p.c() == '-' { // range - p.nextc(); - left = c; - } else { // single char + case left < 0: // first of pair + if p.c() == '-' { // range + p.nextc() + left = c + } else { // single char cc.addRange(c, c) } - case left <= c: // second of pair - cc.addRange(left, c); - left = -1; + case left <= c: // second of pair + cc.addRange(left, c) + left = -1 default: - p.error = ErrBadRange; - return nil; + p.error = ErrBadRange + return nil } } } - return nil; + return nil } func (p *parser) term() (start, end instr) { @@ -390,126 +390,126 @@ func (p *parser) term() (start, end instr) { case '|', endOfFile: return nil, nil case '*', '+': - p.error = ErrBareClosure; - return; + p.error = ErrBareClosure + return case ')': if p.nlpar == 0 { - p.error = ErrUnmatchedRpar; - return; + p.error = ErrUnmatchedRpar + return } - return nil, nil; + return nil, nil case ']': - p.error = ErrUnmatchedRbkt; - return; + p.error = ErrUnmatchedRbkt + return case '^': - p.nextc(); - start = p.re.add(new(_Bot)); - return start, start; + p.nextc() + start = p.re.add(new(_Bot)) + return start, start case '$': - p.nextc(); - start = p.re.add(new(_Eot)); - return start, start; + p.nextc() + start = p.re.add(new(_Eot)) + return start, start case '.': - p.nextc(); - start = p.re.add(new(_Any)); - return start, start; + p.nextc() + start = p.re.add(new(_Any)) + return start, start case '[': - p.nextc(); - start = p.charClass(); + p.nextc() + start = p.charClass() if p.error != "" { return } if p.c() != ']' { - p.error = ErrUnmatchedLbkt; - return; + p.error = ErrUnmatchedLbkt + return } - p.nextc(); - return start, start; + p.nextc() + return start, start case '(': - p.nextc(); - p.nlpar++; - p.re.nbra++; // increment first so first subexpr is \1 - nbra := p.re.nbra; - start, end = p.regexp(); + p.nextc() + p.nlpar++ + p.re.nbra++ // increment first so first subexpr is \1 + nbra := p.re.nbra + start, end = p.regexp() if p.c() != ')' { - p.error = ErrUnmatchedLpar; - return; + p.error = ErrUnmatchedLpar + return } - p.nlpar--; - p.nextc(); - bra := new(_Bra); - p.re.add(bra); - ebra := new(_Ebra); - p.re.add(ebra); - bra.n = nbra; - ebra.n = nbra; + p.nlpar-- + p.nextc() + bra := new(_Bra) + p.re.add(bra) + ebra := new(_Ebra) + p.re.add(ebra) + bra.n = nbra + ebra.n = nbra if start == nil { if end == nil { - p.error = ErrInternal; - return; + p.error = ErrInternal + return } - start = ebra; + start = ebra } else { end.setNext(ebra) } - bra.setNext(start); - return bra, ebra; + bra.setNext(start) + return bra, ebra case '\\': - c = p.nextc(); + c = p.nextc() switch { case c == endOfFile: - p.error = ErrExtraneousBackslash; - return; + p.error = ErrExtraneousBackslash + return case c == 'n': c = '\n' case special(c): // c is as delivered default: - p.error = ErrBadBackslash; - return; + p.error = ErrBadBackslash + return } - fallthrough; + fallthrough default: - p.nextc(); - start = newChar(c); - p.re.add(start); - return start, start; + p.nextc() + start = newChar(c) + p.re.add(start) + return start, start } - panic("unreachable"); + panic("unreachable") } func (p *parser) closure() (start, end instr) { - start, end = p.term(); + start, end = p.term() if start == nil || p.error != "" { return } switch p.c() { case '*': // (start,end)*: - alt := new(_Alt); - p.re.add(alt); - end.setNext(alt); // after end, do alt - alt.left = start; // alternate brach: return to start - start = alt; // alt becomes new (start, end) - end = alt; + alt := new(_Alt) + p.re.add(alt) + end.setNext(alt) // after end, do alt + alt.left = start // alternate brach: return to start + start = alt // alt becomes new (start, end) + end = alt case '+': // (start,end)+: - alt := new(_Alt); - p.re.add(alt); - end.setNext(alt); // after end, do alt - alt.left = start; // alternate brach: return to start - end = alt; // start is unchanged; end is alt + alt := new(_Alt) + p.re.add(alt) + end.setNext(alt) // after end, do alt + alt.left = start // alternate brach: return to start + end = alt // start is unchanged; end is alt case '?': // (start,end)?: - alt := new(_Alt); - p.re.add(alt); - nop := new(_Nop); - p.re.add(nop); - alt.left = start; // alternate branch is start - alt.setNext(nop); // follow on to nop - end.setNext(nop); // after end, go to nop - start = alt; // start is now alt - end = nop; // end is nop pointed to by both branches + alt := new(_Alt) + p.re.add(alt) + nop := new(_Nop) + p.re.add(nop) + alt.left = start // alternate branch is start + alt.setNext(nop) // follow on to nop + end.setNext(nop) // after end, go to nop + start = alt // start is now alt + end = nop // end is nop pointed to by both branches default: return } @@ -517,34 +517,34 @@ func (p *parser) closure() (start, end instr) { case '*', '+', '?': p.error = ErrBadClosure } - return; + return } func (p *parser) concatenation() (start, end instr) { for { - nstart, nend := p.closure(); + nstart, nend := p.closure() if p.error != "" { return } switch { - case nstart == nil: // end of this concatenation - if start == nil { // this is the empty string - nop := p.re.add(new(_Nop)); - return nop, nop; + case nstart == nil: // end of this concatenation + if start == nil { // this is the empty string + nop := p.re.add(new(_Nop)) + return nop, nop } - return; - case start == nil: // this is first element of concatenation + return + case start == nil: // this is first element of concatenation start, end = nstart, nend default: - end.setNext(nstart); - end = nend; + end.setNext(nstart) + end = nend } } - panic("unreachable"); + panic("unreachable") } func (p *parser) regexp() (start, end instr) { - start, end = p.concatenation(); + start, end = p.concatenation() if p.error != "" { return } @@ -553,145 +553,145 @@ func (p *parser) regexp() (start, end instr) { default: return case '|': - p.nextc(); - nstart, nend := p.concatenation(); + p.nextc() + nstart, nend := p.concatenation() if p.error != "" { return } - alt := new(_Alt); - p.re.add(alt); - alt.left = start; - alt.setNext(nstart); - nop := new(_Nop); - p.re.add(nop); - end.setNext(nop); - nend.setNext(nop); - start, end = alt, nop; + alt := new(_Alt) + p.re.add(alt) + alt.left = start + alt.setNext(nstart) + nop := new(_Nop) + p.re.add(nop) + end.setNext(nop) + nend.setNext(nop) + start, end = alt, nop } } - panic("unreachable"); + panic("unreachable") } func unNop(i instr) instr { for i.kind() == _NOP { i = i.next() } - return i; + return i } func (re *Regexp) eliminateNops() { for i := 0; i < len(re.inst); i++ { - inst := re.inst[i]; + inst := re.inst[i] if inst.kind() == _END { continue } - inst.setNext(unNop(inst.next())); + inst.setNext(unNop(inst.next())) if inst.kind() == _ALT { - alt := inst.(*_Alt); - alt.left = unNop(alt.left); + alt := inst.(*_Alt) + alt.left = unNop(alt.left) } } } func (re *Regexp) doParse() string { - p := newParser(re); - start := new(_Start); - re.add(start); - s, e := p.regexp(); + p := newParser(re) + start := new(_Start) + re.add(start) + s, e := p.regexp() if p.error != "" { return p.error } - start.setNext(s); - re.start = start; - e.setNext(re.add(new(_End))); - re.eliminateNops(); - return p.error; + start.setNext(s) + re.start = start + e.setNext(re.add(new(_End))) + re.eliminateNops() + return p.error } // CompileRegexp parses a regular expression and returns, if successful, a Regexp // object that can be used to match against text. func CompileRegexp(str string) (regexp *Regexp, error string) { - regexp = new(Regexp); - regexp.expr = str; - regexp.inst = make([]instr, 0, 20); - error = regexp.doParse(); - return; + regexp = new(Regexp) + regexp.expr = str + regexp.inst = make([]instr, 0, 20) + error = regexp.doParse() + return } // MustCompileRegexp is like CompileRegexp but panics if the expression cannot be parsed. // It simplifies safe initialization of global variables holding compiled regular // expressions. func MustCompile(str string) *Regexp { - regexp, error := CompileRegexp(str); + regexp, error := CompileRegexp(str) if error != "" { panicln(`regexp: compiling "`, str, `": `, error) } - return regexp; + return regexp } type state struct { - inst instr; // next instruction to execute - match []int; // pairs of bracketing submatches. 0th is start,end + inst instr // next instruction to execute + match []int // pairs of bracketing submatches. 0th is start,end } // Append new state to to-do list. Leftmost-longest wins so avoid // adding a state that's already active. func addState(s []state, inst instr, match []int) []state { - index := inst.index(); - l := len(s); - pos := match[0]; + index := inst.index() + l := len(s) + pos := match[0] // TODO: Once the state is a vector and we can do insert, have inputs always // go in order correctly and this "earlier" test is never necessary, for i := 0; i < l; i++ { - if s[i].inst.index() == index && // same instruction - s[i].match[0] < pos { // earlier match already going; lefmost wins + if s[i].inst.index() == index && // same instruction + s[i].match[0] < pos { // earlier match already going; lefmost wins return s } } if l == cap(s) { - s1 := make([]state, 2*l)[0:l]; + s1 := make([]state, 2*l)[0:l] for i := 0; i < l; i++ { s1[i] = s[i] } - s = s1; + s = s1 } - s = s[0 : l+1]; - s[l].inst = inst; - s[l].match = match; - return s; + s = s[0 : l+1] + s[l].inst = inst + s[l].match = match + return s } // Accepts either string or bytes - the logic is identical either way. // If bytes == nil, scan str. func (re *Regexp) doExecute(str string, bytes []byte, pos int) []int { - var s [2][]state; // TODO: use a vector when state values (not ptrs) can be vector elements - s[0] = make([]state, 10)[0:0]; - s[1] = make([]state, 10)[0:0]; - in, out := 0, 1; - var final state; - found := false; - end := len(str); + var s [2][]state // TODO: use a vector when state values (not ptrs) can be vector elements + s[0] = make([]state, 10)[0:0] + s[1] = make([]state, 10)[0:0] + in, out := 0, 1 + var final state + found := false + end := len(str) if bytes != nil { end = len(bytes) } for pos <= end { if !found { // prime the pump if we haven't seen a match yet - match := make([]int, 2*(re.nbra+1)); + match := make([]int, 2*(re.nbra+1)) for i := 0; i < len(match); i++ { - match[i] = -1 // no match seen; catches cases like "a(b)?c" on "ac" + match[i] = -1 // no match seen; catches cases like "a(b)?c" on "ac" } - match[0] = pos; - s[out] = addState(s[out], re.start.next(), match); + match[0] = pos + s[out] = addState(s[out], re.start.next(), match) } - in, out = out, in; // old out state is new in state - s[out] = s[out][0:0]; // clear out state + in, out = out, in // old out state is new in state + s[out] = s[out][0:0] // clear out state if len(s[in]) == 0 { // machine has completed break } - charwidth := 1; - c := endOfFile; + charwidth := 1 + c := endOfFile if pos < end { if bytes == nil { c, charwidth = utf8.DecodeRuneInString(str[pos:end]) @@ -700,7 +700,7 @@ func (re *Regexp) doExecute(str string, bytes []byte, pos int) []int { } } for i := 0; i < len(s[in]); i++ { - st := s[in][i]; + st := s[in][i] switch s[in][i].inst.kind() { case _BOT: if pos == 0 { @@ -727,38 +727,38 @@ func (re *Regexp) doExecute(str string, bytes []byte, pos int) []int { s[out] = addState(s[out], st.inst.next(), st.match) } case _BRA: - n := st.inst.(*_Bra).n; - st.match[2*n] = pos; - s[in] = addState(s[in], st.inst.next(), st.match); + n := st.inst.(*_Bra).n + st.match[2*n] = pos + s[in] = addState(s[in], st.inst.next(), st.match) case _EBRA: - n := st.inst.(*_Ebra).n; - st.match[2*n+1] = pos; - s[in] = addState(s[in], st.inst.next(), st.match); + n := st.inst.(*_Ebra).n + st.match[2*n+1] = pos + s[in] = addState(s[in], st.inst.next(), st.match) case _ALT: - s[in] = addState(s[in], st.inst.(*_Alt).left, st.match); + s[in] = addState(s[in], st.inst.(*_Alt).left, st.match) // give other branch a copy of this match vector - s1 := make([]int, 2*(re.nbra+1)); + s1 := make([]int, 2*(re.nbra+1)) for i := 0; i < len(s1); i++ { s1[i] = st.match[i] } - s[in] = addState(s[in], st.inst.next(), s1); + s[in] = addState(s[in], st.inst.next(), s1) case _END: // choose leftmost longest - if !found || // first - st.match[0] < final.match[0] || // leftmost - (st.match[0] == final.match[0] && pos > final.match[1]) { // longest - final = st; - final.match[1] = pos; + if !found || // first + st.match[0] < final.match[0] || // leftmost + (st.match[0] == final.match[0] && pos > final.match[1]) { // longest + final = st + final.match[1] = pos } - found = true; + found = true default: - st.inst.print(); - panic("unknown instruction in execute"); + st.inst.print() + panic("unknown instruction in execute") } } - pos += charwidth; + pos += charwidth } - return final.match; + return final.match } @@ -781,17 +781,17 @@ func (re *Regexp) ExecuteString(s string) (a []int) { // b[a[2*i]:a[2*i+1]] for i > 0 is the subslice matched by the ith parenthesized subexpression. // A negative value means the subexpression did not match any element of the slice. // An empty array means "no match". -func (re *Regexp) Execute(b []byte) (a []int) { return re.doExecute("", b, 0) } +func (re *Regexp) Execute(b []byte) (a []int) { return re.doExecute("", b, 0) } // MatchString returns whether the Regexp matches the string s. // The return value is a boolean: true for match, false for no match. -func (re *Regexp) MatchString(s string) bool { return len(re.doExecute(s, nil, 0)) > 0 } +func (re *Regexp) MatchString(s string) bool { return len(re.doExecute(s, nil, 0)) > 0 } // Match returns whether the Regexp matches the byte slice b. // The return value is a boolean: true for match, false for no match. -func (re *Regexp) Match(b []byte) bool { return len(re.doExecute("", b, 0)) > 0 } +func (re *Regexp) Match(b []byte) bool { return len(re.doExecute("", b, 0)) > 0 } // MatchStrings matches the Regexp against the string s. @@ -800,17 +800,17 @@ func (re *Regexp) Match(b []byte) bool { return len(re.doExecute("", b, 0)) > 0 // a[i] for i > 0 is the substring matched by the ith parenthesized subexpression. // An empty array means ``no match''. func (re *Regexp) MatchStrings(s string) (a []string) { - r := re.doExecute(s, nil, 0); + r := re.doExecute(s, nil, 0) if r == nil { return nil } - a = make([]string, len(r)/2); + a = make([]string, len(r)/2) for i := 0; i < len(r); i += 2 { - if r[i] != -1 { // -1 means no match for this subexpression + if r[i] != -1 { // -1 means no match for this subexpression a[i/2] = s[r[i]:r[i+1]] } } - return; + return } // MatchSlices matches the Regexp against the byte slice b. @@ -819,37 +819,37 @@ func (re *Regexp) MatchStrings(s string) (a []string) { // a[i] for i > 0 is the subslice matched by the ith parenthesized subexpression. // An empty array means ``no match''. func (re *Regexp) MatchSlices(b []byte) (a [][]byte) { - r := re.doExecute("", b, 0); + r := re.doExecute("", b, 0) if r == nil { return nil } - a = make([][]byte, len(r)/2); + a = make([][]byte, len(r)/2) for i := 0; i < len(r); i += 2 { - if r[i] != -1 { // -1 means no match for this subexpression + if r[i] != -1 { // -1 means no match for this subexpression a[i/2] = b[r[i]:r[i+1]] } } - return; + return } // MatchString checks whether a textual regular expression // matches a string. More complicated queries need // to use Compile and the full Regexp interface. func MatchString(pattern string, s string) (matched bool, error string) { - re, err := CompileRegexp(pattern); + re, err := CompileRegexp(pattern) if err != "" { return false, err } - return re.MatchString(s), ""; + return re.MatchString(s), "" } // Match checks whether a textual regular expression // matches a byte slice. More complicated queries need // to use Compile and the full Regexp interface. func Match(pattern string, b []byte) (matched bool, error string) { - re, err := CompileRegexp(pattern); + re, err := CompileRegexp(pattern) if err != "" { return false, err } - return re.Match(b), ""; + return re.Match(b), "" } diff --git a/src/pkg/testing/regexp_test.go b/src/pkg/testing/regexp_test.go index 66139ea1e..51b632ee2 100644 --- a/src/pkg/testing/regexp_test.go +++ b/src/pkg/testing/regexp_test.go @@ -5,7 +5,7 @@ package testing import ( - "strings"; + "strings" ) var good_re = []string{ @@ -30,8 +30,8 @@ var good_re = []string{ // TODO: nice to do this with a map type stringError struct { - re string; - err string; + re string + err string } var bad_re = []stringError{ @@ -52,9 +52,9 @@ var bad_re = []stringError{ type vec []int type tester struct { - re string; - text string; - match vec; + re string + text string + match vec } var matches = []tester{ @@ -87,15 +87,15 @@ var matches = []tester{ } func compileTest(t *T, expr string, error string) *Regexp { - re, err := CompileRegexp(expr); + re, err := CompileRegexp(expr) if err != error { t.Error("compiling `", expr, "`; unexpected error: ", err) } - return re; + return re } func printVec(t *T, m []int) { - l := len(m); + l := len(m) if l == 0 { t.Log("\t<no match>") } else { @@ -106,7 +106,7 @@ func printVec(t *T, m []int) { } func printStrings(t *T, m []string) { - l := len(m); + l := len(m) if l == 0 { t.Log("\t<no match>") } else { @@ -117,7 +117,7 @@ func printStrings(t *T, m []string) { } func printBytes(t *T, b [][]byte) { - l := len(b); + l := len(b) if l == 0 { t.Log("\t<no match>") } else { @@ -128,7 +128,7 @@ func printBytes(t *T, b [][]byte) { } func equal(m1, m2 []int) bool { - l := len(m1); + l := len(m1) if l != len(m2) { return false } @@ -137,11 +137,11 @@ func equal(m1, m2 []int) bool { return false } } - return true; + return true } func equalStrings(m1, m2 []string) bool { - l := len(m1); + l := len(m1) if l != len(m2) { return false } @@ -150,11 +150,11 @@ func equalStrings(m1, m2 []string) bool { return false } } - return true; + return true } func equalBytes(m1 [][]byte, m2 []string) bool { - l := len(m1); + l := len(m1) if l != len(m2) { return false } @@ -163,28 +163,28 @@ func equalBytes(m1 [][]byte, m2 []string) bool { return false } } - return true; + return true } func executeTest(t *T, expr string, str string, match []int) { - re := compileTest(t, expr, ""); + re := compileTest(t, expr, "") if re == nil { return } - m := re.ExecuteString(str); + m := re.ExecuteString(str) if !equal(m, match) { - t.Error("ExecuteString failure on `", expr, "` matching `", str, "`:"); - printVec(t, m); - t.Log("should be:"); - printVec(t, match); + t.Error("ExecuteString failure on `", expr, "` matching `", str, "`:") + printVec(t, m) + t.Log("should be:") + printVec(t, match) } // now try bytes - m = re.Execute(strings.Bytes(str)); + m = re.Execute(strings.Bytes(str)) if !equal(m, match) { - t.Error("Execute failure on `", expr, "` matching `", str, "`:"); - printVec(t, m); - t.Log("should be:"); - printVec(t, match); + t.Error("Execute failure on `", expr, "` matching `", str, "`:") + printVec(t, m) + t.Log("should be:") + printVec(t, match) } } @@ -202,22 +202,22 @@ func TestBadCompile(t *T) { func TestExecute(t *T) { for i := 0; i < len(matches); i++ { - test := &matches[i]; - executeTest(t, test.re, test.text, test.match); + test := &matches[i] + executeTest(t, test.re, test.text, test.match) } } func matchTest(t *T, expr string, str string, match []int) { - re := compileTest(t, expr, ""); + re := compileTest(t, expr, "") if re == nil { return } - m := re.MatchString(str); + m := re.MatchString(str) if m != (len(match) > 0) { t.Error("MatchString failure on `", expr, "` matching `", str, "`:", m, "should be", len(match) > 0) } // now try bytes - m = re.Match(strings.Bytes(str)); + m = re.Match(strings.Bytes(str)) if m != (len(match) > 0) { t.Error("Match failure on `", expr, "` matching `", str, "`:", m, "should be", len(match) > 0) } @@ -225,46 +225,46 @@ func matchTest(t *T, expr string, str string, match []int) { func TestMatch(t *T) { for i := 0; i < len(matches); i++ { - test := &matches[i]; - matchTest(t, test.re, test.text, test.match); + test := &matches[i] + matchTest(t, test.re, test.text, test.match) } } func matchStringsTest(t *T, expr string, str string, match []int) { - re := compileTest(t, expr, ""); + re := compileTest(t, expr, "") if re == nil { return } - strs := make([]string, len(match)/2); + strs := make([]string, len(match)/2) for i := 0; i < len(match); i++ { strs[i/2] = str[match[i]:match[i+1]] } - m := re.MatchStrings(str); + m := re.MatchStrings(str) if !equalStrings(m, strs) { - t.Error("MatchStrings failure on `", expr, "` matching `", str, "`:"); - printStrings(t, m); - t.Log("should be:"); - printStrings(t, strs); + t.Error("MatchStrings failure on `", expr, "` matching `", str, "`:") + printStrings(t, m) + t.Log("should be:") + printStrings(t, strs) } // now try bytes - s := re.MatchSlices(strings.Bytes(str)); + s := re.MatchSlices(strings.Bytes(str)) if !equalBytes(s, strs) { - t.Error("MatchSlices failure on `", expr, "` matching `", str, "`:"); - printBytes(t, s); - t.Log("should be:"); - printStrings(t, strs); + t.Error("MatchSlices failure on `", expr, "` matching `", str, "`:") + printBytes(t, s) + t.Log("should be:") + printStrings(t, strs) } } func TestMatchStrings(t *T) { for i := 0; i < len(matches); i++ { - test := &matches[i]; - matchTest(t, test.re, test.text, test.match); + test := &matches[i] + matchTest(t, test.re, test.text, test.match) } } func matchFunctionTest(t *T, expr string, str string, match []int) { - m, err := MatchString(expr, str); + m, err := MatchString(expr, str) if err == "" { return } @@ -275,15 +275,15 @@ func matchFunctionTest(t *T, expr string, str string, match []int) { func TestMatchFunction(t *T) { for i := 0; i < len(matches); i++ { - test := &matches[i]; - matchFunctionTest(t, test.re, test.text, test.match); + test := &matches[i] + matchFunctionTest(t, test.re, test.text, test.match) } } func BenchmarkSimpleMatch(b *B) { - b.StopTimer(); - re, _ := CompileRegexp("a"); - b.StartTimer(); + b.StopTimer() + re, _ := CompileRegexp("a") + b.StartTimer() for i := 0; i < b.N; i++ { re.MatchString("a") @@ -291,9 +291,9 @@ func BenchmarkSimpleMatch(b *B) { } func BenchmarkUngroupedMatch(b *B) { - b.StopTimer(); - re, _ := CompileRegexp("[a-z]+ [0-9]+ [a-z]+"); - b.StartTimer(); + b.StopTimer() + re, _ := CompileRegexp("[a-z]+ [0-9]+ [a-z]+") + b.StartTimer() for i := 0; i < b.N; i++ { re.MatchString("word 123 other") @@ -301,9 +301,9 @@ func BenchmarkUngroupedMatch(b *B) { } func BenchmarkGroupedMatch(b *B) { - b.StopTimer(); - re, _ := CompileRegexp("([a-z]+) ([0-9]+) ([a-z]+)"); - b.StartTimer(); + b.StopTimer() + re, _ := CompileRegexp("([a-z]+) ([0-9]+) ([a-z]+)") + b.StartTimer() for i := 0; i < b.N; i++ { re.MatchString("word 123 other") diff --git a/src/pkg/testing/script/script.go b/src/pkg/testing/script/script.go index 623685efd..9a41a467f 100644 --- a/src/pkg/testing/script/script.go +++ b/src/pkg/testing/script/script.go @@ -6,37 +6,37 @@ package script import ( - "fmt"; - "os"; - "rand"; - "reflect"; - "strings"; + "fmt" + "os" + "rand" + "reflect" + "strings" ) // An Event is an element in a partially ordered set that either sends a value // to a channel or expects a value from a channel. type Event struct { - name string; - occurred bool; - predecessors []*Event; - action action; + name string + occurred bool + predecessors []*Event + action action } type action interface { // getSend returns nil if the action is not a send action. - getSend() sendAction; + getSend() sendAction // getRecv returns nil if the action is not a receive action. - getRecv() recvAction; + getRecv() recvAction // getChannel returns the channel that the action operates on. - getChannel() interface{}; + getChannel() interface{} } type recvAction interface { - recvMatch(interface{}) bool; + recvMatch(interface{}) bool } type sendAction interface { - send(); + send() } // isReady returns true if all the predecessors of an Event have occurred. @@ -47,87 +47,87 @@ func (e Event) isReady() bool { } } - return true; + return true } // A Recv action reads a value from a channel and uses reflect.DeepMatch to // compare it with an expected value. type Recv struct { - Channel interface{}; - Expected interface{}; + Channel interface{} + Expected interface{} } -func (r Recv) getRecv() recvAction { return r } +func (r Recv) getRecv() recvAction { return r } -func (Recv) getSend() sendAction { return nil } +func (Recv) getSend() sendAction { return nil } -func (r Recv) getChannel() interface{} { return r.Channel } +func (r Recv) getChannel() interface{} { return r.Channel } func (r Recv) recvMatch(chanEvent interface{}) bool { - c, ok := chanEvent.(channelRecv); + c, ok := chanEvent.(channelRecv) if !ok || c.channel != r.Channel { return false } - return reflect.DeepEqual(c.value, r.Expected); + return reflect.DeepEqual(c.value, r.Expected) } // A RecvMatch action reads a value from a channel and calls a function to // determine if the value matches. type RecvMatch struct { - Channel interface{}; - Match func(interface{}) bool; + Channel interface{} + Match func(interface{}) bool } -func (r RecvMatch) getRecv() recvAction { return r } +func (r RecvMatch) getRecv() recvAction { return r } -func (RecvMatch) getSend() sendAction { return nil } +func (RecvMatch) getSend() sendAction { return nil } -func (r RecvMatch) getChannel() interface{} { return r.Channel } +func (r RecvMatch) getChannel() interface{} { return r.Channel } func (r RecvMatch) recvMatch(chanEvent interface{}) bool { - c, ok := chanEvent.(channelRecv); + c, ok := chanEvent.(channelRecv) if !ok || c.channel != r.Channel { return false } - return r.Match(c.value); + return r.Match(c.value) } // A Closed action matches if the given channel is closed. The closing is // treated as an event, not a state, thus Closed will only match once for a // given channel. type Closed struct { - Channel interface{}; + Channel interface{} } -func (r Closed) getRecv() recvAction { return r } +func (r Closed) getRecv() recvAction { return r } -func (Closed) getSend() sendAction { return nil } +func (Closed) getSend() sendAction { return nil } -func (r Closed) getChannel() interface{} { return r.Channel } +func (r Closed) getChannel() interface{} { return r.Channel } func (r Closed) recvMatch(chanEvent interface{}) bool { - c, ok := chanEvent.(channelClosed); + c, ok := chanEvent.(channelClosed) if !ok || c.channel != r.Channel { return false } - return true; + return true } // A Send action sends a value to a channel. The value must match the // type of the channel exactly unless the channel if of type chan interface{}. type Send struct { - Channel interface{}; - Value interface{}; + Channel interface{} + Value interface{} } -func (Send) getRecv() recvAction { return nil } +func (Send) getRecv() recvAction { return nil } -func (s Send) getSend() sendAction { return s } +func (s Send) getSend() sendAction { return s } -func (s Send) getChannel() interface{} { return s.Channel } +func (s Send) getChannel() interface{} { return s.Channel } func newEmptyInterface(args ...) reflect.Value { return reflect.NewValue(args).(*reflect.StructValue).Field(0) @@ -137,53 +137,53 @@ func (s Send) send() { // With reflect.ChanValue.Send, we must match the types exactly. So, if // s.Channel is a chan interface{} we convert s.Value to an interface{} // first. - c := reflect.NewValue(s.Channel).(*reflect.ChanValue); - var v reflect.Value; + c := reflect.NewValue(s.Channel).(*reflect.ChanValue) + var v reflect.Value if iface, ok := c.Type().(*reflect.ChanType).Elem().(*reflect.InterfaceType); ok && iface.NumMethod() == 0 { v = newEmptyInterface(s.Value) } else { v = reflect.NewValue(s.Value) } - c.Send(v); + c.Send(v) } // A Close action closes the given channel. type Close struct { - Channel interface{}; + Channel interface{} } -func (Close) getRecv() recvAction { return nil } +func (Close) getRecv() recvAction { return nil } -func (s Close) getSend() sendAction { return s } +func (s Close) getSend() sendAction { return s } -func (s Close) getChannel() interface{} { return s.Channel } +func (s Close) getChannel() interface{} { return s.Channel } -func (s Close) send() { reflect.NewValue(s.Channel).(*reflect.ChanValue).Close() } +func (s Close) send() { reflect.NewValue(s.Channel).(*reflect.ChanValue).Close() } // A ReceivedUnexpected error results if no active Events match a value // received from a channel. type ReceivedUnexpected struct { - Value interface{}; - ready []*Event; + Value interface{} + ready []*Event } func (r ReceivedUnexpected) String() string { - names := make([]string, len(r.ready)); + names := make([]string, len(r.ready)) for i, v := range r.ready { names[i] = v.name } - return fmt.Sprintf("received unexpected value on one of the channels: %#v. Runnable events: %s", r.Value, strings.Join(names, ", ")); + return fmt.Sprintf("received unexpected value on one of the channels: %#v. Runnable events: %s", r.Value, strings.Join(names, ", ")) } // A SetupError results if there is a error with the configuration of a set of // Events. type SetupError string -func (s SetupError) String() string { return string(s) } +func (s SetupError) String() string { return string(s) } func NewEvent(name string, predecessors []*Event, action action) *Event { - e := &Event{name, false, predecessors, action}; - return e; + e := &Event{name, false, predecessors, action} + return e } // Given a set of Events, Perform repeatedly iterates over the set and finds the @@ -220,20 +220,20 @@ func NewEvent(name string, predecessors []*Event, action action) *Event { // thus Perform may see a value from a channel that is not in the current ready // set and fail. func Perform(seed int64, events []*Event) (err os.Error) { - r := rand.New(rand.NewSource(seed)); + r := rand.New(rand.NewSource(seed)) - channels, err := getChannels(events); + channels, err := getChannels(events) if err != nil { return } - multiplex := make(chan interface{}); + multiplex := make(chan interface{}) for _, channel := range channels { go recvValues(multiplex, channel) } Outer: for { - ready, err := readyEvents(events); + ready, err := readyEvents(events) if err != nil { return err } @@ -243,113 +243,113 @@ Outer: break } - event := ready[r.Intn(len(ready))]; + event := ready[r.Intn(len(ready))] if send := event.action.getSend(); send != nil { - send.send(); - event.occurred = true; - continue; + send.send() + event.occurred = true + continue } - v := <-multiplex; + v := <-multiplex for _, event := range ready { if recv := event.action.getRecv(); recv != nil && recv.recvMatch(v) { - event.occurred = true; - continue Outer; + event.occurred = true + continue Outer } } - return ReceivedUnexpected{v, ready}; + return ReceivedUnexpected{v, ready} } - return nil; + return nil } // getChannels returns all the channels listed in any receive events. func getChannels(events []*Event) ([]interface{}, os.Error) { - channels := make([]interface{}, len(events)); + channels := make([]interface{}, len(events)) - j := 0; + j := 0 for _, event := range events { if recv := event.action.getRecv(); recv == nil { continue } - c := event.action.getChannel(); + c := event.action.getChannel() if _, ok := reflect.NewValue(c).(*reflect.ChanValue); !ok { return nil, SetupError("one of the channel values is not a channel") } - duplicate := false; + duplicate := false for _, other := range channels[0:j] { if c == other { - duplicate = true; - break; + duplicate = true + break } } if !duplicate { - channels[j] = c; - j++; + channels[j] = c + j++ } } - return channels[0:j], nil; + return channels[0:j], nil } // recvValues is a multiplexing helper function. It reads values from the given // channel repeatedly, wrapping them up as either a channelRecv or // channelClosed structure, and forwards them to the multiplex channel. func recvValues(multiplex chan<- interface{}, channel interface{}) { - c := reflect.NewValue(channel).(*reflect.ChanValue); + c := reflect.NewValue(channel).(*reflect.ChanValue) for { - v := c.Recv(); + v := c.Recv() if c.Closed() { - multiplex <- channelClosed{channel}; - return; + multiplex <- channelClosed{channel} + return } - multiplex <- channelRecv{channel, v.Interface()}; + multiplex <- channelRecv{channel, v.Interface()} } } type channelClosed struct { - channel interface{}; + channel interface{} } type channelRecv struct { - channel interface{}; - value interface{}; + channel interface{} + value interface{} } // readyEvents returns the subset of events that are ready. func readyEvents(events []*Event) ([]*Event, os.Error) { - ready := make([]*Event, len(events)); + ready := make([]*Event, len(events)) - j := 0; - eventsWaiting := false; + j := 0 + eventsWaiting := false for _, event := range events { if event.occurred { continue } - eventsWaiting = true; + eventsWaiting = true if event.isReady() { - ready[j] = event; - j++; + ready[j] = event + j++ } } if j == 0 && eventsWaiting { - names := make([]string, len(events)); + names := make([]string, len(events)) for _, event := range events { if event.occurred { continue } - names[j] = event.name; + names[j] = event.name } - return nil, SetupError("dependency cycle in events. These events are waiting to run but cannot: " + strings.Join(names, ", ")); + return nil, SetupError("dependency cycle in events. These events are waiting to run but cannot: " + strings.Join(names, ", ")) } - return ready[0:j], nil; + return ready[0:j], nil } diff --git a/src/pkg/testing/script/script_test.go b/src/pkg/testing/script/script_test.go index 359218c60..e9ab142c2 100644 --- a/src/pkg/testing/script/script_test.go +++ b/src/pkg/testing/script/script_test.go @@ -5,37 +5,37 @@ package script import ( - "testing"; + "testing" ) func TestNoop(t *testing.T) { - err := Perform(0, nil); + err := Perform(0, nil) if err != nil { t.Errorf("Got error: %s", err) } } func TestSimple(t *testing.T) { - c := make(chan int); - defer close(c); + c := make(chan int) + defer close(c) - a := NewEvent("send", nil, Send{c, 1}); - b := NewEvent("recv", []*Event{a}, Recv{c, 1}); + a := NewEvent("send", nil, Send{c, 1}) + b := NewEvent("recv", []*Event{a}, Recv{c, 1}) - err := Perform(0, []*Event{a, b}); + err := Perform(0, []*Event{a, b}) if err != nil { t.Errorf("Got error: %s", err) } } func TestFail(t *testing.T) { - c := make(chan int); - defer close(c); + c := make(chan int) + defer close(c) - a := NewEvent("send", nil, Send{c, 2}); - b := NewEvent("recv", []*Event{a}, Recv{c, 1}); + a := NewEvent("send", nil, Send{c, 2}) + b := NewEvent("recv", []*Event{a}, Recv{c, 1}) - err := Perform(0, []*Event{a, b}); + err := Perform(0, []*Event{a, b}) if err == nil { t.Errorf("Failed to get expected error") } else if _, ok := err.(ReceivedUnexpected); !ok { @@ -44,12 +44,12 @@ func TestFail(t *testing.T) { } func TestClose(t *testing.T) { - c := make(chan int); + c := make(chan int) - a := NewEvent("close", nil, Close{c}); - b := NewEvent("closed", []*Event{a}, Closed{c}); + a := NewEvent("close", nil, Close{c}) + b := NewEvent("closed", []*Event{a}, Closed{c}) - err := Perform(0, []*Event{a, b}); + err := Perform(0, []*Event{a, b}) if err != nil { t.Errorf("Got error: %s", err) } @@ -59,16 +59,16 @@ func matchOne(v interface{}) bool { if i, ok := v.(int); ok && i == 1 { return true } - return false; + return false } func TestRecvMatch(t *testing.T) { - c := make(chan int); + c := make(chan int) - a := NewEvent("send", nil, Send{c, 1}); - b := NewEvent("recv", []*Event{a}, RecvMatch{c, matchOne}); + a := NewEvent("send", nil, Send{c, 1}) + b := NewEvent("recv", []*Event{a}, RecvMatch{c, matchOne}) - err := Perform(0, []*Event{a, b}); + err := Perform(0, []*Event{a, b}) if err != nil { t.Errorf("Got error: %s", err) } diff --git a/src/pkg/testing/testing.go b/src/pkg/testing/testing.go index 654d344c0..77f9942d8 100644 --- a/src/pkg/testing/testing.go +++ b/src/pkg/testing/testing.go @@ -39,10 +39,10 @@ package testing import ( - "flag"; - "fmt"; - "os"; - "runtime"; + "flag" + "fmt" + "os" + "runtime" ) // Report as tests are run; default is silent for success. @@ -52,44 +52,44 @@ var match = flag.String("match", "", "regular expression to select tests to run" // Insert final newline if needed and tabs after internal newlines. func tabify(s string) string { - n := len(s); + n := len(s) if n > 0 && s[n-1] != '\n' { - s += "\n"; - n++; + s += "\n" + n++ } - for i := 0; i < n-1; i++ { // -1 to avoid final newline + for i := 0; i < n-1; i++ { // -1 to avoid final newline if s[i] == '\n' { return s[0:i+1] + "\t" + tabify(s[i+1:n]) } } - return s; + return s } // T is a type passed to Test functions to manage test state and support formatted test logs. // Logs are accumulated during execution and dumped to standard error when done. type T struct { - errors string; - failed bool; - ch chan *T; + errors string + failed bool + ch chan *T } // Fail marks the Test function as having failed but continues execution. -func (t *T) Fail() { t.failed = true } +func (t *T) Fail() { t.failed = true } // Failed returns whether the Test function has failed. -func (t *T) Failed() bool { return t.failed } +func (t *T) Failed() bool { return t.failed } // FailNow marks the Test function as having failed and stops its execution. // Execution will continue at the next Test. func (t *T) FailNow() { - t.Fail(); - t.ch <- t; - runtime.Goexit(); + t.Fail() + t.ch <- t + runtime.Goexit() } // Log formats its arguments using default formatting, analogous to Print(), // and records the text in the error log. -func (t *T) Log(args ...) { t.errors += "\t" + tabify(fmt.Sprintln(args)) } +func (t *T) Log(args ...) { t.errors += "\t" + tabify(fmt.Sprintln(args)) } // Log formats its arguments according to the format, analogous to Printf(), // and records the text in the error log. @@ -99,52 +99,52 @@ func (t *T) Logf(format string, args ...) { // Error is equivalent to Log() followed by Fail(). func (t *T) Error(args ...) { - t.Log(args); - t.Fail(); + t.Log(args) + t.Fail() } // Errorf is equivalent to Logf() followed by Fail(). func (t *T) Errorf(format string, args ...) { - t.Logf(format, args); - t.Fail(); + t.Logf(format, args) + t.Fail() } // Fatal is equivalent to Log() followed by FailNow(). func (t *T) Fatal(args ...) { - t.Log(args); - t.FailNow(); + t.Log(args) + t.FailNow() } // Fatalf is equivalent to Logf() followed by FailNow(). func (t *T) Fatalf(format string, args ...) { - t.Logf(format, args); - t.FailNow(); + t.Logf(format, args) + t.FailNow() } // An internal type but exported because it is cross-package; part of the implementation // of gotest. type Test struct { - Name string; - F func(*T); + Name string + F func(*T) } func tRunner(t *T, test *Test) { - test.F(t); - t.ch <- t; + test.F(t) + t.ch <- t } // An internal function but exported because it is cross-package; part of the implementation // of gotest. func Main(tests []Test) { - flag.Parse(); - ok := true; + flag.Parse() + ok := true if len(tests) == 0 { println("testing: warning: no tests to run") } - re, err := CompileRegexp(*match); + re, err := CompileRegexp(*match) if err != "" { - println("invalid regexp for -match:", err); - os.Exit(1); + println("invalid regexp for -match:", err) + os.Exit(1) } for i := 0; i < len(tests); i++ { if !re.MatchString(tests[i].Name) { @@ -153,22 +153,22 @@ func Main(tests []Test) { if *chatty { println("=== RUN ", tests[i].Name) } - t := new(T); - t.ch = make(chan *T); - go tRunner(t, &tests[i]); - <-t.ch; + t := new(T) + t.ch = make(chan *T) + go tRunner(t, &tests[i]) + <-t.ch if t.failed { - println("--- FAIL:", tests[i].Name); - print(t.errors); - ok = false; + println("--- FAIL:", tests[i].Name) + print(t.errors) + ok = false } else if *chatty { - println("--- PASS:", tests[i].Name); - print(t.errors); + println("--- PASS:", tests[i].Name) + print(t.errors) } } if !ok { - println("FAIL"); - os.Exit(1); + println("FAIL") + os.Exit(1) } - println("PASS"); + println("PASS") } |