Commit 45ca9f7a authored by Robert Griesemer's avatar Robert Griesemer

1) Change default gofmt default settings for

   parsing and printing to new syntax.

   Use -oldparser to parse the old syntax,
   use -oldprinter to print the old syntax.

2) Change default gofmt formatting settings
   to use tabs for indentation only and to use
   spaces for alignment. This will make the code
   alignment insensitive to an editor's tabwidth.

   Use -spaces=false to use tabs for alignment.

3) Manually changed src/exp/parser/parser_test.go
   so that it doesn't try to parse the parser's
   source files using the old syntax (they have
   new syntax now).

4) gofmt -w src misc test/bench

5th and last set of files.

R=rsc
CC=golang-dev
https://golang.org/cl/180050
parent d65a5cce
......@@ -9,10 +9,10 @@
package syslog
import (
"fmt";
"log";
"net";
"os";
"fmt"
"log"
"net"
"os"
)
type Priority int
......@@ -20,21 +20,21 @@ type Priority int
const (
// From /usr/include/sys/syslog.h.
// These are the same on Linux, BSD, and OS X.
LOG_EMERG Priority = iota;
LOG_ALERT;
LOG_CRIT;
LOG_ERR;
LOG_WARNING;
LOG_NOTICE;
LOG_INFO;
LOG_DEBUG;
LOG_EMERG Priority = iota
LOG_ALERT
LOG_CRIT
LOG_ERR
LOG_WARNING
LOG_NOTICE
LOG_INFO
LOG_DEBUG
)
// A Writer is a connection to a syslog server.
type Writer struct {
priority Priority;
prefix string;
conn net.Conn;
priority Priority
prefix string
conn net.Conn
}
// New establishes a new connection to the system log daemon.
......@@ -52,23 +52,23 @@ func Dial(network, raddr string, priority Priority, prefix string) (w *Writer, e
if prefix == "" {
prefix = os.Args[0]
}
var conn net.Conn;
var conn net.Conn
if network == "" {
conn, err = unixSyslog()
} else {
conn, err = net.Dial(network, "", raddr)
}
return &Writer{priority, prefix, conn}, err;
return &Writer{priority, prefix, conn}, err
}
func unixSyslog() (conn net.Conn, err os.Error) {
logTypes := []string{"unixgram", "unix"};
logPaths := []string{"/dev/log", "/var/run/syslog"};
var raddr string;
logTypes := []string{"unixgram", "unix"}
logPaths := []string{"/dev/log", "/var/run/syslog"}
var raddr string
for _, network := range logTypes {
for _, path := range logPaths {
raddr = path;
conn, err := net.Dial(network, "", raddr);
raddr = path
conn, err := net.Dial(network, "", raddr)
if err != nil {
continue
} else {
......@@ -76,7 +76,7 @@ func unixSyslog() (conn net.Conn, err os.Error) {
}
}
}
return nil, os.ErrorString("Unix syslog delivery error");
return nil, os.ErrorString("Unix syslog delivery error")
}
// Write sends a log message to the syslog daemon.
......@@ -84,7 +84,7 @@ func (w *Writer) Write(b []byte) (int, os.Error) {
if w.priority > LOG_DEBUG || w.priority < LOG_EMERG {
return 0, os.EINVAL
}
return fmt.Fprintf(w.conn, "<%d>%s: %s\n", w.priority, w.prefix, b);
return fmt.Fprintf(w.conn, "<%d>%s: %s\n", w.priority, w.prefix, b)
}
func (w *Writer) writeString(p Priority, s string) (int, os.Error) {
......@@ -95,40 +95,40 @@ func (w *Writer) Close() os.Error { return w.conn.Close() }
// Emerg logs a message using the LOG_EMERG priority.
func (w *Writer) Emerg(m string) (err os.Error) {
_, err = w.writeString(LOG_EMERG, m);
return err;
_, err = w.writeString(LOG_EMERG, m)
return err
}
// Crit logs a message using the LOG_CRIT priority.
func (w *Writer) Crit(m string) (err os.Error) {
_, err = w.writeString(LOG_CRIT, m);
return err;
_, err = w.writeString(LOG_CRIT, m)
return err
}
// ERR logs a message using the LOG_ERR priority.
func (w *Writer) Err(m string) (err os.Error) {
_, err = w.writeString(LOG_ERR, m);
return err;
_, err = w.writeString(LOG_ERR, m)
return err
}
// Warning logs a message using the LOG_WARNING priority.
func (w *Writer) Warning(m string) (err os.Error) {
_, err = w.writeString(LOG_WARNING, m);
return err;
_, err = w.writeString(LOG_WARNING, m)
return err
}
// Notice logs a message using the LOG_NOTICE priority.
func (w *Writer) Notice(m string) (err os.Error) {
_, err = w.writeString(LOG_NOTICE, m);
return err;
_, err = w.writeString(LOG_NOTICE, m)
return err
}
// Info logs a message using the LOG_INFO priority.
func (w *Writer) Info(m string) (err os.Error) {
_, err = w.writeString(LOG_INFO, m);
return err;
_, err = w.writeString(LOG_INFO, m)
return err
}
// Debug logs a message using the LOG_DEBUG priority.
func (w *Writer) Debug(m string) (err os.Error) {
_, err = w.writeString(LOG_DEBUG, m);
return err;
_, err = w.writeString(LOG_DEBUG, m)
return err
}
// NewLogger provides an object that implements the full log.Logger interface,
......@@ -136,9 +136,9 @@ func (w *Writer) Debug(m string) (err os.Error) {
// priority will be used for all messages sent using this interface.
// All messages are logged with priority p.
func NewLogger(p Priority, flag int) *log.Logger {
s, err := New(p, "");
s, err := New(p, "")
if err != nil {
return nil
}
return log.New(s, nil, "", flag);
return log.New(s, nil, "", flag)
}
......@@ -4,91 +4,91 @@
package syslog
import (
"io";
"log";
"net";
"testing";
"io"
"log"
"net"
"testing"
)
var serverAddr string
func runSyslog(c net.PacketConn, done chan<- string) {
var buf [4096]byte;
var rcvd string = "";
var buf [4096]byte
var rcvd string = ""
for {
n, _, err := c.ReadFrom(&buf);
n, _, err := c.ReadFrom(&buf)
if err != nil || n == 0 {
break
}
rcvd += string(buf[0:n]);
rcvd += string(buf[0:n])
}
done <- rcvd;
done <- rcvd
}
func startServer(done chan<- string) {
c, e := net.ListenPacket("udp", ":0");
c, e := net.ListenPacket("udp", ":0")
if e != nil {
log.Exitf("net.ListenPacket failed udp :0 %v", e)
}
serverAddr = c.LocalAddr().String();
c.SetReadTimeout(10e6); // 10ms
go runSyslog(c, done);
serverAddr = c.LocalAddr().String()
c.SetReadTimeout(10e6) // 10ms
go runSyslog(c, done)
}
func TestNew(t *testing.T) {
s, err := New(LOG_INFO, "");
s, err := New(LOG_INFO, "")
if err != nil {
t.Fatalf("New() failed: %s", err)
}
// Don't send any messages.
s.Close();
s.Close()
}
func TestNewLogger(t *testing.T) {
f := NewLogger(LOG_INFO, 0);
f := NewLogger(LOG_INFO, 0)
if f == nil {
t.Errorf("NewLogger() failed\n")
}
}
func TestDial(t *testing.T) {
l, err := Dial("", "", LOG_ERR, "syslog_test");
l, err := Dial("", "", LOG_ERR, "syslog_test")
if err != nil {
t.Fatalf("Dial() failed: %s", err)
}
l.Close();
l.Close()
}
func TestUDPDial(t *testing.T) {
done := make(chan string);
startServer(done);
l, err := Dial("udp", serverAddr, LOG_INFO, "syslog_test");
done := make(chan string)
startServer(done)
l, err := Dial("udp", serverAddr, LOG_INFO, "syslog_test")
if err != nil {
t.Fatalf("syslog.Dial() failed: %s", err)
}
msg := "udp test";
l.Info(msg);
expected := "<6>syslog_test: udp test\n";
rcvd := <-done;
msg := "udp test"
l.Info(msg)
expected := "<6>syslog_test: udp test\n"
rcvd := <-done
if rcvd != expected {
t.Fatalf("s.Info() = '%q', but wanted '%q'", rcvd, expected)
}
}
func TestWrite(t *testing.T) {
done := make(chan string);
startServer(done);
l, err := Dial("udp", serverAddr, LOG_ERR, "syslog_test");
done := make(chan string)
startServer(done)
l, err := Dial("udp", serverAddr, LOG_ERR, "syslog_test")
if err != nil {
t.Fatalf("syslog.Dial() failed: %s", err)
}
msg := "write test";
_, err = io.WriteString(l, msg);
msg := "write test"
_, err = io.WriteString(l, msg)
if err != nil {
t.Fatalf("WriteString() failed: %s", err)
}
expected := "<3>syslog_test: write test\n";
rcvd := <-done;
expected := "<3>syslog_test: write test\n"
rcvd := <-done
if rcvd != expected {
t.Fatalf("s.Info() = '%q', but wanted '%q'", rcvd, expected)
}
......
This diff is collapsed.
......@@ -5,14 +5,14 @@
package tabwriter
import (
"io";
"os";
"testing";
"io"
"os"
"testing"
)
type buffer struct {
a []byte;
a []byte
}
......@@ -23,17 +23,17 @@ func (b *buffer) clear() { b.a = b.a[0:0] }
func (b *buffer) Write(buf []byte) (written int, err os.Error) {
n := len(b.a);
m := len(buf);
n := len(b.a)
m := len(buf)
if n+m <= cap(b.a) {
b.a = b.a[0 : n+m];
b.a = b.a[0 : n+m]
for i := 0; i < m; i++ {
b.a[n+i] = buf[i]
}
} else {
panicln("buffer.Write: buffer too small", n, m, cap(b.a))
}
return len(buf), nil;
return len(buf), nil
}
......@@ -41,7 +41,7 @@ func (b *buffer) String() string { return string(b.a) }
func write(t *testing.T, testname string, w *Writer, src string) {
written, err := io.WriteString(w, src);
written, err := io.WriteString(w, src)
if err != nil {
t.Errorf("--- test: %s\n--- src:\n%s\n--- write error: %v\n", testname, src, err)
}
......@@ -52,12 +52,12 @@ func write(t *testing.T, testname string, w *Writer, src string) {
func verify(t *testing.T, testname string, w *Writer, b *buffer, src, expected string) {
err := w.Flush();
err := w.Flush()
if err != nil {
t.Errorf("--- test: %s\n--- src:\n%s\n--- flush error: %v\n", testname, src, err)
}
res := b.String();
res := b.String()
if res != expected {
t.Errorf("--- test: %s\n--- src:\n%s\n--- found:\n%s\n--- expected:\n%s\n", testname, src, res, expected)
}
......@@ -65,43 +65,43 @@ func verify(t *testing.T, testname string, w *Writer, b *buffer, src, expected s
func check(t *testing.T, testname string, minwidth, tabwidth, padding int, padchar byte, flags uint, src, expected string) {
var b buffer;
b.init(1000);
var b buffer
b.init(1000)
var w Writer;
w.Init(&b, minwidth, tabwidth, padding, padchar, flags);
var w Writer
w.Init(&b, minwidth, tabwidth, padding, padchar, flags)
// write all at once
b.clear();
write(t, testname, &w, src);
verify(t, testname, &w, &b, src, expected);
b.clear()
write(t, testname, &w, src)
verify(t, testname, &w, &b, src, expected)
// write byte-by-byte
b.clear();
b.clear()
for i := 0; i < len(src); i++ {
write(t, testname, &w, src[i:i+1])
}
verify(t, testname, &w, &b, src, expected);
verify(t, testname, &w, &b, src, expected)
// write using Fibonacci slice sizes
b.clear();
b.clear()
for i, d := 0, 0; i < len(src); {
write(t, testname, &w, src[i:i+d]);
i, d = i+d, d+1;
write(t, testname, &w, src[i:i+d])
i, d = i+d, d+1
if i+d > len(src) {
d = len(src) - i
}
}
verify(t, testname, &w, &b, src, expected);
verify(t, testname, &w, &b, src, expected)
}
type entry struct {
testname string;
minwidth, tabwidth, padding int;
padchar byte;
flags uint;
src, expected string;
testname string
minwidth, tabwidth, padding int
padchar byte
flags uint
src, expected string
}
......
......@@ -7,10 +7,10 @@
package template
import (
"bytes";
"fmt";
"io";
"strings";
"bytes"
"fmt"
"io"
"strings"
)
// StringFormatter formats into the default string representation.
......@@ -19,25 +19,25 @@ import (
// under the name "" in your custom formatter map.
func StringFormatter(w io.Writer, value interface{}, format string) {
if b, ok := value.([]byte); ok {
w.Write(b);
return;
w.Write(b)
return
}
fmt.Fprint(w, value);
fmt.Fprint(w, value)
}
var (
esc_quot = strings.Bytes("&#34;"); // shorter than "&quot;"
esc_apos = strings.Bytes("&#39;"); // shorter than "&apos;"
esc_amp = strings.Bytes("&amp;");
esc_lt = strings.Bytes("&lt;");
esc_gt = strings.Bytes("&gt;");
esc_quot = strings.Bytes("&#34;") // shorter than "&quot;"
esc_apos = strings.Bytes("&#39;") // shorter than "&apos;"
esc_amp = strings.Bytes("&amp;")
esc_lt = strings.Bytes("&lt;")
esc_gt = strings.Bytes("&gt;")
)
// HTMLEscape writes to w the properly escaped HTML equivalent
// of the plain text data s.
func HTMLEscape(w io.Writer, s []byte) {
var esc []byte;
last := 0;
var esc []byte
last := 0
for i, c := range s {
switch c {
case '"':
......@@ -53,16 +53,16 @@ func HTMLEscape(w io.Writer, s []byte) {
default:
continue
}
w.Write(s[last:i]);
w.Write(esc);
last = i + 1;
w.Write(s[last:i])
w.Write(esc)
last = i + 1
}
w.Write(s[last:]);
w.Write(s[last:])
}
// HTMLFormatter formats arbitrary values for HTML
func HTMLFormatter(w io.Writer, value interface{}, format string) {
var b bytes.Buffer;
fmt.Fprint(&b, value);
HTMLEscape(w, b.Bytes());
var b bytes.Buffer
fmt.Fprint(&b, value)
HTMLEscape(w, b.Bytes())
}
This diff is collapsed.
......@@ -5,65 +5,65 @@
package template
import (
"bytes";
"container/vector";
"fmt";
"io";
"strings";
"testing";
"bytes"
"container/vector"
"fmt"
"io"
"strings"
"testing"
)
type Test struct {
in, out, err string;
in, out, err string
}
type T struct {
item string;
value string;
item string
value string
}
type U struct {
mp map[string]int;
mp map[string]int
}
type S struct {
header string;
integer int;
raw string;
innerT T;
innerPointerT *T;
data []T;
pdata []*T;
empty []*T;
emptystring string;
null []*T;
vec *vector.Vector;
true bool;
false bool;
mp map[string]string;
innermap U;
bytes []byte;
header string
integer int
raw string
innerT T
innerPointerT *T
data []T
pdata []*T
empty []*T
emptystring string
null []*T
vec *vector.Vector
true bool
false bool
mp map[string]string
innermap U
bytes []byte
}
var t1 = T{"ItemNumber1", "ValueNumber1"}
var t2 = T{"ItemNumber2", "ValueNumber2"}
func uppercase(v interface{}) string {
s := v.(string);
t := "";
s := v.(string)
t := ""
for i := 0; i < len(s); i++ {
c := s[i];
c := s[i]
if 'a' <= c && c <= 'z' {
c = c + 'A' - 'a'
}
t += string(c);
t += string(c)
}
return t;
return t
}
func plus1(v interface{}) string {
i := v.(int);
return fmt.Sprint(i + 1);
i := v.(int)
return fmt.Sprint(i + 1)
}
func writer(f func(interface{}) string) (func(io.Writer, interface{}, string)) {
......@@ -306,36 +306,36 @@ var tests = []*Test{
}
func TestAll(t *testing.T) {
s := new(S);
s := new(S)
// initialized by hand for clarity.
s.header = "Header";
s.integer = 77;
s.raw = "&<>!@ #$%^";
s.innerT = t1;
s.data = []T{t1, t2};
s.pdata = []*T{&t1, &t2};
s.empty = []*T{};
s.null = nil;
s.vec = new(vector.Vector);
s.vec.Push("elt1");
s.vec.Push("elt2");
s.true = true;
s.false = false;
s.mp = make(map[string]string);
s.mp["mapkey"] = "Ahoy!";
s.innermap.mp = make(map[string]int);
s.innermap.mp["innerkey"] = 55;
s.bytes = strings.Bytes("hello");
var buf bytes.Buffer;
s.header = "Header"
s.integer = 77
s.raw = "&<>!@ #$%^"
s.innerT = t1
s.data = []T{t1, t2}
s.pdata = []*T{&t1, &t2}
s.empty = []*T{}
s.null = nil
s.vec = new(vector.Vector)
s.vec.Push("elt1")
s.vec.Push("elt2")
s.true = true
s.false = false
s.mp = make(map[string]string)
s.mp["mapkey"] = "Ahoy!"
s.innermap.mp = make(map[string]int)
s.innermap.mp["innerkey"] = 55
s.bytes = strings.Bytes("hello")
var buf bytes.Buffer
for _, test := range tests {
buf.Reset();
tmpl, err := Parse(test.in, formatters);
buf.Reset()
tmpl, err := Parse(test.in, formatters)
if err != nil {
t.Error("unexpected parse error:", err);
continue;
t.Error("unexpected parse error:", err)
continue
}
err = tmpl.Execute(s, &buf);
err = tmpl.Execute(s, &buf)
if test.err == "" {
if err != nil {
t.Error("unexpected execute error:", err)
......@@ -352,60 +352,60 @@ func TestAll(t *testing.T) {
}
func TestMapDriverType(t *testing.T) {
mp := map[string]string{"footer": "Ahoy!"};
tmpl, err := Parse("template: {footer}", nil);
mp := map[string]string{"footer": "Ahoy!"}
tmpl, err := Parse("template: {footer}", nil)
if err != nil {
t.Error("unexpected parse error:", err)
}
var b bytes.Buffer;
err = tmpl.Execute(mp, &b);
var b bytes.Buffer
err = tmpl.Execute(mp, &b)
if err != nil {
t.Error("unexpected execute error:", err)
}
s := b.String();
expected := "template: Ahoy!";
s := b.String()
expected := "template: Ahoy!"
if s != expected {
t.Errorf("failed passing string as data: expected %q got %q", "template: Ahoy!", s)
}
}
func TestStringDriverType(t *testing.T) {
tmpl, err := Parse("template: {@}", nil);
tmpl, err := Parse("template: {@}", nil)
if err != nil {
t.Error("unexpected parse error:", err)
}
var b bytes.Buffer;
err = tmpl.Execute("hello", &b);
var b bytes.Buffer
err = tmpl.Execute("hello", &b)
if err != nil {
t.Error("unexpected execute error:", err)
}
s := b.String();
s := b.String()
if s != "template: hello" {
t.Errorf("failed passing string as data: expected %q got %q", "template: hello", s)
}
}
func TestTwice(t *testing.T) {
tmpl, err := Parse("template: {@}", nil);
tmpl, err := Parse("template: {@}", nil)
if err != nil {
t.Error("unexpected parse error:", err)
}
var b bytes.Buffer;
err = tmpl.Execute("hello", &b);
var b bytes.Buffer
err = tmpl.Execute("hello", &b)
if err != nil {
t.Error("unexpected parse error:", err)
}
s := b.String();
text := "template: hello";
s := b.String()
text := "template: hello"
if s != text {
t.Errorf("failed passing string as data: expected %q got %q", text, s)
}
err = tmpl.Execute("hello", &b);
err = tmpl.Execute("hello", &b)
if err != nil {
t.Error("unexpected parse error:", err)
}
s = b.String();
text += text;
s = b.String()
text += text
if s != text {
t.Errorf("failed passing string as data: expected %q got %q", text, s)
}
......@@ -415,29 +415,29 @@ func TestCustomDelims(t *testing.T) {
// try various lengths. zero should catch error.
for i := 0; i < 7; i++ {
for j := 0; j < 7; j++ {
tmpl := New(nil);
tmpl := New(nil)
// first two chars deliberately the same to test equal left and right delims
ldelim := "$!#$%^&"[0:i];
rdelim := "$*&^%$!"[0:j];
tmpl.SetDelims(ldelim, rdelim);
ldelim := "$!#$%^&"[0:i]
rdelim := "$*&^%$!"[0:j]
tmpl.SetDelims(ldelim, rdelim)
// if braces, this would be template: {@}{.meta-left}{.meta-right}
text := "template: " +
ldelim + "@" + rdelim +
ldelim + ".meta-left" + rdelim +
ldelim + ".meta-right" + rdelim;
err := tmpl.Parse(text);
ldelim + ".meta-right" + rdelim
err := tmpl.Parse(text)
if err != nil {
if i == 0 || j == 0 { // expected
continue
}
t.Error("unexpected parse error:", err);
t.Error("unexpected parse error:", err)
} else if i == 0 || j == 0 {
t.Errorf("expected parse error for empty delimiter: %d %d %q %q", i, j, ldelim, rdelim);
continue;
t.Errorf("expected parse error for empty delimiter: %d %d %q %q", i, j, ldelim, rdelim)
continue
}
var b bytes.Buffer;
err = tmpl.Execute("hello", &b);
s := b.String();
var b bytes.Buffer
err = tmpl.Execute("hello", &b)
s := b.String()
if s != "template: hello"+ldelim+rdelim {
t.Errorf("failed delim check(%q %q) %q got %q", ldelim, rdelim, text, s)
}
......@@ -447,21 +447,21 @@ func TestCustomDelims(t *testing.T) {
// Test that a variable evaluates to the field itself and does not further indirection
func TestVarIndirection(t *testing.T) {
s := new(S);
s := new(S)
// initialized by hand for clarity.
s.innerPointerT = &t1;
s.innerPointerT = &t1
var buf bytes.Buffer;
input := "{.section @}{innerPointerT}{.end}";
tmpl, err := Parse(input, nil);
var buf bytes.Buffer
input := "{.section @}{innerPointerT}{.end}"
tmpl, err := Parse(input, nil)
if err != nil {
t.Fatal("unexpected parse error:", err)
}
err = tmpl.Execute(s, &buf);
err = tmpl.Execute(s, &buf)
if err != nil {
t.Fatal("unexpected execute error:", err)
}
expect := fmt.Sprintf("%v", &t1); // output should be hex address of t1
expect := fmt.Sprintf("%v", &t1) // output should be hex address of t1
if buf.String() != expect {
t.Errorf("for %q: expected %q got %q", input, expect, buf.String())
}
......
......@@ -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,18 +16,18 @@ 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
......@@ -42,13 +42,13 @@ 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.
......@@ -59,51 +59,51 @@ 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()
}
}
......@@ -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
......
......@@ -7,8 +7,8 @@
package iotest
import (
"io";
"os";
"io"
"os"
)
// OneByteReader returns a Reader that implements
......@@ -16,14 +16,14 @@ import (
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
......@@ -31,7 +31,7 @@ func (r *oneByteReader) Read(p []byte) (int, os.Error) {
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) {
......@@ -45,9 +45,9 @@ func (r *halfReader) Read(p []byte) (int, os.Error) {
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
}
......@@ -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
}
This diff is collapsed.
......@@ -5,10 +5,10 @@
package quick
import (
"rand";
"reflect";
"testing";
"os";
"rand"
"reflect"
"testing"
"os"
)
func fBool(a bool) bool { return a }
......@@ -38,8 +38,8 @@ func fSlice(a []byte) []byte { 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 }
......@@ -57,8 +57,8 @@ func fUint(a uint) uint { 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,34 +68,34 @@ 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 {
......@@ -109,8 +109,8 @@ func TestCheckProperty(t *testing.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")
}
......
This diff is collapsed.
......@@ -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")
......
......@@ -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,14 +47,14 @@ 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 }
......@@ -64,19 +64,19 @@ func (Recv) getSend() sendAction { return nil }
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 }
......@@ -86,19 +86,19 @@ func (RecvMatch) getSend() sendAction { return nil }
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 }
......@@ -108,19 +108,19 @@ func (Closed) getSend() sendAction { return nil }
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 }
......@@ -137,19 +137,19 @@ 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 }
......@@ -163,16 +163,16 @@ 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
......@@ -182,8 +182,8 @@ type SetupError string
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
}
......@@ -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)
}
......
......@@ -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,25 +52,25 @@ 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
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.
......@@ -82,9 +82,9 @@ 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(),
......@@ -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")
}
......@@ -5,8 +5,8 @@
package time
import (
"os";
"syscall";
"os"
"syscall"
)
// Sleep pauses the current goroutine for ns nanoseconds.
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -9,5 +9,5 @@ func IsDigit(rune int) bool {
if rune < 0x100 { // quick ASCII (Latin-1, really) check
return '0' <= rune && rune <= '9'
}
return Is(Digit, rune);
return Is(Digit, rune)
}
......@@ -5,8 +5,8 @@
package unicode_test
import (
"testing";
. "unicode";
"testing"
. "unicode"
)
var testDigit = []int{
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment