From 90564a92565877d19e456694ac4e2ef205720432 Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Thu, 14 Jul 2011 14:39:40 -0700 Subject: [PATCH] go/printer: changed max. number of newlines from 3 to 2 manual changes in src/pkg/go/printer, src/cmd/gofix/signal_test.go (cd src/cmd/gofix/testdata; gofmt -w *.in *.out) (cd src/pkg/go/printer; gotest -update) gofmt -w misc src runs all tests R=golang-dev, rsc CC=golang-dev https://golang.org/cl/4715041 --- misc/cgo/gmp/gmp.go | 3 - src/cmd/ebnflint/ebnflint.go | 6 -- src/cmd/godoc/codewalk.go | 12 --- src/cmd/godoc/dirtrees.go | 16 --- src/cmd/godoc/filesystem.go | 11 --- src/cmd/godoc/format.go | 15 --- src/cmd/godoc/godoc.go | 62 ------------ src/cmd/godoc/index.go | 56 ----------- src/cmd/godoc/main.go | 9 -- src/cmd/godoc/mapping.go | 10 -- src/cmd/godoc/parser.go | 1 - src/cmd/godoc/snippet.go | 6 -- src/cmd/godoc/spec.go | 14 --- src/cmd/godoc/utils.go | 8 -- src/cmd/godoc/zip.go | 17 ---- src/cmd/gofix/oserrorstring.go | 1 - src/cmd/gofix/signal_test.go | 2 - src/cmd/gofix/sorthelpers.go | 1 - src/cmd/gofix/sortslice.go | 1 - src/cmd/gofix/testdata/reflect.asn1.go.in | 1 - src/cmd/gofix/testdata/reflect.asn1.go.out | 1 - src/cmd/gofix/testdata/reflect.datafmt.go.in | 21 ---- src/cmd/gofix/testdata/reflect.datafmt.go.out | 21 ---- src/cmd/gofix/testdata/reflect.decode.go.in | 2 - src/cmd/gofix/testdata/reflect.decode.go.out | 2 - src/cmd/gofix/testdata/reflect.dnsmsg.go.in | 2 - src/cmd/gofix/testdata/reflect.dnsmsg.go.out | 2 - src/cmd/gofix/testdata/reflect.print.go.in | 1 - src/cmd/gofix/testdata/reflect.print.go.out | 1 - src/cmd/gofix/testdata/reflect.scan.go.in | 2 - src/cmd/gofix/testdata/reflect.scan.go.out | 2 - src/cmd/gofmt/gofmt.go | 14 --- src/cmd/gofmt/gofmt_test.go | 3 - src/cmd/gofmt/rewrite.go | 10 -- src/cmd/gofmt/simplify.go | 2 - src/cmd/goinstall/main.go | 1 - src/cmd/gotype/gotype.go | 12 --- src/cmd/gotype/gotype_test.go | 3 - src/cmd/govet/govet.go | 1 - src/cmd/hgpatch/main.go | 3 - src/pkg/archive/tar/reader_test.go | 1 - src/pkg/asn1/asn1.go | 1 - src/pkg/big/arith.go | 17 ---- src/pkg/big/arith_test.go | 18 ---- src/pkg/big/calibrate_test.go | 4 - src/pkg/big/hilbert_test.go | 13 --- src/pkg/big/int.go | 45 --------- src/pkg/big/int_test.go | 71 ------------- src/pkg/big/nat.go | 48 --------- src/pkg/big/nat_test.go | 60 ----------- src/pkg/big/rat.go | 28 ------ src/pkg/big/rat_test.go | 12 --- src/pkg/bufio/bufio.go | 3 - src/pkg/bufio/bufio_test.go | 1 - src/pkg/bytes/buffer_test.go | 17 ---- src/pkg/bytes/bytes.go | 1 - src/pkg/bytes/bytes_test.go | 2 - src/pkg/compress/flate/deflate_test.go | 1 - src/pkg/container/heap/heap.go | 6 -- src/pkg/container/heap/heap_test.go | 9 -- src/pkg/container/ring/ring.go | 9 -- src/pkg/container/ring/ring_test.go | 10 -- src/pkg/container/vector/defs.go | 8 -- src/pkg/container/vector/intvector.go | 20 ---- src/pkg/container/vector/intvector_test.go | 13 --- src/pkg/container/vector/nogen_test.go | 9 -- src/pkg/container/vector/numbers_test.go | 8 -- src/pkg/container/vector/stringvector.go | 20 ---- src/pkg/container/vector/stringvector_test.go | 13 --- src/pkg/container/vector/vector.go | 20 ---- src/pkg/container/vector/vector_test.go | 13 --- src/pkg/crypto/ocsp/ocsp.go | 1 - src/pkg/crypto/openpgp/canonical_text_test.go | 1 - .../openpgp/packet/encrypted_key_test.go | 1 - src/pkg/crypto/openpgp/s2k/s2k_test.go | 3 - src/pkg/crypto/tls/handshake_server_test.go | 1 - src/pkg/crypto/tls/key_agreement.go | 1 - src/pkg/crypto/x509/verify.go | 1 - src/pkg/csv/reader.go | 1 - src/pkg/debug/dwarf/type_test.go | 1 - src/pkg/debug/elf/elf.go | 2 - src/pkg/debug/pe/file.go | 2 - src/pkg/ebnf/ebnf.go | 10 -- src/pkg/ebnf/ebnf_test.go | 8 -- src/pkg/ebnf/parser.go | 13 --- src/pkg/encoding/base32/base32_test.go | 1 - src/pkg/encoding/hex/hex.go | 1 - src/pkg/exec/exec_test.go | 1 - src/pkg/exp/datafmt/datafmt.go | 21 ---- src/pkg/exp/datafmt/datafmt_test.go | 21 ---- src/pkg/exp/datafmt/parser.go | 17 ---- src/pkg/exp/regexp/syntax/parse.go | 1 - src/pkg/exp/regexp/syntax/prog.go | 1 - src/pkg/exp/template/funcs.go | 1 - src/pkg/exp/template/parse.go | 1 - src/pkg/exp/template/set_test.go | 1 - src/pkg/expvar/expvar.go | 1 - src/pkg/fmt/fmt_test.go | 2 - src/pkg/fmt/print.go | 1 - src/pkg/fmt/scan.go | 4 - src/pkg/go/ast/ast.go | 42 -------- src/pkg/go/ast/filter.go | 18 ---- src/pkg/go/ast/print.go | 9 -- src/pkg/go/ast/print_test.go | 3 - src/pkg/go/ast/resolve.go | 7 -- src/pkg/go/ast/scope.go | 11 --- src/pkg/go/ast/walk.go | 7 -- src/pkg/go/doc/comment.go | 12 --- src/pkg/go/doc/doc.go | 33 ------- src/pkg/go/parser/interface.go | 8 -- src/pkg/go/parser/parser.go | 99 ------------------- src/pkg/go/parser/parser_test.go | 9 -- src/pkg/go/printer/nodes.go | 41 -------- src/pkg/go/printer/performance_test.go | 4 - src/pkg/go/printer/printer.go | 37 +------ src/pkg/go/printer/printer_test.go | 10 -- src/pkg/go/printer/testdata/comments.golden | 10 -- src/pkg/go/printer/testdata/comments.x | 1 - .../go/printer/testdata/declarations.golden | 22 ----- .../go/printer/testdata/expressions.golden | 23 ----- src/pkg/go/printer/testdata/expressions.raw | 23 ----- src/pkg/go/printer/testdata/parser.go | 99 ------------------- src/pkg/go/printer/testdata/statements.golden | 20 ---- src/pkg/go/scanner/errors.go | 15 --- src/pkg/go/scanner/scanner.go | 22 ----- src/pkg/go/scanner/scanner_test.go | 21 ---- src/pkg/go/token/position.go | 33 ------- src/pkg/go/token/position_test.go | 9 -- src/pkg/go/token/token.go | 8 -- src/pkg/go/typechecker/scope.go | 6 -- src/pkg/go/typechecker/type.go | 7 -- src/pkg/go/typechecker/typechecker.go | 20 ---- src/pkg/go/typechecker/typechecker_test.go | 5 - src/pkg/go/typechecker/universe.go | 2 - src/pkg/go/types/check.go | 7 -- src/pkg/go/types/check_test.go | 9 -- src/pkg/go/types/const.go | 15 --- src/pkg/go/types/exportdata.go | 3 - src/pkg/go/types/gcimporter.go | 39 -------- src/pkg/go/types/gcimporter_test.go | 5 - src/pkg/go/types/testdata/exports.go | 5 - src/pkg/go/types/types.go | 18 ---- src/pkg/go/types/universe.go | 7 -- src/pkg/gob/codec_test.go | 2 - src/pkg/gob/debug.go | 3 - src/pkg/http/cgi/host_test.go | 2 - src/pkg/http/client.go | 1 - src/pkg/http/triv.go | 2 - src/pkg/http/url.go | 2 - src/pkg/index/suffixarray/qsufsort.go | 4 - src/pkg/index/suffixarray/suffixarray.go | 7 -- src/pkg/index/suffixarray/suffixarray_test.go | 9 -- src/pkg/io/ioutil/ioutil_test.go | 1 - src/pkg/json/decode.go | 2 - src/pkg/math/acosh.go | 1 - src/pkg/math/asin.go | 1 - src/pkg/math/asinh.go | 1 - src/pkg/math/atanh.go | 1 - src/pkg/math/erf.go | 1 - src/pkg/math/exp_port.go | 1 - src/pkg/math/expm1.go | 1 - src/pkg/math/floor.go | 1 - src/pkg/math/fmod.go | 1 - src/pkg/math/log1p.go | 1 - src/pkg/math/sin.go | 1 - src/pkg/math/sinh.go | 1 - src/pkg/math/tan.go | 1 - src/pkg/math/tanh.go | 1 - src/pkg/mime/multipart/multipart.go | 1 - src/pkg/net/dnsclient_unix.go | 1 - src/pkg/net/dnsmsg.go | 1 - src/pkg/net/fd_windows.go | 1 - src/pkg/net/interface_windows.go | 1 - src/pkg/net/ipraw_test.go | 1 - src/pkg/os/env_unix.go | 1 - src/pkg/os/file_plan9.go | 2 - src/pkg/os/inotify/inotify_linux.go | 7 -- src/pkg/os/inotify/inotify_linux_test.go | 1 - src/pkg/os/os_test.go | 1 - src/pkg/os/path.go | 1 - src/pkg/os/proc.go | 1 - src/pkg/os/stat_plan9.go | 1 - src/pkg/os/sys_linux.go | 1 - src/pkg/os/sys_plan9.go | 1 - src/pkg/os/time.go | 1 - src/pkg/reflect/all_test.go | 2 - src/pkg/reflect/type.go | 2 - src/pkg/rpc/client.go | 1 - src/pkg/rpc/server.go | 1 - src/pkg/scanner/scanner.go | 30 ------ src/pkg/scanner/scanner_test.go | 23 ----- src/pkg/sort/search.go | 6 -- src/pkg/sort/search_test.go | 8 -- src/pkg/sort/sort.go | 6 -- src/pkg/sort/sort_test.go | 1 - src/pkg/strconv/atoi.go | 2 - src/pkg/strings/reader.go | 1 - src/pkg/strings/strings.go | 1 - src/pkg/strings/strings_test.go | 2 - src/pkg/sync/mutex_test.go | 1 - src/pkg/syscall/exec_unix.go | 1 - src/pkg/syscall/syscall_darwin.go | 1 - src/pkg/syscall/syscall_freebsd.go | 1 - src/pkg/syscall/syscall_plan9.go | 2 - src/pkg/syscall/syscall_unix.go | 1 - src/pkg/syscall/zerrors_darwin_386.go | 1 - src/pkg/syscall/zerrors_darwin_amd64.go | 1 - src/pkg/syscall/zerrors_freebsd_386.go | 1 - src/pkg/syscall/zerrors_freebsd_amd64.go | 1 - src/pkg/syscall/zerrors_linux_386.go | 1 - src/pkg/syscall/zerrors_linux_amd64.go | 1 - src/pkg/syscall/zerrors_linux_arm.go | 1 - src/pkg/syscall/zerrors_plan9_386.go | 1 - src/pkg/tabwriter/tabwriter.go | 25 ----- src/pkg/tabwriter/tabwriter_test.go | 10 -- src/pkg/template/template_test.go | 2 - src/pkg/testing/iotest/reader.go | 1 - src/pkg/testing/testing.go | 1 - src/pkg/time/zoneinfo_unix.go | 2 - src/pkg/unicode/casetables.go | 1 - src/pkg/unicode/maketables.go | 1 - src/pkg/unicode/tables.go | 1 - src/pkg/websocket/server.go | 1 - src/pkg/xml/xml.go | 1 - src/pkg/xml/xml_test.go | 2 - 225 files changed, 1 insertion(+), 2005 deletions(-) diff --git a/misc/cgo/gmp/gmp.go b/misc/cgo/gmp/gmp.go index 7faa71b696..10933498db 100644 --- a/misc/cgo/gmp/gmp.go +++ b/misc/cgo/gmp/gmp.go @@ -211,7 +211,6 @@ func (z *Int) destroy() { z.init = false } - /* * arithmetic */ @@ -300,7 +299,6 @@ func (z *Int) Int64() int64 { return int64(C.mpz_get_si(&z.i[0])) } - // Neg sets z = -x and returns z. func (z *Int) Neg(x *Int) *Int { x.doinit() @@ -317,7 +315,6 @@ func (z *Int) Abs(x *Int) *Int { return z } - /* * functions without a clear receiver */ diff --git a/src/cmd/ebnflint/ebnflint.go b/src/cmd/ebnflint/ebnflint.go index 0b04431568..009b336f39 100644 --- a/src/cmd/ebnflint/ebnflint.go +++ b/src/cmd/ebnflint/ebnflint.go @@ -16,31 +16,26 @@ import ( "path/filepath" ) - var fset = token.NewFileSet() var start = flag.String("start", "Start", "name of start production") - func usage() { fmt.Fprintf(os.Stderr, "usage: ebnflint [flags] [filename]\n") flag.PrintDefaults() os.Exit(1) } - // Markers around EBNF sections in .html files var ( open = []byte(`
`)
 	close = []byte(`
`) ) - func report(err os.Error) { scanner.PrintError(os.Stderr, err) os.Exit(1) } - func extractEBNF(src []byte) []byte { var buf bytes.Buffer @@ -77,7 +72,6 @@ func extractEBNF(src []byte) []byte { return buf.Bytes() } - func main() { flag.Parse() diff --git a/src/cmd/godoc/codewalk.go b/src/cmd/godoc/codewalk.go index 50043e2aba..e2643e4662 100644 --- a/src/cmd/godoc/codewalk.go +++ b/src/cmd/godoc/codewalk.go @@ -28,7 +28,6 @@ import ( "xml" ) - // Handler for /doc/codewalk/ and below. func codewalk(w http.ResponseWriter, r *http.Request) { relpath := r.URL.Path[len("/doc/codewalk/"):] @@ -71,7 +70,6 @@ func codewalk(w http.ResponseWriter, r *http.Request) { servePage(w, "Codewalk: "+cw.Title, "", "", b) } - // A Codewalk represents a single codewalk read from an XML file. type Codewalk struct { Title string `xml:"attr"` @@ -79,7 +77,6 @@ type Codewalk struct { Step []*Codestep } - // A Codestep is a single step in a codewalk. type Codestep struct { // Filled in from XML @@ -97,7 +94,6 @@ type Codestep struct { Data []byte } - // String method for printing in template. // Formats file address nicely. func (st *Codestep) String() string { @@ -111,7 +107,6 @@ func (st *Codestep) String() string { return s } - // loadCodewalk reads a codewalk from the named XML file. func loadCodewalk(filename string) (*Codewalk, os.Error) { f, err := fs.Open(filename) @@ -173,7 +168,6 @@ func loadCodewalk(filename string) (*Codewalk, os.Error) { return cw, nil } - // codewalkDir serves the codewalk directory listing. // It scans the directory for subdirectories or files named *.xml // and prepares a table. @@ -207,7 +201,6 @@ func codewalkDir(w http.ResponseWriter, r *http.Request, relpath, abspath string servePage(w, "Codewalks", "", "", b) } - // codewalkFileprint serves requests with ?fileprint=f&lo=lo&hi=hi. // The filename f has already been retrieved and is passed as an argument. // Lo and hi are the numbers of the first and last line to highlight @@ -256,7 +249,6 @@ func codewalkFileprint(w http.ResponseWriter, r *http.Request, f string) { io.WriteString(w, "") } - // addrToByte evaluates the given address starting at offset start in data. // It returns the lo and hi byte offset of the matched region within data. // See http://plan9.bell-labs.com/sys/doc/sam/sam.html Table II @@ -351,7 +343,6 @@ func addrToByteRange(addr string, start int, data []byte) (lo, hi int, err os.Er return lo, hi, nil } - // addrNumber applies the given dir, n, and charOffset to the address lo, hi. // dir is '+' or '-', n is the count, and charOffset is true if the syntax // used was #n. Applying +n (or +#n) means to advance n lines @@ -437,7 +428,6 @@ func addrNumber(data []byte, lo, hi int, dir byte, n int, charOffset bool) (int, return 0, 0, os.NewError("address out of range") } - // addrRegexp searches for pattern in the given direction starting at lo, hi. // The direction dir is '+' (search forward from hi) or '-' (search backward from lo). // Backward searches are unimplemented. @@ -465,7 +455,6 @@ func addrRegexp(data []byte, lo, hi int, dir byte, pattern string) (int, int, os return m[0], m[1], nil } - // lineToByte returns the byte index of the first byte of line n. // Line numbers begin at 1. func lineToByte(data []byte, n int) int { @@ -483,7 +472,6 @@ func lineToByte(data []byte, n int) int { return len(data) } - // byteToLine returns the number of the line containing the byte at index i. func byteToLine(data []byte, i int) int { l := 1 diff --git a/src/cmd/godoc/dirtrees.go b/src/cmd/godoc/dirtrees.go index e98e93a461..aa590b363d 100644 --- a/src/cmd/godoc/dirtrees.go +++ b/src/cmd/godoc/dirtrees.go @@ -17,7 +17,6 @@ import ( "unicode" ) - type Directory struct { Depth int Path string // includes Name @@ -26,7 +25,6 @@ type Directory struct { Dirs []*Directory // subdirectories } - func isGoFile(fi FileInfo) bool { name := fi.Name() return fi.IsRegular() && @@ -34,20 +32,17 @@ func isGoFile(fi FileInfo) bool { filepath.Ext(name) == ".go" } - func isPkgFile(fi FileInfo) bool { return isGoFile(fi) && !strings.HasSuffix(fi.Name(), "_test.go") // ignore test files } - func isPkgDir(fi FileInfo) bool { name := fi.Name() return fi.IsDirectory() && len(name) > 0 && name[0] != '_' && name[0] != '.' // ignore _files and .files } - func firstSentence(s string) string { i := -1 // index+1 of first terminator (punctuation ending a sentence) j := -1 // index+1 of first terminator followed by white space @@ -83,13 +78,11 @@ func firstSentence(s string) string { return s[0:j] } - type treeBuilder struct { pathFilter func(string) bool maxDepth int } - func (b *treeBuilder) newDirTree(fset *token.FileSet, path, name string, depth int) *Directory { if b.pathFilter != nil && !b.pathFilter(path) { return nil @@ -185,7 +178,6 @@ func (b *treeBuilder) newDirTree(fset *token.FileSet, path, name string, depth i return &Directory{depth, path, name, synopsis, dirs} } - // newDirectory creates a new package directory tree with at most maxDepth // levels, anchored at root. The result tree is pruned such that it only // contains directories that contain package files or that contain @@ -218,7 +210,6 @@ func newDirectory(root string, pathFilter func(string) bool, maxDepth int) *Dire return b.newDirTree(token.NewFileSet(), root, d.Name(), 0) } - func (dir *Directory) writeLeafs(buf *bytes.Buffer) { if dir != nil { if len(dir.Dirs) == 0 { @@ -233,7 +224,6 @@ func (dir *Directory) writeLeafs(buf *bytes.Buffer) { } } - func (dir *Directory) walk(c chan<- *Directory, skipRoot bool) { if dir != nil { if !skipRoot { @@ -245,7 +235,6 @@ func (dir *Directory) walk(c chan<- *Directory, skipRoot bool) { } } - func (dir *Directory) iter(skipRoot bool) <-chan *Directory { c := make(chan *Directory) go func() { @@ -255,7 +244,6 @@ func (dir *Directory) iter(skipRoot bool) <-chan *Directory { return c } - func (dir *Directory) lookupLocal(name string) *Directory { for _, d := range dir.Dirs { if d.Name == name { @@ -265,7 +253,6 @@ func (dir *Directory) lookupLocal(name string) *Directory { return nil } - // lookup looks for the *Directory for a given path, relative to dir. func (dir *Directory) lookup(path string) *Directory { d := strings.Split(dir.Path, string(filepath.Separator)) @@ -284,7 +271,6 @@ func (dir *Directory) lookup(path string) *Directory { return dir } - // DirEntry describes a directory entry. The Depth and Height values // are useful for presenting an entry in an indented fashion. // @@ -296,13 +282,11 @@ type DirEntry struct { Synopsis string } - type DirList struct { MaxHeight int // directory tree height, > 0 List []DirEntry } - // listing creates a (linear) directory listing from a directory tree. // If skipRoot is set, the root directory itself is excluded from the list. // diff --git a/src/cmd/godoc/filesystem.go b/src/cmd/godoc/filesystem.go index 62430e3844..e9b5fe3c82 100644 --- a/src/cmd/godoc/filesystem.go +++ b/src/cmd/godoc/filesystem.go @@ -15,7 +15,6 @@ import ( "os" ) - // The FileInfo interface provides access to file information. type FileInfo interface { Name() string @@ -24,7 +23,6 @@ type FileInfo interface { IsDirectory() bool } - // The FileSystem interface specifies the methods godoc is using // to access the file system for which it serves documentation. type FileSystem interface { @@ -35,24 +33,20 @@ type FileSystem interface { ReadFile(path string) ([]byte, os.Error) } - // ---------------------------------------------------------------------------- // OS-specific FileSystem implementation var OS FileSystem = osFS{} - // osFI is the OS-specific implementation of FileInfo. type osFI struct { *os.FileInfo } - func (fi osFI) Name() string { return fi.FileInfo.Name } - func (fi osFI) Size() int64 { if fi.IsDirectory() { return 0 @@ -60,7 +54,6 @@ func (fi osFI) Size() int64 { return fi.FileInfo.Size } - // osFS is the OS-specific implementation of FileSystem type osFS struct{} @@ -79,19 +72,16 @@ func (osFS) Open(path string) (io.ReadCloser, os.Error) { return f, nil } - func (osFS) Lstat(path string) (FileInfo, os.Error) { fi, err := os.Lstat(path) return osFI{fi}, err } - func (osFS) Stat(path string) (FileInfo, os.Error) { fi, err := os.Stat(path) return osFI{fi}, err } - func (osFS) ReadDir(path string) ([]FileInfo, os.Error) { l0, err := ioutil.ReadDir(path) // l0 is sorted if err != nil { @@ -104,7 +94,6 @@ func (osFS) ReadDir(path string) ([]FileInfo, os.Error) { return l1, nil } - func (osFS) ReadFile(path string) ([]byte, os.Error) { return ioutil.ReadFile(path) } diff --git a/src/cmd/godoc/format.go b/src/cmd/godoc/format.go index 7e64708467..78dde4166f 100644 --- a/src/cmd/godoc/format.go +++ b/src/cmd/godoc/format.go @@ -20,7 +20,6 @@ import ( "template" ) - // ---------------------------------------------------------------------------- // Implementation of FormatSelections @@ -34,13 +33,11 @@ import ( // type Selection func() []int - // A LinkWriter writes some start or end "tag" to w for the text offset offs. // It is called by FormatSelections at the start or end of each link segment. // type LinkWriter func(w io.Writer, offs int, start bool) - // A SegmentWriter formats a text according to selections and writes it to w. // The selections parameter is a bit set indicating which selections provided // to FormatSelections overlap with the text segment: If the n'th bit is set @@ -49,7 +46,6 @@ type LinkWriter func(w io.Writer, offs int, start bool) // type SegmentWriter func(w io.Writer, text []byte, selections int) - // FormatSelections takes a text and writes it to w using link and segment // writers lw and sw as follows: lw is invoked for consecutive segment starts // and ends as specified through the links selection, and sw is invoked for @@ -138,7 +134,6 @@ func FormatSelections(w io.Writer, text []byte, lw LinkWriter, links Selection, flush() } - // A merger merges a slice of Selections and produces a sequence of // consecutive segment change events through repeated next() calls. // @@ -147,7 +142,6 @@ type merger struct { segments [][]int // segments[i] is the next segment of selections[i] } - const infinity int = 2e9 func newMerger(selections []Selection) *merger { @@ -163,7 +157,6 @@ func newMerger(selections []Selection) *merger { return &merger{selections, segments} } - // next returns the next segment change: index specifies the Selection // to which the segment belongs, offs is the segment start or end offset // as determined by the start value. If there are no more segment changes, @@ -208,7 +201,6 @@ func (m *merger) next() (index, offs int, start bool) { return } - // ---------------------------------------------------------------------------- // Implementation of FormatText @@ -232,7 +224,6 @@ func lineSelection(text []byte) Selection { } } - // commentSelection returns the sequence of consecutive comments // in the Go src text as a Selection. // @@ -257,7 +248,6 @@ func commentSelection(src []byte) Selection { } } - // makeSelection is a helper function to make a Selection from a slice of pairs. func makeSelection(matches [][]int) Selection { return func() (seg []int) { @@ -269,7 +259,6 @@ func makeSelection(matches [][]int) Selection { } } - // regexpSelection computes the Selection for the regular expression expr in text. func regexpSelection(text []byte, expr string) Selection { var matches [][]int @@ -279,7 +268,6 @@ func regexpSelection(text []byte, expr string) Selection { return makeSelection(matches) } - var selRx = regexp.MustCompile(`^([0-9]+):([0-9]+)`) // rangeSelection computes the Selection for a text range described @@ -298,7 +286,6 @@ func rangeSelection(str string) Selection { return nil } - // Span tags for all the possible selection combinations that may // be generated by FormatText. Selections are indicated by a bitset, // and the value of the bitset specifies the tag to be used. @@ -320,7 +307,6 @@ var startTags = [][]byte{ var endTag = []byte(``) - func selectionTag(w io.Writer, text []byte, selections int) { if selections < len(startTags) { if tag := startTags[selections]; len(tag) > 0 { @@ -333,7 +319,6 @@ func selectionTag(w io.Writer, text []byte, selections int) { template.HTMLEscape(w, text) } - // FormatText HTML-escapes text and writes it to w. // Consecutive text segments are wrapped in HTML spans (with tags as // defined by startTags and endTag) as follows: diff --git a/src/cmd/godoc/godoc.go b/src/cmd/godoc/godoc.go index 771c8e6165..67441f304f 100644 --- a/src/cmd/godoc/godoc.go +++ b/src/cmd/godoc/godoc.go @@ -27,7 +27,6 @@ import ( "time" ) - // ---------------------------------------------------------------------------- // Globals @@ -35,7 +34,6 @@ type delayTime struct { RWValue } - func (dt *delayTime) backoff(max int) { dt.mutex.Lock() v := dt.value.(int) * 2 @@ -47,7 +45,6 @@ func (dt *delayTime) backoff(max int) { dt.mutex.Unlock() } - var ( verbose = flag.Bool("v", false, "verbose mode") @@ -82,7 +79,6 @@ var ( pkgHandler httpHandler ) - func initHandlers() { paths := filepath.SplitList(*pkgPath) for _, t := range build.Path { @@ -98,7 +94,6 @@ func initHandlers() { pkgHandler = httpHandler{"/pkg/", filepath.Join(*goroot, "src", "pkg"), true} } - func registerPublicHandlers(mux *http.ServeMux) { mux.Handle(cmdHandler.pattern, &cmdHandler) mux.Handle(pkgHandler.pattern, &pkgHandler) @@ -108,13 +103,11 @@ func registerPublicHandlers(mux *http.ServeMux) { mux.HandleFunc("/", serveFile) } - func initFSTree() { fsTree.set(newDirectory(filepath.Join(*goroot, *testDir), nil, -1)) invalidateIndex() } - // ---------------------------------------------------------------------------- // Directory filters @@ -125,7 +118,6 @@ func isParentOf(p, q string) bool { return strings.HasPrefix(q, p) && (len(q) <= n || q[n] == '/') } - func setPathFilter(list []string) { if len(list) == 0 { pathFilter.set(nil) @@ -142,7 +134,6 @@ func setPathFilter(list []string) { }) } - func getPathFilter() func(string) bool { f, _ := pathFilter.get() if f != nil { @@ -151,7 +142,6 @@ func getPathFilter() func(string) bool { return nil } - // readDirList reads a file containing a newline-separated list // of directory paths and returns the list of paths. func readDirList(filename string) ([]string, os.Error) { @@ -182,7 +172,6 @@ func readDirList(filename string) ([]string, os.Error) { return list[0:i], err } - // updateMappedDirs computes the directory tree for // each user-defined file system mapping. If a filter // is provided, it is used to filter directories. @@ -197,7 +186,6 @@ func updateMappedDirs(filter func(string) bool) { } } - func updateFilterFile() { updateMappedDirs(nil) // no filter for accuracy @@ -220,7 +208,6 @@ func updateFilterFile() { } } - func initDirTrees() { // setup initial path filter if *filter != "" { @@ -255,7 +242,6 @@ func initDirTrees() { } } - // ---------------------------------------------------------------------------- // Path mapping @@ -271,7 +257,6 @@ func absolutePath(relpath, defaultRoot string) string { return abspath } - func relativeURL(abspath string) string { relpath := fsMap.ToRelative(abspath) if relpath == "" { @@ -293,7 +278,6 @@ func relativeURL(abspath string) string { return relpath } - // ---------------------------------------------------------------------------- // Tab conversion @@ -311,7 +295,6 @@ type tconv struct { indent int // valid if state == indenting } - func (p *tconv) writeIndent() (err os.Error) { i := p.indent for i >= len(spaces) { @@ -327,7 +310,6 @@ func (p *tconv) writeIndent() (err os.Error) { return } - func (p *tconv) Write(data []byte) (n int, err os.Error) { if len(data) == 0 { return @@ -371,7 +353,6 @@ func (p *tconv) Write(data []byte) (n int, err os.Error) { return } - // ---------------------------------------------------------------------------- // Templates @@ -389,7 +370,6 @@ func writeNode(w io.Writer, fset *token.FileSet, x interface{}) { (&printer.Config{mode, *tabwidth}).Fprint(&tconv{output: w}, fset, x) } - // Write anything to w. func writeAny(w io.Writer, fset *token.FileSet, x interface{}) { switch v := x.(type) { @@ -404,7 +384,6 @@ func writeAny(w io.Writer, fset *token.FileSet, x interface{}) { } } - // Write anything html-escaped to w. func writeAnyHTML(w io.Writer, fset *token.FileSet, x interface{}) { switch v := x.(type) { @@ -423,7 +402,6 @@ func writeAnyHTML(w io.Writer, fset *token.FileSet, x interface{}) { } } - func fileset(x []interface{}) *token.FileSet { if len(x) > 1 { if fset, ok := x[1].(*token.FileSet); ok { @@ -433,13 +411,11 @@ func fileset(x []interface{}) *token.FileSet { return nil } - // Template formatter for "html-esc" format. func htmlEscFmt(w io.Writer, format string, x ...interface{}) { writeAnyHTML(w, fileset(x), x[0]) } - // Template formatter for "html-comment" format. func htmlCommentFmt(w io.Writer, format string, x ...interface{}) { var buf bytes.Buffer @@ -449,13 +425,11 @@ func htmlCommentFmt(w io.Writer, format string, x ...interface{}) { doc.ToHTML(w, buf.Bytes(), nil) // does html-escaping } - // Template formatter for "" (default) format. func textFmt(w io.Writer, format string, x ...interface{}) { writeAny(w, fileset(x), x[0]) } - // Template formatter for "urlquery-esc" format. func urlQueryEscFmt(w io.Writer, format string, x ...interface{}) { var buf bytes.Buffer @@ -463,7 +437,6 @@ func urlQueryEscFmt(w io.Writer, format string, x ...interface{}) { template.HTMLEscape(w, []byte(http.URLEscape(string(buf.Bytes())))) } - // Template formatter for the various "url-xxx" formats excluding url-esc. func urlFmt(w io.Writer, format string, x ...interface{}) { var path string @@ -536,7 +509,6 @@ func urlFmt(w io.Writer, format string, x ...interface{}) { } } - // The strings in infoKinds must be properly html-escaped. var infoKinds = [nKinds]string{ PackageClause: "package clause", @@ -549,13 +521,11 @@ var infoKinds = [nKinds]string{ Use: "use", } - // Template formatter for "infoKind" format. func infoKindFmt(w io.Writer, format string, x ...interface{}) { fmt.Fprintf(w, infoKinds[x[0].(SpotKind)]) // infoKind entries are html-escaped } - // Template formatter for "infoLine" format. func infoLineFmt(w io.Writer, format string, x ...interface{}) { info := x[0].(SpotInfo) @@ -575,7 +545,6 @@ func infoLineFmt(w io.Writer, format string, x ...interface{}) { fmt.Fprintf(w, "%d", line) } - // Template formatter for "infoSnippet" format. func infoSnippetFmt(w io.Writer, format string, x ...interface{}) { info := x[0].(SpotInfo) @@ -589,7 +558,6 @@ func infoSnippetFmt(w io.Writer, format string, x ...interface{}) { w.Write(text) } - // Template formatter for "padding" format. func paddingFmt(w io.Writer, format string, x ...interface{}) { for i := x[0].(int); i > 0; i-- { @@ -597,13 +565,11 @@ func paddingFmt(w io.Writer, format string, x ...interface{}) { } } - // Template formatter for "time" format. func timeFmt(w io.Writer, format string, x ...interface{}) { template.HTMLEscape(w, []byte(time.SecondsToLocalTime(x[0].(int64)/1e9).String())) } - // Template formatter for "dir/" format. func dirslashFmt(w io.Writer, format string, x ...interface{}) { if x[0].(FileInfo).IsDirectory() { @@ -611,21 +577,18 @@ func dirslashFmt(w io.Writer, format string, x ...interface{}) { } } - // Template formatter for "localname" format. func localnameFmt(w io.Writer, format string, x ...interface{}) { _, localname := filepath.Split(x[0].(string)) template.HTMLEscape(w, []byte(localname)) } - // Template formatter for "numlines" format. func numlinesFmt(w io.Writer, format string, x ...interface{}) { list := x[0].([]int) fmt.Fprintf(w, "%d", len(list)) } - var fmap = template.FormatterMap{ "": textFmt, "html-esc": htmlEscFmt, @@ -644,7 +607,6 @@ var fmap = template.FormatterMap{ "numlines": numlinesFmt, } - func readTemplate(name string) *template.Template { path := filepath.Join(*goroot, "lib", "godoc", name) if *templateDir != "" { @@ -666,7 +628,6 @@ func readTemplate(name string) *template.Template { return t } - var ( codewalkHTML, codewalkdirHTML, @@ -692,7 +653,6 @@ func readTemplates() { searchText = readTemplate("search.txt") } - // ---------------------------------------------------------------------------- // Generic HTML wrapper @@ -722,13 +682,11 @@ func servePage(w http.ResponseWriter, title, subtitle, query string, content []b } } - func serveText(w http.ResponseWriter, text []byte) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Write(text) } - // ---------------------------------------------------------------------------- // Files @@ -738,7 +696,6 @@ var ( firstCommentRx = regexp.MustCompile(``) ) - func extractString(src []byte, rx *regexp.Regexp) (s string) { m := rx.FindSubmatch(src) if m != nil { @@ -747,7 +704,6 @@ func extractString(src []byte, rx *regexp.Regexp) (s string) { return } - func serveHTMLDoc(w http.ResponseWriter, r *http.Request, abspath, relpath string) { // get HTML body contents src, err := fs.ReadFile(abspath) @@ -782,7 +738,6 @@ func serveHTMLDoc(w http.ResponseWriter, r *http.Request, abspath, relpath strin servePage(w, title, subtitle, "", src) } - func applyTemplate(t *template.Template, name string, data interface{}) []byte { var buf bytes.Buffer if err := t.Execute(&buf, data); err != nil { @@ -791,7 +746,6 @@ func applyTemplate(t *template.Template, name string, data interface{}) []byte { return buf.Bytes() } - func redirect(w http.ResponseWriter, r *http.Request) (redirected bool) { if canonical := path.Clean(r.URL.Path) + "/"; r.URL.Path != canonical { http.Redirect(w, r, canonical, http.StatusMovedPermanently) @@ -816,7 +770,6 @@ func serveTextFile(w http.ResponseWriter, r *http.Request, abspath, relpath, tit servePage(w, title+" "+relpath, "", "", buf.Bytes()) } - func serveDirectory(w http.ResponseWriter, r *http.Request, abspath, relpath string) { if redirect(w, r) { return @@ -833,7 +786,6 @@ func serveDirectory(w http.ResponseWriter, r *http.Request, abspath, relpath str servePage(w, "Directory "+relpath, "", "", contents) } - func serveFile(w http.ResponseWriter, r *http.Request) { relpath := r.URL.Path[1:] // serveFile URL paths start with '/' abspath := absolutePath(relpath, *goroot) @@ -893,7 +845,6 @@ func serveFile(w http.ResponseWriter, r *http.Request) { fileServer.ServeHTTP(w, r) } - // ---------------------------------------------------------------------------- // Packages @@ -908,7 +859,6 @@ const ( genDoc // generate documentation ) - type PageInfo struct { Dirname string // directory containing the package PList []string // list of package names found @@ -921,19 +871,16 @@ type PageInfo struct { Err os.Error // directory read error or nil } - func (info *PageInfo) IsEmpty() bool { return info.Err != nil || info.PAst == nil && info.PDoc == nil && info.Dirs == nil } - type httpHandler struct { pattern string // url pattern; e.g. "/pkg/" fsRoot string // file system root to which the pattern is mapped isPkg bool // true if this handler serves real package documentation (as opposed to command documentation) } - // getPageInfo returns the PageInfo for a package directory abspath. If the // parameter genAST is set, an AST containing only the package exports is // computed (PageInfo.PAst), otherwise package documentation (PageInfo.Doc) @@ -1072,7 +1019,6 @@ func (h *httpHandler) getPageInfo(abspath, relpath, pkgname string, mode PageInf return PageInfo{abspath, plist, fset, past, pdoc, dir.listing(true), timestamp, h.isPkg, nil} } - func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if redirect(w, r) { return @@ -1123,7 +1069,6 @@ func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { servePage(w, title, subtitle, "", contents) } - // ---------------------------------------------------------------------------- // Search @@ -1143,7 +1088,6 @@ type SearchResult struct { Complete bool // true if all textual occurrences of Query are reported } - func lookup(query string) (result SearchResult) { result.Query = query @@ -1195,7 +1139,6 @@ func lookup(query string) (result SearchResult) { return } - func search(w http.ResponseWriter, r *http.Request) { query := strings.TrimSpace(r.FormValue("q")) result := lookup(query) @@ -1217,7 +1160,6 @@ func search(w http.ResponseWriter, r *http.Request) { servePage(w, title, "", query, contents) } - // ---------------------------------------------------------------------------- // Indexer @@ -1228,7 +1170,6 @@ func invalidateIndex() { fsModified.set(nil) } - // indexUpToDate() returns true if the search index is not older // than any of the file systems under godoc's observation. // @@ -1238,7 +1179,6 @@ func indexUpToDate() bool { return fsTime <= siTime } - // feedDirnames feeds the directory names of all directories // under the file system given by root to channel c. // @@ -1250,7 +1190,6 @@ func feedDirnames(root *RWValue, c chan<- string) { } } - // fsDirnames() returns a channel sending all directory names // of all the file systems under godoc's observation. // @@ -1267,7 +1206,6 @@ func fsDirnames() <-chan string { return c } - func indexer() { for { if !indexUpToDate() { diff --git a/src/cmd/godoc/index.go b/src/cmd/godoc/index.go index c724d71fb2..9b4f31514c 100644 --- a/src/cmd/godoc/index.go +++ b/src/cmd/godoc/index.go @@ -52,7 +52,6 @@ import ( "strings" ) - // ---------------------------------------------------------------------------- // RunList @@ -69,13 +68,11 @@ type RunList struct { func (h *RunList) Less(i, j int) bool { return h.less(h.At(i), h.At(j)) } - func (h *RunList) sort(less func(x, y interface{}) bool) { h.less = less sort.Sort(h) } - // Compress entries which are the same according to a sort criteria // (specified by less) into "runs". func (h *RunList) reduce(less func(x, y interface{}) bool, newRun func(h *RunList, i, j int) interface{}) *RunList { @@ -99,7 +96,6 @@ func (h *RunList) reduce(less func(x, y interface{}) bool, newRun func(h *RunLis return &hh } - // ---------------------------------------------------------------------------- // SpotInfo @@ -130,7 +126,6 @@ const ( nKinds ) - func init() { // sanity check: if nKinds is too large, the SpotInfo // accessor functions may need to be updated @@ -139,7 +134,6 @@ func init() { } } - // makeSpotInfo makes a SpotInfo. func makeSpotInfo(kind SpotKind, lori int, isIndex bool) SpotInfo { // encode lori: bits [4..32) @@ -159,12 +153,10 @@ func makeSpotInfo(kind SpotKind, lori int, isIndex bool) SpotInfo { return x } - func (x SpotInfo) Kind() SpotKind { return SpotKind(x >> 1 & 7) } func (x SpotInfo) Lori() int { return int(x >> 4) } func (x SpotInfo) IsIndex() bool { return x&1 != 0 } - // ---------------------------------------------------------------------------- // KindRun @@ -177,18 +169,15 @@ type KindRun struct { Infos []SpotInfo } - // KindRuns are sorted by line number or index. Since the isIndex bit // is always the same for all infos in one list we can compare lori's. func (f *KindRun) Len() int { return len(f.Infos) } func (f *KindRun) Less(i, j int) bool { return f.Infos[i].Lori() < f.Infos[j].Lori() } func (f *KindRun) Swap(i, j int) { f.Infos[i], f.Infos[j] = f.Infos[j], f.Infos[i] } - // FileRun contents are sorted by Kind for the reduction into KindRuns. func lessKind(x, y interface{}) bool { return x.(SpotInfo).Kind() < y.(SpotInfo).Kind() } - // newKindRun allocates a new KindRun from the SpotInfo run [i, j) in h. func newKindRun(h *RunList, i, j int) interface{} { kind := h.At(i).(SpotInfo).Kind() @@ -224,7 +213,6 @@ func newKindRun(h *RunList, i, j int) interface{} { return run } - // ---------------------------------------------------------------------------- // FileRun @@ -239,32 +227,27 @@ func (p *Pak) less(q *Pak) bool { return p.Name < q.Name || p.Name == q.Name && p.Path < q.Path } - // A File describes a Go file. type File struct { Path string // complete file name Pak Pak // the package to which the file belongs } - // A Spot describes a single occurrence of a word. type Spot struct { File *File Info SpotInfo } - // A FileRun is a list of KindRuns belonging to the same file. type FileRun struct { File *File Groups []*KindRun } - // Spots are sorted by path for the reduction into FileRuns. func lessSpot(x, y interface{}) bool { return x.(Spot).File.Path < y.(Spot).File.Path } - // newFileRun allocates a new FileRun from the Spot run [i, j) in h. func newFileRun(h0 *RunList, i, j int) interface{} { file := h0.At(i).(Spot).File @@ -287,7 +270,6 @@ func newFileRun(h0 *RunList, i, j int) interface{} { return &FileRun{file, groups} } - // ---------------------------------------------------------------------------- // PakRun @@ -302,13 +284,11 @@ func (p *PakRun) Len() int { return len(p.Files) } func (p *PakRun) Less(i, j int) bool { return p.Files[i].File.Path < p.Files[j].File.Path } func (p *PakRun) Swap(i, j int) { p.Files[i], p.Files[j] = p.Files[j], p.Files[i] } - // FileRuns are sorted by package for the reduction into PakRuns. func lessFileRun(x, y interface{}) bool { return x.(*FileRun).File.Pak.less(&y.(*FileRun).File.Pak) } - // newPakRun allocates a new PakRun from the *FileRun run [i, j) in h. func newPakRun(h *RunList, i, j int) interface{} { pak := h.At(i).(*FileRun).File.Pak @@ -323,18 +303,15 @@ func newPakRun(h *RunList, i, j int) interface{} { return run } - // ---------------------------------------------------------------------------- // HitList // A HitList describes a list of PakRuns. type HitList []*PakRun - // PakRuns are sorted by package. func lessPakRun(x, y interface{}) bool { return x.(*PakRun).Pak.less(&y.(*PakRun).Pak) } - func reduce(h0 *RunList) HitList { // reduce a list of Spots into a list of FileRuns h1 := h0.reduce(lessSpot, newFileRun) @@ -350,7 +327,6 @@ func reduce(h0 *RunList) HitList { return h } - func (h HitList) filter(pakname string) HitList { // determine number of matching packages (most of the time just one) n := 0 @@ -371,7 +347,6 @@ func (h HitList) filter(pakname string) HitList { return hh } - // ---------------------------------------------------------------------------- // AltWords @@ -380,7 +355,6 @@ type wordPair struct { alt string // alternative spelling } - // An AltWords describes a list of alternative spellings for a // canonical (all lowercase) spelling of a word. type AltWords struct { @@ -388,11 +362,9 @@ type AltWords struct { Alts []string // alternative spelling for the same word } - // wordPairs are sorted by their canonical spelling. func lessWordPair(x, y interface{}) bool { return x.(*wordPair).canon < y.(*wordPair).canon } - // newAltWords allocates a new AltWords from the *wordPair run [i, j) in h. func newAltWords(h *RunList, i, j int) interface{} { canon := h.At(i).(*wordPair).canon @@ -405,7 +377,6 @@ func newAltWords(h *RunList, i, j int) interface{} { return &AltWords{canon, alts} } - func (a *AltWords) filter(s string) *AltWords { if len(a.Alts) == 1 && a.Alts[0] == s { // there are no different alternatives @@ -424,7 +395,6 @@ func (a *AltWords) filter(s string) *AltWords { return &AltWords{a.Canon, alts[0:i]} } - // ---------------------------------------------------------------------------- // Indexer @@ -432,13 +402,11 @@ func (a *AltWords) filter(s string) *AltWords { const includeMainPackages = true const includeTestFiles = true - type IndexResult struct { Decls RunList // package-level declarations (with snippets) Others RunList // all other occurrences } - // Statistics provides statistics information for an index. type Statistics struct { Bytes int // total size of indexed source files @@ -448,7 +416,6 @@ type Statistics struct { Spots int // number of identifier occurrences } - // An Indexer maintains the data structures and provides the machinery // for indexing .go files under a file tree. It implements the path.Visitor // interface for walking file trees, and the ast.Visitor interface for @@ -464,21 +431,18 @@ type Indexer struct { stats Statistics } - func (x *Indexer) addSnippet(s *Snippet) int { index := x.snippets.Len() x.snippets.Push(s) return index } - func (x *Indexer) visitComment(c *ast.CommentGroup) { if c != nil { ast.Walk(x, c) } } - func (x *Indexer) visitIdent(kind SpotKind, id *ast.Ident) { if id != nil { lists, found := x.words[id.Name] @@ -502,7 +466,6 @@ func (x *Indexer) visitIdent(kind SpotKind, id *ast.Ident) { } } - func (x *Indexer) visitSpec(spec ast.Spec, isVarDecl bool) { switch n := spec.(type) { case *ast.ImportSpec: @@ -534,7 +497,6 @@ func (x *Indexer) visitSpec(spec ast.Spec, isVarDecl bool) { } } - func (x *Indexer) Visit(node ast.Node) ast.Visitor { // TODO(gri): methods in interface types are categorized as VarDecl switch n := node.(type) { @@ -606,7 +568,6 @@ func (x *Indexer) Visit(node ast.Node) ast.Visitor { return nil } - func pkgName(filename string) string { // use a new file set each time in order to not pollute the indexer's // file set (which must stay in sync with the concatenated source code) @@ -617,7 +578,6 @@ func pkgName(filename string) string { return file.Name.Name } - // addFile adds a file to the index if possible and returns the file set file // and the file's AST if it was successfully parsed as a Go file. If addFile // failed (that is, if the file was not added), it returns file == nil. @@ -679,7 +639,6 @@ func (x *Indexer) addFile(filename string, goFile bool) (file *token.File, ast * return } - // Design note: Using an explicit white list of permitted files for indexing // makes sure that the important files are included and massively reduces the // number of files to index. The advantage over a blacklist is that unexpected @@ -712,7 +671,6 @@ var whitelisted = map[string]bool{ "README": true, } - // isWhitelisted returns true if a file is on the list // of "permitted" files for indexing. The filename must // be the directory-local name of the file. @@ -725,7 +683,6 @@ func isWhitelisted(filename string) bool { return whitelisted[key] } - func (x *Indexer) visitFile(dirname string, f FileInfo, fulltextIndex bool) { if !f.IsRegular() { return @@ -768,7 +725,6 @@ func (x *Indexer) visitFile(dirname string, f FileInfo, fulltextIndex bool) { x.stats.Lines += file.LineCount() } - // ---------------------------------------------------------------------------- // Index @@ -777,7 +733,6 @@ type LookupResult struct { Others HitList // all other occurrences } - type Index struct { fset *token.FileSet // file set used during indexing; nil if no textindex suffixes *suffixarray.Index // suffixes for concatenated sources; nil if no textindex @@ -787,10 +742,8 @@ type Index struct { stats Statistics } - func canonical(w string) string { return strings.ToLower(w) } - // NewIndex creates a new index for the .go files // in the directories given by dirnames. // @@ -865,13 +818,11 @@ func NewIndex(dirnames <-chan string, fulltextIndex bool) *Index { return &Index{x.fset, suffixes, words, alts, snippets, x.stats} } - // Stats() returns index statistics. func (x *Index) Stats() Statistics { return x.stats } - func (x *Index) LookupWord(w string) (match *LookupResult, alt *AltWords) { match = x.words[w] alt = x.alts[canonical(w)] @@ -884,7 +835,6 @@ func (x *Index) LookupWord(w string) (match *LookupResult, alt *AltWords) { return } - func isIdentifier(s string) bool { var S scanner.Scanner fset := token.NewFileSet() @@ -896,7 +846,6 @@ func isIdentifier(s string) bool { return false } - // For a given query, which is either a single identifier or a qualified // identifier, Lookup returns a LookupResult, and a list of alternative // spellings, if any. If the query syntax is wrong, an error is reported. @@ -932,7 +881,6 @@ func (x *Index) Lookup(query string) (match *LookupResult, alt *AltWords, err os return } - func (x *Index) Snippet(i int) *Snippet { // handle illegal snippet indices gracefully if 0 <= i && i < len(x.snippets) { @@ -941,7 +889,6 @@ func (x *Index) Snippet(i int) *Snippet { return nil } - type positionList []struct { filename string line int @@ -951,7 +898,6 @@ func (list positionList) Len() int { return len(list) } func (list positionList) Less(i, j int) bool { return list[i].filename < list[j].filename } func (list positionList) Swap(i, j int) { list[i], list[j] = list[j], list[i] } - // unique returns the list sorted and with duplicate entries removed func unique(list []int) []int { sort.Ints(list) @@ -967,14 +913,12 @@ func unique(list []int) []int { return list[0:i] } - // A FileLines value specifies a file and line numbers within that file. type FileLines struct { Filename string Lines []int } - // LookupRegexp returns the number of matches and the matches where a regular // expression r is found in the full text index. At most n matches are // returned (thus found <= n). diff --git a/src/cmd/godoc/main.go b/src/cmd/godoc/main.go index 6455ec235d..f984719659 100644 --- a/src/cmd/godoc/main.go +++ b/src/cmd/godoc/main.go @@ -69,14 +69,12 @@ var ( query = flag.Bool("q", false, "arguments are considered search queries") ) - func serveError(w http.ResponseWriter, r *http.Request, relpath string, err os.Error) { contents := applyTemplate(errorHTML, "errorHTML", err) // err may contain an absolute path! w.WriteHeader(http.StatusNotFound) servePage(w, "File "+relpath, "", "", contents) } - func exec(rw http.ResponseWriter, args []string) (status int) { r, w, err := os.Pipe() if err != nil { @@ -124,7 +122,6 @@ func exec(rw http.ResponseWriter, args []string) (status int) { return } - func dosync(w http.ResponseWriter, r *http.Request) { args := []string{"/bin/sh", "-c", *syncCmd} switch exec(w, args) { @@ -146,7 +143,6 @@ func dosync(w http.ResponseWriter, r *http.Request) { } } - func usage() { fmt.Fprintf(os.Stderr, "usage: godoc package [name ...]\n"+ @@ -155,7 +151,6 @@ func usage() { os.Exit(2) } - func loggingHandler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { log.Printf("%s\t%s", req.RemoteAddr, req.URL) @@ -163,7 +158,6 @@ func loggingHandler(h http.Handler) http.Handler { }) } - func remoteSearch(query string) (res *http.Response, err os.Error) { search := "/search?f=text&q=" + http.URLEscape(query) @@ -195,13 +189,11 @@ func remoteSearch(query string) (res *http.Response, err os.Error) { return } - // Does s look like a regular expression? func isRegexp(s string) bool { return strings.IndexAny(s, ".(|)*+?^$[]") >= 0 } - // Make a regular expression of the form // names[0]|names[1]|...names[len(names)-1]. // Returns nil if the regular expression is illegal. @@ -223,7 +215,6 @@ func makeRx(names []string) (rx *regexp.Regexp) { return } - func main() { flag.Usage = usage flag.Parse() diff --git a/src/cmd/godoc/mapping.go b/src/cmd/godoc/mapping.go index 92614e83e8..51f23ab985 100644 --- a/src/cmd/godoc/mapping.go +++ b/src/cmd/godoc/mapping.go @@ -15,7 +15,6 @@ import ( "strings" ) - // A Mapping object maps relative paths (e.g. from URLs) // to absolute paths (of the file system) and vice versa. // @@ -52,13 +51,11 @@ type Mapping struct { prefixes []string // lazily computed from list } - type mapping struct { prefix, path string value *RWValue } - // Init initializes the Mapping from a list of paths. // Empty paths are ignored; relative paths are assumed to be relative to // the current working directory and converted to absolute paths. @@ -93,11 +90,9 @@ func (m *Mapping) Init(paths []string) { m.list = list } - // IsEmpty returns true if there are no mappings specified. func (m *Mapping) IsEmpty() bool { return len(m.list) == 0 } - // PrefixList returns a list of all prefixes, with duplicates removed. // For instance, for the mapping: // @@ -137,7 +132,6 @@ func (m *Mapping) PrefixList() []string { return m.prefixes } - // Fprint prints the mapping. func (m *Mapping) Fprint(w io.Writer) { for _, e := range m.list { @@ -145,7 +139,6 @@ func (m *Mapping) Fprint(w io.Writer) { } } - func splitFirst(path string) (head, tail string) { i := strings.Index(path, string(filepath.Separator)) if i > 0 { @@ -155,7 +148,6 @@ func splitFirst(path string) (head, tail string) { return "", path } - // ToAbsolute maps a slash-separated relative path to an absolute filesystem // path using the Mapping specified by the receiver. If the path cannot // be mapped, the empty string is returned. @@ -181,7 +173,6 @@ func (m *Mapping) ToAbsolute(spath string) string { return "" // no match } - // ToRelative maps an absolute filesystem path to a relative slash-separated // path using the Mapping specified by the receiver. If the path cannot // be mapped, the empty string is returned. @@ -197,7 +188,6 @@ func (m *Mapping) ToRelative(fpath string) string { return "" // no match } - // Iterate calls f for each path and RWValue in the mapping (in uspecified order) // until f returns false. // diff --git a/src/cmd/godoc/parser.go b/src/cmd/godoc/parser.go index 423db222da..da4b3853c5 100644 --- a/src/cmd/godoc/parser.go +++ b/src/cmd/godoc/parser.go @@ -48,7 +48,6 @@ func parseFiles(fset *token.FileSet, filenames []string) (pkgs map[string]*ast.P return } - func parseDir(fset *token.FileSet, path string, filter func(FileInfo) bool) (map[string]*ast.Package, os.Error) { list, err := fs.ReadDir(path) if err != nil { diff --git a/src/cmd/godoc/snippet.go b/src/cmd/godoc/snippet.go index c5f4c1edf7..626b01455d 100755 --- a/src/cmd/godoc/snippet.go +++ b/src/cmd/godoc/snippet.go @@ -16,13 +16,11 @@ import ( "fmt" ) - type Snippet struct { Line int Text []byte } - func newSnippet(fset *token.FileSet, decl ast.Decl, id *ast.Ident) *Snippet { // TODO instead of pretty-printing the node, should use the original source instead var buf1 bytes.Buffer @@ -35,7 +33,6 @@ func newSnippet(fset *token.FileSet, decl ast.Decl, id *ast.Ident) *Snippet { return &Snippet{fset.Position(id.Pos()).Line, buf2.Bytes()} } - func findSpec(list []ast.Spec, id *ast.Ident) ast.Spec { for _, spec := range list { switch s := spec.(type) { @@ -58,7 +55,6 @@ func findSpec(list []ast.Spec, id *ast.Ident) ast.Spec { return nil } - func genSnippet(fset *token.FileSet, d *ast.GenDecl, id *ast.Ident) *Snippet { s := findSpec(d.Specs, id) if s == nil { @@ -71,7 +67,6 @@ func genSnippet(fset *token.FileSet, d *ast.GenDecl, id *ast.Ident) *Snippet { return newSnippet(fset, dd, id) } - func funcSnippet(fset *token.FileSet, d *ast.FuncDecl, id *ast.Ident) *Snippet { if d.Name != id { return nil // declaration doesn't contain id - exit gracefully @@ -83,7 +78,6 @@ func funcSnippet(fset *token.FileSet, d *ast.FuncDecl, id *ast.Ident) *Snippet { return newSnippet(fset, dd, id) } - // NewSnippet creates a text snippet from a declaration decl containing an // identifier id. Parts of the declaration not containing the identifier // may be removed for a more compact snippet. diff --git a/src/cmd/godoc/spec.go b/src/cmd/godoc/spec.go index 444e36e086..3f69add860 100644 --- a/src/cmd/godoc/spec.go +++ b/src/cmd/godoc/spec.go @@ -18,7 +18,6 @@ import ( "io" ) - type ebnfParser struct { out io.Writer // parser output src []byte // parser source @@ -30,14 +29,12 @@ type ebnfParser struct { lit string // token literal } - func (p *ebnfParser) flush() { offs := p.file.Offset(p.pos) p.out.Write(p.src[p.prev:offs]) p.prev = offs } - func (p *ebnfParser) next() { if p.pos.IsValid() { p.flush() @@ -50,12 +47,10 @@ func (p *ebnfParser) next() { } } - func (p *ebnfParser) Error(pos token.Position, msg string) { fmt.Fprintf(p.out, `error: %s`, msg) } - func (p *ebnfParser) errorExpected(pos token.Pos, msg string) { msg = "expected " + msg if pos == p.pos { @@ -69,7 +64,6 @@ func (p *ebnfParser) errorExpected(pos token.Pos, msg string) { p.Error(p.file.Position(pos), msg) } - func (p *ebnfParser) expect(tok token.Token) token.Pos { pos := p.pos if p.tok != tok { @@ -79,7 +73,6 @@ func (p *ebnfParser) expect(tok token.Token) token.Pos { return pos } - func (p *ebnfParser) parseIdentifier(def bool) { name := p.lit p.expect(token.IDENT) @@ -91,7 +84,6 @@ func (p *ebnfParser) parseIdentifier(def bool) { p.prev += len(name) // skip identifier when calling flush } - func (p *ebnfParser) parseTerm() bool { switch p.tok { case token.IDENT: @@ -127,7 +119,6 @@ func (p *ebnfParser) parseTerm() bool { return true } - func (p *ebnfParser) parseSequence() { if !p.parseTerm() { p.errorExpected(p.pos, "term") @@ -136,7 +127,6 @@ func (p *ebnfParser) parseSequence() { } } - func (p *ebnfParser) parseExpression() { for { p.parseSequence() @@ -147,7 +137,6 @@ func (p *ebnfParser) parseExpression() { } } - func (p *ebnfParser) parseProduction() { p.parseIdentifier(true) p.expect(token.ASSIGN) @@ -157,7 +146,6 @@ func (p *ebnfParser) parseProduction() { p.expect(token.PERIOD) } - func (p *ebnfParser) parse(fset *token.FileSet, out io.Writer, src []byte) { // initialize ebnfParser p.out = out @@ -173,14 +161,12 @@ func (p *ebnfParser) parse(fset *token.FileSet, out io.Writer, src []byte) { p.flush() } - // Markers around EBNF sections var ( openTag = []byte(`
`)
 	closeTag = []byte(`
`) ) - func linkify(out io.Writer, src []byte) { fset := token.NewFileSet() for len(src) > 0 { diff --git a/src/cmd/godoc/utils.go b/src/cmd/godoc/utils.go index e2637ab3d5..5b3ec41b6b 100644 --- a/src/cmd/godoc/utils.go +++ b/src/cmd/godoc/utils.go @@ -18,7 +18,6 @@ import ( "utf8" ) - // An RWValue wraps a value and permits mutually exclusive // access to it and records the time the value was last set. // @@ -28,7 +27,6 @@ type RWValue struct { timestamp int64 // time of last set(), in seconds since epoch } - func (v *RWValue) set(value interface{}) { v.mutex.Lock() v.value = value @@ -36,14 +34,12 @@ func (v *RWValue) set(value interface{}) { v.mutex.Unlock() } - func (v *RWValue) get() (interface{}, int64) { v.mutex.RLock() defer v.mutex.RUnlock() return v.value, v.timestamp } - // TODO(gri) For now, using os.Getwd() is ok here since the functionality // based on this code is not invoked for the appengine version, // but this is fragile. Determine what the right thing to do is, @@ -94,7 +90,6 @@ func canonicalizePaths(list []string, filter func(path string) bool) []string { return list[0:i] } - // writeFileAtomically writes data to a temporary file and then // atomically renames that file to the file named by filename. // @@ -115,7 +110,6 @@ func writeFileAtomically(filename string, data []byte) os.Error { return os.Rename(f.Name(), filename) } - // isText returns true if a significant prefix of s looks like correct UTF-8; // that is, if it is likely that s is human-readable text. // @@ -137,7 +131,6 @@ func isText(s []byte) bool { return true } - // TODO(gri): Should have a mapping from extension to handler, eventually. // textExt[x] is true if the extension x indicates a text file, and false otherwise. @@ -146,7 +139,6 @@ var textExt = map[string]bool{ ".js": false, // must be served raw } - // isTextFile returns true if the file has a known extension indicating // a text file, or if a significant chunk of the specified file looks like // correct UTF-8; that is, if it is likely that the file contains human- diff --git a/src/cmd/godoc/zip.go b/src/cmd/godoc/zip.go index 84f36d0e22..b2257998d7 100644 --- a/src/cmd/godoc/zip.go +++ b/src/cmd/godoc/zip.go @@ -29,19 +29,16 @@ import ( "strings" ) - // zipFI is the zip-file based implementation of FileInfo type zipFI struct { name string // directory-local name file *zip.File // nil for a directory } - func (fi zipFI) Name() string { return fi.name } - func (fi zipFI) Size() int64 { if fi.file != nil { return int64(fi.file.UncompressedSize) @@ -49,30 +46,25 @@ func (fi zipFI) Size() int64 { return 0 // directory } - func (fi zipFI) IsDirectory() bool { return fi.file == nil } - func (fi zipFI) IsRegular() bool { return fi.file != nil } - // zipFS is the zip-file based implementation of FileSystem type zipFS struct { *zip.ReadCloser list zipList } - func (fs *zipFS) Close() os.Error { fs.list = nil return fs.ReadCloser.Close() } - func zipPath(name string) string { if !path.IsAbs(name) { panic(fmt.Sprintf("stat: not an absolute path: %s", name)) @@ -80,7 +72,6 @@ func zipPath(name string) string { return name[1:] // strip '/' } - func (fs *zipFS) stat(abspath string) (int, zipFI, os.Error) { i := fs.list.lookup(abspath) if i < 0 { @@ -94,7 +85,6 @@ func (fs *zipFS) stat(abspath string) (int, zipFI, os.Error) { return i, zipFI{name, file}, nil } - func (fs *zipFS) Open(abspath string) (io.ReadCloser, os.Error) { _, fi, err := fs.stat(zipPath(abspath)) if err != nil { @@ -106,19 +96,16 @@ func (fs *zipFS) Open(abspath string) (io.ReadCloser, os.Error) { return fi.file.Open() } - func (fs *zipFS) Lstat(abspath string) (FileInfo, os.Error) { _, fi, err := fs.stat(zipPath(abspath)) return fi, err } - func (fs *zipFS) Stat(abspath string) (FileInfo, os.Error) { _, fi, err := fs.stat(zipPath(abspath)) return fi, err } - func (fs *zipFS) ReadDir(abspath string) ([]FileInfo, os.Error) { path := zipPath(abspath) i, fi, err := fs.stat(path) @@ -157,7 +144,6 @@ func (fs *zipFS) ReadDir(abspath string) ([]FileInfo, os.Error) { return list, nil } - func (fs *zipFS) ReadFile(abspath string) ([]byte, os.Error) { rc, err := fs.Open(abspath) if err != nil { @@ -166,7 +152,6 @@ func (fs *zipFS) ReadFile(abspath string) ([]byte, os.Error) { return ioutil.ReadAll(rc) } - func NewZipFS(rc *zip.ReadCloser) FileSystem { list := make(zipList, len(rc.File)) copy(list, rc.File) // sort a copy of rc.File @@ -174,7 +159,6 @@ func NewZipFS(rc *zip.ReadCloser) FileSystem { return &zipFS{rc, list} } - type zipList []*zip.File // zipList implements sort.Interface @@ -182,7 +166,6 @@ func (z zipList) Len() int { return len(z) } func (z zipList) Less(i, j int) bool { return z[i].Name < z[j].Name } func (z zipList) Swap(i, j int) { z[i], z[j] = z[j], z[i] } - // lookup returns the first index in the zipList // of a path equal to name or beginning with name/. func (z zipList) lookup(name string) int { diff --git a/src/cmd/gofix/oserrorstring.go b/src/cmd/gofix/oserrorstring.go index 5e61ab9528..db39ee9dc6 100644 --- a/src/cmd/gofix/oserrorstring.go +++ b/src/cmd/gofix/oserrorstring.go @@ -62,7 +62,6 @@ func oserrorstring(f *ast.File) bool { return fixed } - // callExpr returns the call expression if x is a call to pkg.name with one argument; // otherwise it returns nil. func callExpr(x interface{}, pkg, name string) *ast.CallExpr { diff --git a/src/cmd/gofix/signal_test.go b/src/cmd/gofix/signal_test.go index 2500e9ceea..4abba35349 100644 --- a/src/cmd/gofix/signal_test.go +++ b/src/cmd/gofix/signal_test.go @@ -63,7 +63,6 @@ func f() { import "os" - func f() { var _ os.Error _ = os.SIGHUP @@ -86,7 +85,6 @@ func f() { import "os" - func f() { var _ os.Error _ = os.SIGHUP diff --git a/src/cmd/gofix/sorthelpers.go b/src/cmd/gofix/sorthelpers.go index 4d0bee6e7b..4e89fa88f1 100644 --- a/src/cmd/gofix/sorthelpers.go +++ b/src/cmd/gofix/sorthelpers.go @@ -17,7 +17,6 @@ func init() { }) } - func sorthelpers(f *ast.File) (fixed bool) { if !imports(f, "sort") { return diff --git a/src/cmd/gofix/sortslice.go b/src/cmd/gofix/sortslice.go index b9c108b5a1..7cfa1696be 100644 --- a/src/cmd/gofix/sortslice.go +++ b/src/cmd/gofix/sortslice.go @@ -20,7 +20,6 @@ http://codereview.appspot.com/4639041 }) } - func sortslice(f *ast.File) (fixed bool) { if !imports(f, "sort") { return diff --git a/src/cmd/gofix/testdata/reflect.asn1.go.in b/src/cmd/gofix/testdata/reflect.asn1.go.in index c5314517b3..43128f6b26 100644 --- a/src/cmd/gofix/testdata/reflect.asn1.go.in +++ b/src/cmd/gofix/testdata/reflect.asn1.go.in @@ -198,7 +198,6 @@ func parseObjectIdentifier(bytes []byte) (s []int, err os.Error) { // An Enumerated is represented as a plain int. type Enumerated int - // FLAG // A Flag accepts any data and is set to true if present. diff --git a/src/cmd/gofix/testdata/reflect.asn1.go.out b/src/cmd/gofix/testdata/reflect.asn1.go.out index f5716f2730..ba6224e6df 100644 --- a/src/cmd/gofix/testdata/reflect.asn1.go.out +++ b/src/cmd/gofix/testdata/reflect.asn1.go.out @@ -198,7 +198,6 @@ func parseObjectIdentifier(bytes []byte) (s []int, err os.Error) { // An Enumerated is represented as a plain int. type Enumerated int - // FLAG // A Flag accepts any data and is set to true if present. diff --git a/src/cmd/gofix/testdata/reflect.datafmt.go.in b/src/cmd/gofix/testdata/reflect.datafmt.go.in index 46c412342a..91f885f9a3 100644 --- a/src/cmd/gofix/testdata/reflect.datafmt.go.in +++ b/src/cmd/gofix/testdata/reflect.datafmt.go.in @@ -211,7 +211,6 @@ import ( "runtime" ) - // ---------------------------------------------------------------------------- // Format representation @@ -228,13 +227,11 @@ import ( // type Formatter func(state *State, value interface{}, ruleName string) bool - // A FormatterMap is a set of custom formatters. // It maps a rule name to a formatter function. // type FormatterMap map[string]Formatter - // A parsed format expression is built from the following nodes. // type ( @@ -269,13 +266,11 @@ type ( } ) - // A Format is the result of parsing a format specification. // The format may be applied repeatedly to format values. // type Format map[string]expr - // ---------------------------------------------------------------------------- // Formatting @@ -293,7 +288,6 @@ type Environment interface { Copy() Environment } - // State represents the current formatting state. // It is provided as argument to custom formatters. // @@ -309,7 +303,6 @@ type State struct { separator expr // possibly nil } - func newState(fmt Format, env Environment, errors chan os.Error) *State { s := new(State) s.fmt = fmt @@ -330,17 +323,14 @@ func newState(fmt Format, env Environment, errors chan os.Error) *State { return s } - // Env returns the environment passed to Format.Apply. func (s *State) Env() interface{} { return s.env } - // LinePos returns the position of the current line beginning // in the state's output buffer. Line numbers start at 1. // func (s *State) LinePos() token.Position { return s.linePos } - // Pos returns the position of the next byte to be written to the // output buffer. Line numbers start at 1. // @@ -349,7 +339,6 @@ func (s *State) Pos() token.Position { return token.Position{Line: s.linePos.Line, Column: offs - s.linePos.Offset, Offset: offs} } - // Write writes data to the output buffer, inserting the indentation // string after each newline or form feed character. It cannot return an error. // @@ -371,7 +360,6 @@ func (s *State) Write(data []byte) (int, os.Error) { return n + n3, nil } - type checkpoint struct { env Environment hasOutput bool @@ -379,7 +367,6 @@ type checkpoint struct { linePos token.Position } - func (s *State) save() checkpoint { saved := checkpoint{nil, s.hasOutput, s.output.Len(), s.linePos} if s.env != nil { @@ -388,19 +375,16 @@ func (s *State) save() checkpoint { return saved } - func (s *State) restore(m checkpoint) { s.env = m.env s.output.Truncate(m.outputLen) } - func (s *State) error(msg string) { s.errors <- os.NewError(msg) runtime.Goexit() } - // TODO At the moment, unnamed types are simply mapped to the default // names below. For instance, all unnamed arrays are mapped to // 'array' which is not really sufficient. Eventually one may want @@ -440,7 +424,6 @@ func (s *State) getFormat(name string) expr { return nil } - // eval applies a format expression fexpr to a value. If the expression // evaluates internally to a non-nil []byte, that slice is appended to // the state's output buffer and eval returns true. Otherwise, eval @@ -653,7 +636,6 @@ func (s *State) eval(fexpr expr, value reflect.Value, index int) bool { return false } - // Eval formats each argument according to the format // f and returns the resulting []byte and os.Error. If // an error occurred, the []byte contains the partially @@ -688,7 +670,6 @@ func (f Format) Eval(env Environment, args ...interface{}) ([]byte, os.Error) { return s.output.Bytes(), err } - // ---------------------------------------------------------------------------- // Convenience functions @@ -705,7 +686,6 @@ func (f Format) Fprint(w io.Writer, env Environment, args ...interface{}) (int, return w.Write(data) } - // Print formats each argument according to the format f // and writes to standard output. The result is the total // number of bytes written and an os.Error, if any. @@ -714,7 +694,6 @@ func (f Format) Print(args ...interface{}) (int, os.Error) { return f.Fprint(os.Stdout, nil, args...) } - // Sprint formats each argument according to the format f // and returns the resulting string. If an error occurs // during formatting, the result string contains the diff --git a/src/cmd/gofix/testdata/reflect.datafmt.go.out b/src/cmd/gofix/testdata/reflect.datafmt.go.out index bd7f5fd31c..fd447588b0 100644 --- a/src/cmd/gofix/testdata/reflect.datafmt.go.out +++ b/src/cmd/gofix/testdata/reflect.datafmt.go.out @@ -211,7 +211,6 @@ import ( "runtime" ) - // ---------------------------------------------------------------------------- // Format representation @@ -228,13 +227,11 @@ import ( // type Formatter func(state *State, value interface{}, ruleName string) bool - // A FormatterMap is a set of custom formatters. // It maps a rule name to a formatter function. // type FormatterMap map[string]Formatter - // A parsed format expression is built from the following nodes. // type ( @@ -269,13 +266,11 @@ type ( } ) - // A Format is the result of parsing a format specification. // The format may be applied repeatedly to format values. // type Format map[string]expr - // ---------------------------------------------------------------------------- // Formatting @@ -293,7 +288,6 @@ type Environment interface { Copy() Environment } - // State represents the current formatting state. // It is provided as argument to custom formatters. // @@ -309,7 +303,6 @@ type State struct { separator expr // possibly nil } - func newState(fmt Format, env Environment, errors chan os.Error) *State { s := new(State) s.fmt = fmt @@ -330,17 +323,14 @@ func newState(fmt Format, env Environment, errors chan os.Error) *State { return s } - // Env returns the environment passed to Format.Apply. func (s *State) Env() interface{} { return s.env } - // LinePos returns the position of the current line beginning // in the state's output buffer. Line numbers start at 1. // func (s *State) LinePos() token.Position { return s.linePos } - // Pos returns the position of the next byte to be written to the // output buffer. Line numbers start at 1. // @@ -349,7 +339,6 @@ func (s *State) Pos() token.Position { return token.Position{Line: s.linePos.Line, Column: offs - s.linePos.Offset, Offset: offs} } - // Write writes data to the output buffer, inserting the indentation // string after each newline or form feed character. It cannot return an error. // @@ -371,7 +360,6 @@ func (s *State) Write(data []byte) (int, os.Error) { return n + n3, nil } - type checkpoint struct { env Environment hasOutput bool @@ -379,7 +367,6 @@ type checkpoint struct { linePos token.Position } - func (s *State) save() checkpoint { saved := checkpoint{nil, s.hasOutput, s.output.Len(), s.linePos} if s.env != nil { @@ -388,19 +375,16 @@ func (s *State) save() checkpoint { return saved } - func (s *State) restore(m checkpoint) { s.env = m.env s.output.Truncate(m.outputLen) } - func (s *State) error(msg string) { s.errors <- os.NewError(msg) runtime.Goexit() } - // TODO At the moment, unnamed types are simply mapped to the default // names below. For instance, all unnamed arrays are mapped to // 'array' which is not really sufficient. Eventually one may want @@ -440,7 +424,6 @@ func (s *State) getFormat(name string) expr { return nil } - // eval applies a format expression fexpr to a value. If the expression // evaluates internally to a non-nil []byte, that slice is appended to // the state's output buffer and eval returns true. Otherwise, eval @@ -653,7 +636,6 @@ func (s *State) eval(fexpr expr, value reflect.Value, index int) bool { return false } - // Eval formats each argument according to the format // f and returns the resulting []byte and os.Error. If // an error occurred, the []byte contains the partially @@ -688,7 +670,6 @@ func (f Format) Eval(env Environment, args ...interface{}) ([]byte, os.Error) { return s.output.Bytes(), err } - // ---------------------------------------------------------------------------- // Convenience functions @@ -705,7 +686,6 @@ func (f Format) Fprint(w io.Writer, env Environment, args ...interface{}) (int, return w.Write(data) } - // Print formats each argument according to the format f // and writes to standard output. The result is the total // number of bytes written and an os.Error, if any. @@ -714,7 +694,6 @@ func (f Format) Print(args ...interface{}) (int, os.Error) { return f.Fprint(os.Stdout, nil, args...) } - // Sprint formats each argument according to the format f // and returns the resulting string. If an error occurs // during formatting, the result string contains the diff --git a/src/cmd/gofix/testdata/reflect.decode.go.in b/src/cmd/gofix/testdata/reflect.decode.go.in index 501230c0c0..f831abee37 100644 --- a/src/cmd/gofix/testdata/reflect.decode.go.in +++ b/src/cmd/gofix/testdata/reflect.decode.go.in @@ -71,7 +71,6 @@ type Unmarshaler interface { UnmarshalJSON([]byte) os.Error } - // An UnmarshalTypeError describes a JSON value that was // not appropriate for a value of a specific Go type. type UnmarshalTypeError struct { @@ -732,7 +731,6 @@ func (d *decodeState) objectInterface() map[string]interface{} { return m } - // literalInterface is like literal but returns an interface value. func (d *decodeState) literalInterface() interface{} { // All bytes inside literal return scanContinue op code. diff --git a/src/cmd/gofix/testdata/reflect.decode.go.out b/src/cmd/gofix/testdata/reflect.decode.go.out index feeb7b8673..fb7910ee30 100644 --- a/src/cmd/gofix/testdata/reflect.decode.go.out +++ b/src/cmd/gofix/testdata/reflect.decode.go.out @@ -71,7 +71,6 @@ type Unmarshaler interface { UnmarshalJSON([]byte) os.Error } - // An UnmarshalTypeError describes a JSON value that was // not appropriate for a value of a specific Go type. type UnmarshalTypeError struct { @@ -735,7 +734,6 @@ func (d *decodeState) objectInterface() map[string]interface{} { return m } - // literalInterface is like literal but returns an interface value. func (d *decodeState) literalInterface() interface{} { // All bytes inside literal return scanContinue op code. diff --git a/src/cmd/gofix/testdata/reflect.dnsmsg.go.in b/src/cmd/gofix/testdata/reflect.dnsmsg.go.in index 5209c1a06a..3d9c312f24 100644 --- a/src/cmd/gofix/testdata/reflect.dnsmsg.go.in +++ b/src/cmd/gofix/testdata/reflect.dnsmsg.go.in @@ -117,7 +117,6 @@ type dnsRR interface { Header() *dnsRR_Header } - // Specific DNS RR formats for each query type. type dnsRR_CNAME struct { @@ -645,7 +644,6 @@ type dnsMsg struct { extra []dnsRR } - func (dns *dnsMsg) Pack() (msg []byte, ok bool) { var dh dnsHeader diff --git a/src/cmd/gofix/testdata/reflect.dnsmsg.go.out b/src/cmd/gofix/testdata/reflect.dnsmsg.go.out index 12e4c34c39..c777fe27cb 100644 --- a/src/cmd/gofix/testdata/reflect.dnsmsg.go.out +++ b/src/cmd/gofix/testdata/reflect.dnsmsg.go.out @@ -117,7 +117,6 @@ type dnsRR interface { Header() *dnsRR_Header } - // Specific DNS RR formats for each query type. type dnsRR_CNAME struct { @@ -645,7 +644,6 @@ type dnsMsg struct { extra []dnsRR } - func (dns *dnsMsg) Pack() (msg []byte, ok bool) { var dh dnsHeader diff --git a/src/cmd/gofix/testdata/reflect.print.go.in b/src/cmd/gofix/testdata/reflect.print.go.in index 194bcdb3b2..cba1df2967 100644 --- a/src/cmd/gofix/testdata/reflect.print.go.in +++ b/src/cmd/gofix/testdata/reflect.print.go.in @@ -252,7 +252,6 @@ func Sprintln(a ...interface{}) string { return s } - // Get the i'th arg of the struct value. // If the arg itself is an interface, return a value for // the thing inside the interface, not the interface itself. diff --git a/src/cmd/gofix/testdata/reflect.print.go.out b/src/cmd/gofix/testdata/reflect.print.go.out index 10379bd204..b475a2ae17 100644 --- a/src/cmd/gofix/testdata/reflect.print.go.out +++ b/src/cmd/gofix/testdata/reflect.print.go.out @@ -252,7 +252,6 @@ func Sprintln(a ...interface{}) string { return s } - // Get the i'th arg of the struct value. // If the arg itself is an interface, return a value for // the thing inside the interface, not the interface itself. diff --git a/src/cmd/gofix/testdata/reflect.scan.go.in b/src/cmd/gofix/testdata/reflect.scan.go.in index 36271a8d46..83650e605d 100644 --- a/src/cmd/gofix/testdata/reflect.scan.go.in +++ b/src/cmd/gofix/testdata/reflect.scan.go.in @@ -324,7 +324,6 @@ func (r *readRune) ReadRune() (rune int, size int, err os.Error) { return } - var ssFree = newCache(func() interface{} { return new(ss) }) // Allocate a new ss struct or grab a cached one. @@ -398,7 +397,6 @@ func (s *ss) skipSpace(stopAtNewline bool) { } } - // token returns the next space-delimited string from the input. It // skips white space. For Scanln, it stops at newlines. For Scan, // newlines are treated as spaces. diff --git a/src/cmd/gofix/testdata/reflect.scan.go.out b/src/cmd/gofix/testdata/reflect.scan.go.out index 2b07115e99..956c13bde8 100644 --- a/src/cmd/gofix/testdata/reflect.scan.go.out +++ b/src/cmd/gofix/testdata/reflect.scan.go.out @@ -324,7 +324,6 @@ func (r *readRune) ReadRune() (rune int, size int, err os.Error) { return } - var ssFree = newCache(func() interface{} { return new(ss) }) // Allocate a new ss struct or grab a cached one. @@ -398,7 +397,6 @@ func (s *ss) skipSpace(stopAtNewline bool) { } } - // token returns the next space-delimited string from the input. It // skips white space. For Scanln, it stops at newlines. For Scan, // newlines are treated as spaces. diff --git a/src/cmd/gofmt/gofmt.go b/src/cmd/gofmt/gofmt.go index ea1c1b00ff..2543e30778 100644 --- a/src/cmd/gofmt/gofmt.go +++ b/src/cmd/gofmt/gofmt.go @@ -22,7 +22,6 @@ import ( "strings" ) - var ( // main operation modes list = flag.Bool("l", false, "list files whose formatting differs from gofmt's") @@ -41,7 +40,6 @@ var ( cpuprofile = flag.String("cpuprofile", "", "write cpu profile to this file") ) - var ( fset = token.NewFileSet() exitCode = 0 @@ -50,20 +48,17 @@ var ( printerMode uint ) - func report(err os.Error) { scanner.PrintError(os.Stderr, err) exitCode = 2 } - func usage() { fmt.Fprintf(os.Stderr, "usage: gofmt [flags] [path ...]\n") flag.PrintDefaults() os.Exit(2) } - func initParserMode() { parserMode = uint(0) if *comments { @@ -71,7 +66,6 @@ func initParserMode() { } } - func initPrinterMode() { printerMode = uint(0) if *tabIndent { @@ -82,13 +76,11 @@ func initPrinterMode() { } } - func isGoFile(f *os.FileInfo) bool { // ignore non-Go files return f.IsRegular() && !strings.HasPrefix(f.Name, ".") && strings.HasSuffix(f.Name, ".go") } - // If in == nil, the source is the contents of the file with the given filename. func processFile(filename string, in io.Reader, out io.Writer) os.Error { if in == nil { @@ -153,14 +145,12 @@ func processFile(filename string, in io.Reader, out io.Writer) os.Error { return err } - type fileVisitor chan os.Error func (v fileVisitor) VisitDir(path string, f *os.FileInfo) bool { return true } - func (v fileVisitor) VisitFile(path string, f *os.FileInfo) { if isGoFile(f) { v <- nil // synchronize error handler @@ -170,7 +160,6 @@ func (v fileVisitor) VisitFile(path string, f *os.FileInfo) { } } - func walkDir(path string) { v := make(fileVisitor) go func() { @@ -184,7 +173,6 @@ func walkDir(path string) { } } - func main() { // call gofmtMain in a separate function // so that it can use defer and have them @@ -193,7 +181,6 @@ func main() { os.Exit(exitCode) } - func gofmtMain() { flag.Usage = usage flag.Parse() @@ -241,7 +228,6 @@ func gofmtMain() { } } - func diff(b1, b2 []byte) (data []byte, err os.Error) { f1, err := ioutil.TempFile("", "gofmt") if err != nil { diff --git a/src/cmd/gofmt/gofmt_test.go b/src/cmd/gofmt/gofmt_test.go index 70700554ba..2e35ce9a44 100644 --- a/src/cmd/gofmt/gofmt_test.go +++ b/src/cmd/gofmt/gofmt_test.go @@ -12,7 +12,6 @@ import ( "testing" ) - func runTest(t *testing.T, dirname, in, out, flags string) { in = filepath.Join(dirname, in) out = filepath.Join(dirname, out) @@ -62,7 +61,6 @@ func runTest(t *testing.T, dirname, in, out, flags string) { } } - // TODO(gri) Add more test cases! var tests = []struct { dirname, in, out, flags string @@ -74,7 +72,6 @@ var tests = []struct { {"testdata", "rewrite2.input", "rewrite2.golden", "-r=int->bool"}, } - func TestRewrite(t *testing.T) { for _, test := range tests { runTest(t, test.dirname, test.in, test.out, test.flags) diff --git a/src/cmd/gofmt/rewrite.go b/src/cmd/gofmt/rewrite.go index f7f1fe8243..3d74dea0f1 100644 --- a/src/cmd/gofmt/rewrite.go +++ b/src/cmd/gofmt/rewrite.go @@ -16,7 +16,6 @@ import ( "utf8" ) - func initRewrite() { if *rewriteRule == "" { rewrite = nil // disable any previous rewrite @@ -32,7 +31,6 @@ func initRewrite() { rewrite = func(p *ast.File) *ast.File { return rewriteFile(pattern, replace, p) } } - // parseExpr parses s as an expression. // It might make sense to expand this to allow statement patterns, // but there are problems with preserving formatting and also @@ -46,7 +44,6 @@ func parseExpr(s string, what string) ast.Expr { return x } - // Keep this function for debugging. /* func dump(msg string, val reflect.Value) { @@ -56,7 +53,6 @@ func dump(msg string, val reflect.Value) { } */ - // rewriteFile applies the rewrite rule 'pattern -> replace' to an entire file. func rewriteFile(pattern, replace ast.Expr, p *ast.File) *ast.File { m := make(map[string]reflect.Value) @@ -80,7 +76,6 @@ func rewriteFile(pattern, replace ast.Expr, p *ast.File) *ast.File { return apply(f, reflect.ValueOf(p)).Interface().(*ast.File) } - // setValue is a wrapper for x.SetValue(y); it protects // the caller from panics if x cannot be changed to y. func setValue(x, y reflect.Value) { @@ -100,7 +95,6 @@ func setValue(x, y reflect.Value) { x.Set(y) } - // Values/types for special cases. var ( objectPtrNil = reflect.ValueOf((*ast.Object)(nil)) @@ -112,7 +106,6 @@ var ( scopePtrType = reflect.TypeOf((*ast.Scope)(nil)) ) - // apply replaces each AST field x in val with f(x), returning val. // To avoid extra conversions, f operates on the reflect.Value form. func apply(f func(reflect.Value) reflect.Value, val reflect.Value) reflect.Value { @@ -150,13 +143,11 @@ func apply(f func(reflect.Value) reflect.Value, val reflect.Value) reflect.Value return val } - func isWildcard(s string) bool { rune, size := utf8.DecodeRuneInString(s) return size == len(s) && unicode.IsLower(rune) } - // match returns true if pattern matches val, // recording wildcard submatches in m. // If m == nil, match checks whether pattern == val. @@ -238,7 +229,6 @@ func match(m map[string]reflect.Value, pattern, val reflect.Value) bool { return p.Interface() == v.Interface() } - // subst returns a copy of pattern with values from m substituted in place // of wildcards and pos used as the position of tokens from the pattern. // if m == nil, subst returns a copy of pattern and doesn't change the line diff --git a/src/cmd/gofmt/simplify.go b/src/cmd/gofmt/simplify.go index 40a9f8f178..d9afc0e7b4 100644 --- a/src/cmd/gofmt/simplify.go +++ b/src/cmd/gofmt/simplify.go @@ -9,7 +9,6 @@ import ( "reflect" ) - type simplifier struct{} func (s *simplifier) Visit(node ast.Node) ast.Visitor { @@ -60,7 +59,6 @@ func (s *simplifier) Visit(node ast.Node) ast.Visitor { return s } - func simplify(node ast.Node) { var s simplifier ast.Walk(&s, node) diff --git a/src/cmd/goinstall/main.go b/src/cmd/goinstall/main.go index 5cdf0f18e2..02f9371394 100644 --- a/src/cmd/goinstall/main.go +++ b/src/cmd/goinstall/main.go @@ -254,7 +254,6 @@ func install(pkg, parent string) { return } - // Is this a standard package path? strings container/vector etc. // Assume that if the first element has a dot, it's a domain name // and is not the standard package path. diff --git a/src/cmd/gotype/gotype.go b/src/cmd/gotype/gotype.go index 501ead443c..aaa702fdf2 100644 --- a/src/cmd/gotype/gotype.go +++ b/src/cmd/gotype/gotype.go @@ -18,7 +18,6 @@ import ( "strings" ) - var ( // main operation modes pkgName = flag.String("p", "", "process only those files in package pkgName") @@ -30,23 +29,19 @@ var ( printAST = flag.Bool("ast", false, "print AST") ) - var exitCode = 0 - func usage() { fmt.Fprintf(os.Stderr, "usage: gotype [flags] [path ...]\n") flag.PrintDefaults() os.Exit(2) } - func report(err os.Error) { scanner.PrintError(os.Stderr, err) exitCode = 2 } - // parse returns the AST for the Go source src. // The filename is for error reporting only. // The result is nil if there were errors or if @@ -88,7 +83,6 @@ func parse(fset *token.FileSet, filename string, src []byte) *ast.File { return file } - func parseStdin(fset *token.FileSet) (files map[string]*ast.File) { files = make(map[string]*ast.File) src, err := ioutil.ReadAll(os.Stdin) @@ -103,7 +97,6 @@ func parseStdin(fset *token.FileSet) (files map[string]*ast.File) { return } - func parseFiles(fset *token.FileSet, filenames []string) (files map[string]*ast.File) { files = make(map[string]*ast.File) for _, filename := range filenames { @@ -123,13 +116,11 @@ func parseFiles(fset *token.FileSet, filenames []string) (files map[string]*ast. return } - func isGoFilename(filename string) bool { // ignore non-Go files return !strings.HasPrefix(filename, ".") && strings.HasSuffix(filename, ".go") } - func processDirectory(dirname string) { f, err := os.Open(dirname) if err != nil { @@ -148,7 +139,6 @@ func processDirectory(dirname string) { processFiles(filenames, false) } - func processFiles(filenames []string, allFiles bool) { i := 0 for _, filename := range filenames { @@ -170,7 +160,6 @@ func processFiles(filenames []string, allFiles bool) { processPackage(fset, parseFiles(fset, filenames[0:i])) } - func processPackage(fset *token.FileSet, files map[string]*ast.File) { // make a package (resolve all identifiers) pkg, err := ast.NewPackage(fset, files, types.GcImporter, types.Universe) @@ -184,7 +173,6 @@ func processPackage(fset *token.FileSet, files map[string]*ast.File) { } } - func main() { flag.Usage = usage flag.Parse() diff --git a/src/cmd/gotype/gotype_test.go b/src/cmd/gotype/gotype_test.go index 9c8f8f2a77..ad0bc89032 100644 --- a/src/cmd/gotype/gotype_test.go +++ b/src/cmd/gotype/gotype_test.go @@ -10,7 +10,6 @@ import ( "testing" ) - func runTest(t *testing.T, path, pkg string) { exitCode = 0 *pkgName = pkg @@ -27,7 +26,6 @@ func runTest(t *testing.T, path, pkg string) { } } - var tests = []struct { path string pkg string @@ -44,7 +42,6 @@ var tests = []struct { {filepath.Join(runtime.GOROOT(), "src/pkg/go/types"), "types"}, } - func Test(t *testing.T) { for _, test := range tests { runTest(t, test.path, test.pkg) diff --git a/src/cmd/govet/govet.go b/src/cmd/govet/govet.go index 5b24d2ff03..98d3d5c17f 100644 --- a/src/cmd/govet/govet.go +++ b/src/cmd/govet/govet.go @@ -348,7 +348,6 @@ FlagLoop: return } - // checkPrint checks a call to an unformatted print routine such as Println. // The skip argument records how many arguments to ignore; that is, // call.Args[skip] is the first argument to be printed. diff --git a/src/cmd/hgpatch/main.go b/src/cmd/hgpatch/main.go index 4f7aec22b2..9e338abcbd 100644 --- a/src/cmd/hgpatch/main.go +++ b/src/cmd/hgpatch/main.go @@ -182,7 +182,6 @@ func main() { } } - // make parent directory for name, if necessary func makeParent(name string) { parent, _ := filepath.Split(name) @@ -240,7 +239,6 @@ func chk(err os.Error) { } } - // Undo log type undo func() os.Error @@ -258,7 +256,6 @@ func runUndo() { } } - // hgRoot returns the root directory of the repository. func hgRoot() (string, os.Error) { out, err := run([]string{"hg", "root"}, nil) diff --git a/src/pkg/archive/tar/reader_test.go b/src/pkg/archive/tar/reader_test.go index 32fc8f9151..f473c900f2 100644 --- a/src/pkg/archive/tar/reader_test.go +++ b/src/pkg/archive/tar/reader_test.go @@ -178,7 +178,6 @@ func TestPartialRead(t *testing.T) { } } - func TestIncrementalRead(t *testing.T) { test := gnuTarTest f, err := os.Open(test.file) diff --git a/src/pkg/asn1/asn1.go b/src/pkg/asn1/asn1.go index 6557729317..2dcdcfea6c 100644 --- a/src/pkg/asn1/asn1.go +++ b/src/pkg/asn1/asn1.go @@ -220,7 +220,6 @@ func parseObjectIdentifier(bytes []byte) (s []int, err os.Error) { // An Enumerated is represented as a plain int. type Enumerated int - // FLAG // A Flag accepts any data and is set to true if present. diff --git a/src/pkg/big/arith.go b/src/pkg/big/arith.go index b9aeea9684..0a02a4ef59 100644 --- a/src/pkg/big/arith.go +++ b/src/pkg/big/arith.go @@ -27,7 +27,6 @@ const ( _M2 = _B2 - 1 // half digit mask ) - // ---------------------------------------------------------------------------- // Elementary operations on words // @@ -43,7 +42,6 @@ func addWW_g(x, y, c Word) (z1, z0 Word) { return } - // z1<<_W + z0 = x-y-c, with c == 0 or 1 func subWW_g(x, y, c Word) (z1, z0 Word) { yc := y + c @@ -54,7 +52,6 @@ func subWW_g(x, y, c Word) (z1, z0 Word) { return } - // z1<<_W + z0 = x*y // Adapted from Warren, Hacker's Delight, p. 132. func mulWW_g(x, y Word) (z1, z0 Word) { @@ -72,7 +69,6 @@ func mulWW_g(x, y Word) (z1, z0 Word) { return } - // z1<<_W + z0 = x*y + c func mulAddWWW_g(x, y, c Word) (z1, z0 Word) { z1, zz0 := mulWW(x, y) @@ -82,7 +78,6 @@ func mulAddWWW_g(x, y, c Word) (z1, z0 Word) { return } - // Length of x in bits. func bitLen(x Word) (n int) { for ; x >= 0x100; x >>= 8 { @@ -94,7 +89,6 @@ func bitLen(x Word) (n int) { return } - // log2 computes the integer binary logarithm of x. // The result is the integer n for which 2^n <= x < 2^(n+1). // If x == 0, the result is -1. @@ -102,13 +96,11 @@ func log2(x Word) int { return bitLen(x) - 1 } - // Number of leading zeros in x. func leadingZeros(x Word) uint { return uint(_W - bitLen(x)) } - // q = (u1<<_W + u0 - r)/y // Adapted from Warren, Hacker's Delight, p. 152. func divWW_g(u1, u0, v Word) (q, r Word) { @@ -153,7 +145,6 @@ again2: return q1*_B2 + q0, (un21*_B2 + un0 - q0*v) >> s } - func addVV_g(z, x, y []Word) (c Word) { for i := range z { c, z[i] = addWW_g(x[i], y[i], c) @@ -161,7 +152,6 @@ func addVV_g(z, x, y []Word) (c Word) { return } - func subVV_g(z, x, y []Word) (c Word) { for i := range z { c, z[i] = subWW_g(x[i], y[i], c) @@ -169,7 +159,6 @@ func subVV_g(z, x, y []Word) (c Word) { return } - func addVW_g(z, x []Word, y Word) (c Word) { c = y for i := range z { @@ -178,7 +167,6 @@ func addVW_g(z, x []Word, y Word) (c Word) { return } - func subVW_g(z, x []Word, y Word) (c Word) { c = y for i := range z { @@ -187,7 +175,6 @@ func subVW_g(z, x []Word, y Word) (c Word) { return } - func shlVU_g(z, x []Word, s uint) (c Word) { if n := len(z); n > 0 { ŝ := _W - s @@ -203,7 +190,6 @@ func shlVU_g(z, x []Word, s uint) (c Word) { return } - func shrVU_g(z, x []Word, s uint) (c Word) { if n := len(z); n > 0 { ŝ := _W - s @@ -219,7 +205,6 @@ func shrVU_g(z, x []Word, s uint) (c Word) { return } - func mulAddVWW_g(z, x []Word, y, r Word) (c Word) { c = r for i := range z { @@ -228,7 +213,6 @@ func mulAddVWW_g(z, x []Word, y, r Word) (c Word) { return } - func addMulVVW_g(z, x []Word, y Word) (c Word) { for i := range z { z1, z0 := mulAddWWW_g(x[i], y, z[i]) @@ -238,7 +222,6 @@ func addMulVVW_g(z, x []Word, y Word) (c Word) { return } - func divWVW_g(z []Word, xn Word, x []Word, y Word) (r Word) { r = xn for i := len(z) - 1; i >= 0; i-- { diff --git a/src/pkg/big/arith_test.go b/src/pkg/big/arith_test.go index f3e2d4735d..b6c56c39ef 100644 --- a/src/pkg/big/arith_test.go +++ b/src/pkg/big/arith_test.go @@ -6,7 +6,6 @@ package big import "testing" - type funWW func(x, y, c Word) (z1, z0 Word) type argWW struct { x, y, c, z1, z0 Word @@ -26,7 +25,6 @@ var sumWW = []argWW{ {_M, _M, 1, 1, _M}, } - func testFunWW(t *testing.T, msg string, f funWW, a argWW) { z1, z0 := f(a.x, a.y, a.c) if z1 != a.z1 || z0 != a.z0 { @@ -34,7 +32,6 @@ func testFunWW(t *testing.T, msg string, f funWW, a argWW) { } } - func TestFunWW(t *testing.T) { for _, a := range sumWW { arg := a @@ -51,7 +48,6 @@ func TestFunWW(t *testing.T) { } } - type funVV func(z, x, y []Word) (c Word) type argVV struct { z, x, y nat @@ -70,7 +66,6 @@ var sumVV = []argVV{ {nat{0, 0, 0, 0}, nat{_M, 0, _M, 0}, nat{1, _M, 0, _M}, 1}, } - func testFunVV(t *testing.T, msg string, f funVV, a argVV) { z := make(nat, len(a.z)) c := f(z, a.x, a.y) @@ -85,7 +80,6 @@ func testFunVV(t *testing.T, msg string, f funVV, a argVV) { } } - func TestFunVV(t *testing.T) { for _, a := range sumVV { arg := a @@ -106,7 +100,6 @@ func TestFunVV(t *testing.T) { } } - type funVW func(z, x []Word, y Word) (c Word) type argVW struct { z, x nat @@ -169,7 +162,6 @@ var rshVW = []argVW{ {nat{_M, _M, _M >> 20}, nat{_M, _M, _M}, 20, _M << (_W - 20) & _M}, } - func testFunVW(t *testing.T, msg string, f funVW, a argVW) { z := make(nat, len(a.z)) c := f(z, a.x, a.y) @@ -184,14 +176,12 @@ func testFunVW(t *testing.T, msg string, f funVW, a argVW) { } } - func makeFunVW(f func(z, x []Word, s uint) (c Word)) funVW { return func(z, x []Word, s Word) (c Word) { return f(z, x, uint(s)) } } - func TestFunVW(t *testing.T) { for _, a := range sumVW { arg := a @@ -220,7 +210,6 @@ func TestFunVW(t *testing.T) { } } - type funVWW func(z, x []Word, y, r Word) (c Word) type argVWW struct { z, x nat @@ -254,7 +243,6 @@ var prodVWW = []argVWW{ {nat{_M<<7&_M + 1<<6, _M, _M, _M}, nat{_M, _M, _M, _M}, 1 << 7, 1 << 6, _M >> (_W - 7)}, } - func testFunVWW(t *testing.T, msg string, f funVWW, a argVWW) { z := make(nat, len(a.z)) c := f(z, a.x, a.y, a.r) @@ -269,7 +257,6 @@ func testFunVWW(t *testing.T, msg string, f funVWW, a argVWW) { } } - // TODO(gri) mulAddVWW and divWVW are symmetric operations but // their signature is not symmetric. Try to unify. @@ -296,7 +283,6 @@ func testFunWVW(t *testing.T, msg string, f funWVW, a argWVW) { } } - func TestFunVWW(t *testing.T) { for _, a := range prodVWW { arg := a @@ -311,7 +297,6 @@ func TestFunVWW(t *testing.T) { } } - var mulWWTests = []struct { x, y Word q, r Word @@ -320,7 +305,6 @@ var mulWWTests = []struct { // 32 bit only: {0xc47dfa8c, 50911, 0x98a4, 0x998587f4}, } - func TestMulWW(t *testing.T) { for i, test := range mulWWTests { q, r := mulWW_g(test.x, test.y) @@ -330,7 +314,6 @@ func TestMulWW(t *testing.T) { } } - var mulAddWWWTests = []struct { x, y, c Word q, r Word @@ -342,7 +325,6 @@ var mulAddWWWTests = []struct { {_M, _M, _M, _M, 0}, } - func TestMulAddWWW(t *testing.T) { for i, test := range mulAddWWWTests { q, r := mulAddWWW_g(test.x, test.y, test.c) diff --git a/src/pkg/big/calibrate_test.go b/src/pkg/big/calibrate_test.go index c6cd2e693b..1cd93b1052 100644 --- a/src/pkg/big/calibrate_test.go +++ b/src/pkg/big/calibrate_test.go @@ -19,10 +19,8 @@ import ( "time" ) - var calibrate = flag.Bool("calibrate", false, "run calibration test") - // measure returns the time to run f func measure(f func()) int64 { const N = 100 @@ -34,7 +32,6 @@ func measure(f func()) int64 { return (stop - start) / N } - func computeThresholds() { fmt.Printf("Multiplication times for varying Karatsuba thresholds\n") fmt.Printf("(run repeatedly for good results)\n") @@ -84,7 +81,6 @@ func computeThresholds() { } } - func TestCalibrate(t *testing.T) { if *calibrate { computeThresholds() diff --git a/src/pkg/big/hilbert_test.go b/src/pkg/big/hilbert_test.go index 66a21214d2..1a84341b3c 100644 --- a/src/pkg/big/hilbert_test.go +++ b/src/pkg/big/hilbert_test.go @@ -13,13 +13,11 @@ import ( "testing" ) - type matrix struct { n, m int a []*Rat } - func (a *matrix) at(i, j int) *Rat { if !(0 <= i && i < a.n && 0 <= j && j < a.m) { panic("index out of range") @@ -27,7 +25,6 @@ func (a *matrix) at(i, j int) *Rat { return a.a[i*a.m+j] } - func (a *matrix) set(i, j int, x *Rat) { if !(0 <= i && i < a.n && 0 <= j && j < a.m) { panic("index out of range") @@ -35,7 +32,6 @@ func (a *matrix) set(i, j int, x *Rat) { a.a[i*a.m+j] = x } - func newMatrix(n, m int) *matrix { if !(0 <= n && 0 <= m) { panic("illegal matrix") @@ -47,7 +43,6 @@ func newMatrix(n, m int) *matrix { return a } - func newUnit(n int) *matrix { a := newMatrix(n, n) for i := 0; i < n; i++ { @@ -62,7 +57,6 @@ func newUnit(n int) *matrix { return a } - func newHilbert(n int) *matrix { a := newMatrix(n, n) for i := 0; i < n; i++ { @@ -73,7 +67,6 @@ func newHilbert(n int) *matrix { return a } - func newInverseHilbert(n int) *matrix { a := newMatrix(n, n) for i := 0; i < n; i++ { @@ -98,7 +91,6 @@ func newInverseHilbert(n int) *matrix { return a } - func (a *matrix) mul(b *matrix) *matrix { if a.m != b.n { panic("illegal matrix multiply") @@ -116,7 +108,6 @@ func (a *matrix) mul(b *matrix) *matrix { return c } - func (a *matrix) eql(b *matrix) bool { if a.n != b.n || a.m != b.m { return false @@ -131,7 +122,6 @@ func (a *matrix) eql(b *matrix) bool { return true } - func (a *matrix) String() string { s := "" for i := 0; i < a.n; i++ { @@ -143,7 +133,6 @@ func (a *matrix) String() string { return s } - func doHilbert(t *testing.T, n int) { a := newHilbert(n) b := newInverseHilbert(n) @@ -160,12 +149,10 @@ func doHilbert(t *testing.T, n int) { } } - func TestHilbert(t *testing.T) { doHilbert(t, 10) } - func BenchmarkHilbert(b *testing.B) { for i := 0; i < b.N; i++ { doHilbert(nil, 10) diff --git a/src/pkg/big/int.go b/src/pkg/big/int.go index 0948919cda..0aad189ad0 100755 --- a/src/pkg/big/int.go +++ b/src/pkg/big/int.go @@ -21,10 +21,8 @@ type Int struct { abs nat // absolute value of the integer } - var intOne = &Int{false, natOne} - // Sign returns: // // -1 if x < 0 @@ -41,7 +39,6 @@ func (x *Int) Sign() int { return 1 } - // SetInt64 sets z to x and returns z. func (z *Int) SetInt64(x int64) *Int { neg := false @@ -54,13 +51,11 @@ func (z *Int) SetInt64(x int64) *Int { return z } - // NewInt allocates and returns a new Int set to x. func NewInt(x int64) *Int { return new(Int).SetInt64(x) } - // Set sets z to x and returns z. func (z *Int) Set(x *Int) *Int { z.abs = z.abs.set(x.abs) @@ -68,7 +63,6 @@ func (z *Int) Set(x *Int) *Int { return z } - // Abs sets z to |x| (the absolute value of x) and returns z. func (z *Int) Abs(x *Int) *Int { z.abs = z.abs.set(x.abs) @@ -76,7 +70,6 @@ func (z *Int) Abs(x *Int) *Int { return z } - // Neg sets z to -x and returns z. func (z *Int) Neg(x *Int) *Int { z.abs = z.abs.set(x.abs) @@ -84,7 +77,6 @@ func (z *Int) Neg(x *Int) *Int { return z } - // Add sets z to the sum x+y and returns z. func (z *Int) Add(x, y *Int) *Int { neg := x.neg @@ -106,7 +98,6 @@ func (z *Int) Add(x, y *Int) *Int { return z } - // Sub sets z to the difference x-y and returns z. func (z *Int) Sub(x, y *Int) *Int { neg := x.neg @@ -128,7 +119,6 @@ func (z *Int) Sub(x, y *Int) *Int { return z } - // Mul sets z to the product x*y and returns z. func (z *Int) Mul(x, y *Int) *Int { // x * y == x * y @@ -140,7 +130,6 @@ func (z *Int) Mul(x, y *Int) *Int { return z } - // MulRange sets z to the product of all integers // in the range [a, b] inclusively and returns z. // If a > b (empty range), the result is 1. @@ -164,7 +153,6 @@ func (z *Int) MulRange(a, b int64) *Int { return z } - // Binomial sets z to the binomial coefficient of (n, k) and returns z. func (z *Int) Binomial(n, k int64) *Int { var a, b Int @@ -173,7 +161,6 @@ func (z *Int) Binomial(n, k int64) *Int { return z.Quo(&a, &b) } - // Quo sets z to the quotient x/y for y != 0 and returns z. // If y == 0, a division-by-zero run-time panic occurs. // See QuoRem for more details. @@ -183,7 +170,6 @@ func (z *Int) Quo(x, y *Int) *Int { return z } - // Rem sets z to the remainder x%y for y != 0 and returns z. // If y == 0, a division-by-zero run-time panic occurs. // See QuoRem for more details. @@ -193,7 +179,6 @@ func (z *Int) Rem(x, y *Int) *Int { return z } - // QuoRem sets z to the quotient x/y and r to the remainder x%y // and returns the pair (z, r) for y != 0. // If y == 0, a division-by-zero run-time panic occurs. @@ -211,7 +196,6 @@ func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) { return z, r } - // Div sets z to the quotient x/y for y != 0 and returns z. // If y == 0, a division-by-zero run-time panic occurs. // See DivMod for more details. @@ -229,7 +213,6 @@ func (z *Int) Div(x, y *Int) *Int { return z } - // Mod sets z to the modulus x%y for y != 0 and returns z. // If y == 0, a division-by-zero run-time panic occurs. // See DivMod for more details. @@ -250,7 +233,6 @@ func (z *Int) Mod(x, y *Int) *Int { return z } - // DivMod sets z to the quotient x div y and m to the modulus x mod y // and returns the pair (z, m) for y != 0. // If y == 0, a division-by-zero run-time panic occurs. @@ -283,7 +265,6 @@ func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) { return z, m } - // Cmp compares x and y and returns: // // -1 if x < y @@ -309,7 +290,6 @@ func (x *Int) Cmp(y *Int) (r int) { return } - func (x *Int) String() string { switch { case x == nil: @@ -320,7 +300,6 @@ func (x *Int) String() string { return x.abs.decimalString() } - func charset(ch int) string { switch ch { case 'b': @@ -337,7 +316,6 @@ func charset(ch int) string { return "" // unknown format } - // Format is a support routine for fmt.Formatter. It accepts // the formats 'b' (binary), 'o' (octal), 'd' (decimal), 'x' // (lowercase hexadecimal), and 'X' (uppercase hexadecimal). @@ -424,7 +402,6 @@ func (x *Int) Format(s fmt.State, ch int) { fmt.Fprint(s, t) } - // scan sets z to the integer value corresponding to the longest possible prefix // read from r representing a signed integer number in a given conversion base. // It returns z, the actual conversion base used, and an error, if any. In the @@ -461,7 +438,6 @@ func (z *Int) scan(r io.RuneScanner, base int) (*Int, int, os.Error) { return z, base, nil } - // Scan is a support routine for fmt.Scanner; it sets z to the value of // the scanned number. It accepts the formats 'b' (binary), 'o' (octal), // 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal). @@ -486,7 +462,6 @@ func (z *Int) Scan(s fmt.ScanState, ch int) os.Error { return err } - // Int64 returns the int64 representation of x. // If x cannot be represented in an int64, the result is undefined. func (x *Int) Int64() int64 { @@ -503,7 +478,6 @@ func (x *Int) Int64() int64 { return v } - // SetString sets z to the value of s, interpreted in the given base, // and returns z and a boolean indicating success. If SetString fails, // the value of z is undefined. @@ -523,7 +497,6 @@ func (z *Int) SetString(s string, base int) (*Int, bool) { return z, err == os.EOF // err == os.EOF => scan consumed all of s } - // SetBytes interprets buf as the bytes of a big-endian unsigned // integer, sets z to that value, and returns z. func (z *Int) SetBytes(buf []byte) *Int { @@ -532,21 +505,18 @@ func (z *Int) SetBytes(buf []byte) *Int { return z } - // Bytes returns the absolute value of z as a big-endian byte slice. func (z *Int) Bytes() []byte { buf := make([]byte, len(z.abs)*_S) return buf[z.abs.bytes(buf):] } - // BitLen returns the length of the absolute value of z in bits. // The bit length of 0 is 0. func (z *Int) BitLen() int { return z.abs.bitLen() } - // Exp sets z = x**y mod m. If m is nil, z = x**y. // See Knuth, volume 2, section 4.6.3. func (z *Int) Exp(x, y, m *Int) *Int { @@ -567,7 +537,6 @@ func (z *Int) Exp(x, y, m *Int) *Int { return z } - // GcdInt sets d to the greatest common divisor of a and b, which must be // positive numbers. // If x and y are not nil, GcdInt sets x and y such that d = a*x + b*y. @@ -626,7 +595,6 @@ func GcdInt(d, x, y, a, b *Int) { *d = *A } - // ProbablyPrime performs n Miller-Rabin tests to check whether z is prime. // If it returns true, z is prime with probability 1 - 1/4^n. // If it returns false, z is not prime. @@ -634,7 +602,6 @@ func ProbablyPrime(z *Int, n int) bool { return !z.neg && z.abs.probablyPrime(n) } - // Rand sets z to a pseudo-random number in [0, n) and returns z. func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int { z.neg = false @@ -646,7 +613,6 @@ func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int { return z } - // ModInverse sets z to the multiplicative inverse of g in the group ℤ/pℤ (where // p is a prime) and returns z. func (z *Int) ModInverse(g, p *Int) *Int { @@ -660,7 +626,6 @@ func (z *Int) ModInverse(g, p *Int) *Int { return z } - // Lsh sets z = x << n and returns z. func (z *Int) Lsh(x *Int, n uint) *Int { z.abs = z.abs.shl(x.abs, n) @@ -668,7 +633,6 @@ func (z *Int) Lsh(x *Int, n uint) *Int { return z } - // Rsh sets z = x >> n and returns z. func (z *Int) Rsh(x *Int, n uint) *Int { if x.neg { @@ -685,7 +649,6 @@ func (z *Int) Rsh(x *Int, n uint) *Int { return z } - // Bit returns the value of the i'th bit of z. That is, it // returns (z>>i)&1. The bit index i must be >= 0. func (z *Int) Bit(i int) uint { @@ -700,7 +663,6 @@ func (z *Int) Bit(i int) uint { return z.abs.bit(uint(i)) } - // SetBit sets the i'th bit of z to bit and returns z. // That is, if bit is 1 SetBit sets z = x | (1 << i); // if bit is 0 it sets z = x &^ (1 << i). If bit is not 0 or 1, @@ -721,7 +683,6 @@ func (z *Int) SetBit(x *Int, i int, b uint) *Int { return z } - // And sets z = x & y and returns z. func (z *Int) And(x, y *Int) *Int { if x.neg == y.neg { @@ -752,7 +713,6 @@ func (z *Int) And(x, y *Int) *Int { return z } - // AndNot sets z = x &^ y and returns z. func (z *Int) AndNot(x, y *Int) *Int { if x.neg == y.neg { @@ -786,7 +746,6 @@ func (z *Int) AndNot(x, y *Int) *Int { return z } - // Or sets z = x | y and returns z. func (z *Int) Or(x, y *Int) *Int { if x.neg == y.neg { @@ -817,7 +776,6 @@ func (z *Int) Or(x, y *Int) *Int { return z } - // Xor sets z = x ^ y and returns z. func (z *Int) Xor(x, y *Int) *Int { if x.neg == y.neg { @@ -848,7 +806,6 @@ func (z *Int) Xor(x, y *Int) *Int { return z } - // Not sets z = ^x and returns z. func (z *Int) Not(x *Int) *Int { if x.neg { @@ -864,7 +821,6 @@ func (z *Int) Not(x *Int) *Int { return z } - // Gob codec version. Permits backward-compatible changes to the encoding. const intGobVersion byte = 1 @@ -880,7 +836,6 @@ func (z *Int) GobEncode() ([]byte, os.Error) { return buf[i:], nil } - // GobDecode implements the gob.GobDecoder interface. func (z *Int) GobDecode(buf []byte) os.Error { if len(buf) == 0 { diff --git a/src/pkg/big/int_test.go b/src/pkg/big/int_test.go index 7f33c9522a..593d38ebb8 100755 --- a/src/pkg/big/int_test.go +++ b/src/pkg/big/int_test.go @@ -13,7 +13,6 @@ import ( "testing/quick" ) - func isNormalized(x *Int) bool { if len(x.abs) == 0 { return !x.neg @@ -22,13 +21,11 @@ func isNormalized(x *Int) bool { return x.abs[len(x.abs)-1] != 0 } - type funZZ func(z, x, y *Int) *Int type argZZ struct { z, x, y *Int } - var sumZZ = []argZZ{ {NewInt(0), NewInt(0), NewInt(0)}, {NewInt(1), NewInt(1), NewInt(0)}, @@ -38,7 +35,6 @@ var sumZZ = []argZZ{ {NewInt(-1111111110), NewInt(-123456789), NewInt(-987654321)}, } - var prodZZ = []argZZ{ {NewInt(0), NewInt(0), NewInt(0)}, {NewInt(0), NewInt(1), NewInt(0)}, @@ -47,7 +43,6 @@ var prodZZ = []argZZ{ // TODO(gri) add larger products } - func TestSignZ(t *testing.T) { var zero Int for _, a := range sumZZ { @@ -59,7 +54,6 @@ func TestSignZ(t *testing.T) { } } - func TestSetZ(t *testing.T) { for _, a := range sumZZ { var z Int @@ -73,7 +67,6 @@ func TestSetZ(t *testing.T) { } } - func TestAbsZ(t *testing.T) { var zero Int for _, a := range sumZZ { @@ -90,7 +83,6 @@ func TestAbsZ(t *testing.T) { } } - func testFunZZ(t *testing.T, msg string, f funZZ, a argZZ) { var z Int f(&z, a.x, a.y) @@ -102,7 +94,6 @@ func testFunZZ(t *testing.T, msg string, f funZZ, a argZZ) { } } - func TestSumZZ(t *testing.T) { AddZZ := func(z, x, y *Int) *Int { return z.Add(x, y) } SubZZ := func(z, x, y *Int) *Int { return z.Sub(x, y) } @@ -121,7 +112,6 @@ func TestSumZZ(t *testing.T) { } } - func TestProdZZ(t *testing.T) { MulZZ := func(z, x, y *Int) *Int { return z.Mul(x, y) } for _, a := range prodZZ { @@ -133,7 +123,6 @@ func TestProdZZ(t *testing.T) { } } - // mulBytes returns x*y via grade school multiplication. Both inputs // and the result are assumed to be in big-endian representation (to // match the semantics of Int.Bytes and Int.SetBytes). @@ -166,7 +155,6 @@ func mulBytes(x, y []byte) []byte { return z[i:] } - func checkMul(a, b []byte) bool { var x, y, z1 Int x.SetBytes(a) @@ -179,14 +167,12 @@ func checkMul(a, b []byte) bool { return z1.Cmp(&z2) == 0 } - func TestMul(t *testing.T) { if err := quick.Check(checkMul, nil); err != nil { t.Error(err) } } - var mulRangesZ = []struct { a, b int64 prod string @@ -212,7 +198,6 @@ var mulRangesZ = []struct { }, } - func TestMulRangeZ(t *testing.T) { var tmp Int // test entirely positive ranges @@ -231,7 +216,6 @@ func TestMulRangeZ(t *testing.T) { } } - var stringTests = []struct { in string out string @@ -280,7 +264,6 @@ var stringTests = []struct { {"1001010111", "1001010111", 2, 0x257, true}, } - func format(base int) string { switch base { case 2: @@ -293,7 +276,6 @@ func format(base int) string { return "%d" } - func TestGetString(t *testing.T) { z := new(Int) for i, test := range stringTests { @@ -316,7 +298,6 @@ func TestGetString(t *testing.T) { } } - func TestSetString(t *testing.T) { tmp := new(Int) for i, test := range stringTests { @@ -347,7 +328,6 @@ func TestSetString(t *testing.T) { } } - var formatTests = []struct { input string format string @@ -407,7 +387,6 @@ var formatTests = []struct { "12 49 ad 25 94 c3 7c eb 0b 27 84 c4 ce 0b f3 8a ce 40 8e 21 1a 7c aa b2 43 08 a8 2e 8f 10 00 00 00 00 00 00 00 00 00 00 00 00"}, } - func TestFormat(t *testing.T) { for i, test := range formatTests { var x *Int @@ -425,7 +404,6 @@ func TestFormat(t *testing.T) { } } - var scanTests = []struct { input string format string @@ -449,7 +427,6 @@ var scanTests = []struct { {"0XABC 12", "%v", "2748", 3}, } - func TestScan(t *testing.T) { var buf bytes.Buffer for i, test := range scanTests { @@ -468,7 +445,6 @@ func TestScan(t *testing.T) { } } - // Examples from the Go Language Spec, section "Arithmetic operators" var divisionSignsTests = []struct { x, y int64 @@ -483,7 +459,6 @@ var divisionSignsTests = []struct { {8, 4, 2, 0, 2, 0}, } - func TestDivisionSigns(t *testing.T) { for i, test := range divisionSignsTests { x := NewInt(test.x) @@ -541,7 +516,6 @@ func TestDivisionSigns(t *testing.T) { } } - func checkSetBytes(b []byte) bool { hex1 := hex.EncodeToString(new(Int).SetBytes(b).Bytes()) hex2 := hex.EncodeToString(b) @@ -557,27 +531,23 @@ func checkSetBytes(b []byte) bool { return hex1 == hex2 } - func TestSetBytes(t *testing.T) { if err := quick.Check(checkSetBytes, nil); err != nil { t.Error(err) } } - func checkBytes(b []byte) bool { b2 := new(Int).SetBytes(b).Bytes() return bytes.Compare(b, b2) == 0 } - func TestBytes(t *testing.T) { if err := quick.Check(checkSetBytes, nil); err != nil { t.Error(err) } } - func checkQuo(x, y []byte) bool { u := new(Int).SetBytes(x) v := new(Int).SetBytes(y) @@ -600,7 +570,6 @@ func checkQuo(x, y []byte) bool { return uprime.Cmp(u) == 0 } - var quoTests = []struct { x, y string q, r string @@ -619,7 +588,6 @@ var quoTests = []struct { }, } - func TestQuo(t *testing.T) { if err := quick.Check(checkQuo, nil); err != nil { t.Error(err) @@ -640,7 +608,6 @@ func TestQuo(t *testing.T) { } } - func TestQuoStepD6(t *testing.T) { // See Knuth, Volume 2, section 4.3.1, exercise 21. This code exercises // a code path which only triggers 1 in 10^{-19} cases. @@ -660,7 +627,6 @@ func TestQuoStepD6(t *testing.T) { } } - var bitLenTests = []struct { in string out int @@ -679,7 +645,6 @@ var bitLenTests = []struct { {"-0x4000000000000000000000", 87}, } - func TestBitLen(t *testing.T) { for i, test := range bitLenTests { x, ok := new(Int).SetString(test.in, 0) @@ -694,7 +659,6 @@ func TestBitLen(t *testing.T) { } } - var expTests = []struct { x, y, m string out string @@ -719,7 +683,6 @@ var expTests = []struct { }, } - func TestExp(t *testing.T) { for i, test := range expTests { x, ok1 := new(Int).SetString(test.x, 0) @@ -750,7 +713,6 @@ func TestExp(t *testing.T) { } } - func checkGcd(aBytes, bBytes []byte) bool { a := new(Int).SetBytes(aBytes) b := new(Int).SetBytes(bBytes) @@ -767,7 +729,6 @@ func checkGcd(aBytes, bBytes []byte) bool { return x.Cmp(d) == 0 } - var gcdTests = []struct { a, b int64 d, x, y int64 @@ -775,7 +736,6 @@ var gcdTests = []struct { {120, 23, 1, -9, 47}, } - func TestGcd(t *testing.T) { for i, test := range gcdTests { a := NewInt(test.a) @@ -801,7 +761,6 @@ func TestGcd(t *testing.T) { quick.Check(checkGcd, nil) } - var primes = []string{ "2", "3", @@ -827,7 +786,6 @@ var primes = []string{ "203956878356401977405765866929034577280193993314348263094772646453283062722701277632936616063144088173312372882677123879538709400158306567338328279154499698366071906766440037074217117805690872792848149112022286332144876183376326512083574821647933992961249917319836219304274280243803104015000563790123", } - var composites = []string{ "21284175091214687912771199898307297748211672914763848041968395774954376176754", "6084766654921918907427900243509372380954290099172559290432744450051395395951", @@ -835,7 +793,6 @@ var composites = []string{ "82793403787388584738507275144194252681", } - func TestProbablyPrime(t *testing.T) { nreps := 20 if testing.Short() { @@ -859,14 +816,12 @@ func TestProbablyPrime(t *testing.T) { } } - type intShiftTest struct { in string shift uint out string } - var rshTests = []intShiftTest{ {"0", 0, "0"}, {"-0", 0, "0"}, @@ -894,7 +849,6 @@ var rshTests = []intShiftTest{ {"340282366920938463463374607431768211456", 128, "1"}, } - func TestRsh(t *testing.T) { for i, test := range rshTests { in, _ := new(Int).SetString(test.in, 10) @@ -910,7 +864,6 @@ func TestRsh(t *testing.T) { } } - func TestRshSelf(t *testing.T) { for i, test := range rshTests { z, _ := new(Int).SetString(test.in, 10) @@ -926,7 +879,6 @@ func TestRshSelf(t *testing.T) { } } - var lshTests = []intShiftTest{ {"0", 0, "0"}, {"0", 1, "0"}, @@ -949,7 +901,6 @@ var lshTests = []intShiftTest{ {"1", 128, "340282366920938463463374607431768211456"}, } - func TestLsh(t *testing.T) { for i, test := range lshTests { in, _ := new(Int).SetString(test.in, 10) @@ -965,7 +916,6 @@ func TestLsh(t *testing.T) { } } - func TestLshSelf(t *testing.T) { for i, test := range lshTests { z, _ := new(Int).SetString(test.in, 10) @@ -981,7 +931,6 @@ func TestLshSelf(t *testing.T) { } } - func TestLshRsh(t *testing.T) { for i, test := range rshTests { in, _ := new(Int).SetString(test.in, 10) @@ -1009,7 +958,6 @@ func TestLshRsh(t *testing.T) { } } - var int64Tests = []int64{ 0, 1, @@ -1023,7 +971,6 @@ var int64Tests = []int64{ -9223372036854775808, } - func TestInt64(t *testing.T) { for i, testVal := range int64Tests { in := NewInt(testVal) @@ -1035,7 +982,6 @@ func TestInt64(t *testing.T) { } } - var bitwiseTests = []struct { x, y string and, or, xor, andNot string @@ -1079,7 +1025,6 @@ var bitwiseTests = []struct { }, } - type bitFun func(z, x, y *Int) *Int func testBitFun(t *testing.T, msg string, f bitFun, x, y *Int, exp string) { @@ -1092,7 +1037,6 @@ func testBitFun(t *testing.T, msg string, f bitFun, x, y *Int, exp string) { } } - func testBitFunSelf(t *testing.T, msg string, f bitFun, x, y *Int, exp string) { self := new(Int) self.Set(x) @@ -1105,7 +1049,6 @@ func testBitFunSelf(t *testing.T, msg string, f bitFun, x, y *Int, exp string) { } } - func altBit(x *Int, i int) uint { z := new(Int).Rsh(x, uint(i)) z = z.And(z, NewInt(1)) @@ -1115,7 +1058,6 @@ func altBit(x *Int, i int) uint { return 0 } - func altSetBit(z *Int, x *Int, i int, b uint) *Int { one := NewInt(1) m := one.Lsh(one, uint(i)) @@ -1128,7 +1070,6 @@ func altSetBit(z *Int, x *Int, i int, b uint) *Int { panic("set bit is not 0 or 1") } - func testBitset(t *testing.T, x *Int) { n := x.BitLen() z := new(Int).Set(x) @@ -1166,7 +1107,6 @@ func testBitset(t *testing.T, x *Int) { } } - var bitsetTests = []struct { x string i int @@ -1186,7 +1126,6 @@ var bitsetTests = []struct { {"-0x2000000000000000000000000001", 110, 1}, } - func TestBitSet(t *testing.T) { for _, test := range bitwiseTests { x := new(Int) @@ -1207,7 +1146,6 @@ func TestBitSet(t *testing.T) { } } - func BenchmarkBitset(b *testing.B) { z := new(Int) z.SetBit(z, 512, 1) @@ -1218,7 +1156,6 @@ func BenchmarkBitset(b *testing.B) { } } - func BenchmarkBitsetNeg(b *testing.B) { z := NewInt(-1) z.SetBit(z, 512, 0) @@ -1229,7 +1166,6 @@ func BenchmarkBitsetNeg(b *testing.B) { } } - func BenchmarkBitsetOrig(b *testing.B) { z := new(Int) altSetBit(z, z, 512, 1) @@ -1240,7 +1176,6 @@ func BenchmarkBitsetOrig(b *testing.B) { } } - func BenchmarkBitsetNegOrig(b *testing.B) { z := NewInt(-1) altSetBit(z, z, 512, 0) @@ -1251,7 +1186,6 @@ func BenchmarkBitsetNegOrig(b *testing.B) { } } - func TestBitwise(t *testing.T) { x := new(Int) y := new(Int) @@ -1270,7 +1204,6 @@ func TestBitwise(t *testing.T) { } } - var notTests = []struct { in string out string @@ -1286,7 +1219,6 @@ var notTests = []struct { }, } - func TestNot(t *testing.T) { in := new(Int) out := new(Int) @@ -1305,7 +1237,6 @@ func TestNot(t *testing.T) { } } - var modInverseTests = []struct { element string prime string @@ -1315,7 +1246,6 @@ var modInverseTests = []struct { {"239487239847", "2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919"}, } - func TestModInverse(t *testing.T) { var element, prime Int one := NewInt(1) @@ -1331,7 +1261,6 @@ func TestModInverse(t *testing.T) { } } - // used by TestIntGobEncoding and TestRatGobEncoding var gobEncodingTests = []string{ "0", diff --git a/src/pkg/big/nat.go b/src/pkg/big/nat.go index 6755832bec..be3aff29d1 100755 --- a/src/pkg/big/nat.go +++ b/src/pkg/big/nat.go @@ -24,7 +24,6 @@ import ( "rand" ) - // An unsigned integer x of the form // // x = x[n-1]*_B^(n-1) + x[n-2]*_B^(n-2) + ... + x[1]*_B + x[0] @@ -45,14 +44,12 @@ var ( natTen = nat{10} ) - func (z nat) clear() { for i := range z { z[i] = 0 } } - func (z nat) norm() nat { i := len(z) for i > 0 && z[i-1] == 0 { @@ -61,7 +58,6 @@ func (z nat) norm() nat { return z[0:i] } - func (z nat) make(n int) nat { if n <= cap(z) { return z[0:n] // reuse z @@ -72,7 +68,6 @@ func (z nat) make(n int) nat { return make(nat, n, n+e) } - func (z nat) setWord(x Word) nat { if x == 0 { return z.make(0) @@ -82,7 +77,6 @@ func (z nat) setWord(x Word) nat { return z } - func (z nat) setUint64(x uint64) nat { // single-digit values if w := Word(x); uint64(w) == x { @@ -105,14 +99,12 @@ func (z nat) setUint64(x uint64) nat { return z } - func (z nat) set(x nat) nat { z = z.make(len(x)) copy(z, x) return z } - func (z nat) add(x, y nat) nat { m := len(x) n := len(y) @@ -139,7 +131,6 @@ func (z nat) add(x, y nat) nat { return z.norm() } - func (z nat) sub(x, y nat) nat { m := len(x) n := len(y) @@ -168,7 +159,6 @@ func (z nat) sub(x, y nat) nat { return z.norm() } - func (x nat) cmp(y nat) (r int) { m := len(x) n := len(y) @@ -196,7 +186,6 @@ func (x nat) cmp(y nat) (r int) { return } - func (z nat) mulAddWW(x nat, y, r Word) nat { m := len(x) if m == 0 || y == 0 { @@ -210,7 +199,6 @@ func (z nat) mulAddWW(x nat, y, r Word) nat { return z.norm() } - // basicMul multiplies x and y and leaves the result in z. // The (non-normalized) result is placed in z[0 : len(x) + len(y)]. func basicMul(z, x, y nat) { @@ -222,7 +210,6 @@ func basicMul(z, x, y nat) { } } - // Fast version of z[0:n+n>>1].add(z[0:n+n>>1], x[0:n]) w/o bounds checks. // Factored out for readability - do not use outside karatsuba. func karatsubaAdd(z, x nat, n int) { @@ -231,7 +218,6 @@ func karatsubaAdd(z, x nat, n int) { } } - // Like karatsubaAdd, but does subtract. func karatsubaSub(z, x nat, n int) { if c := subVV(z[0:n], z, x); c != 0 { @@ -239,7 +225,6 @@ func karatsubaSub(z, x nat, n int) { } } - // Operands that are shorter than karatsubaThreshold are multiplied using // "grade school" multiplication; for longer operands the Karatsuba algorithm // is used. @@ -344,13 +329,11 @@ func karatsuba(z, x, y nat) { } } - // alias returns true if x and y share the same base array. func alias(x, y nat) bool { return cap(x) > 0 && cap(y) > 0 && &x[0:cap(x)][cap(x)-1] == &y[0:cap(y)][cap(y)-1] } - // addAt implements z += x*(1<<(_W*i)); z must be long enough. // (we don't use nat.add because we need z to stay the same // slice, and we don't need to normalize z after each addition) @@ -365,7 +348,6 @@ func addAt(z, x nat, i int) { } } - func max(x, y int) int { if x > y { return x @@ -373,7 +355,6 @@ func max(x, y int) int { return y } - // karatsubaLen computes an approximation to the maximum k <= n such that // k = p<= 0. Thus, the // result is the largest number that can be divided repeatedly by 2 before @@ -387,7 +368,6 @@ func karatsubaLen(n int) int { return n << i } - func (z nat) mul(x, y nat) nat { m := len(x) n := len(y) @@ -455,7 +435,6 @@ func (z nat) mul(x, y nat) nat { return z.norm() } - // mulRange computes the product of all the unsigned integers in the // range [a, b] inclusively. If a > b (empty range), the result is 1. func (z nat) mulRange(a, b uint64) nat { @@ -474,7 +453,6 @@ func (z nat) mulRange(a, b uint64) nat { return z.mul(nat(nil).mulRange(a, m), nat(nil).mulRange(m+1, b)) } - // q = (x-r)/y, with 0 <= r < y func (z nat) divW(x nat, y Word) (q nat, r Word) { m := len(x) @@ -495,7 +473,6 @@ func (z nat) divW(x nat, y Word) (q nat, r Word) { return } - func (z nat) div(z2, u, v nat) (q, r nat) { if len(v) == 0 { panic("division by zero") @@ -523,7 +500,6 @@ func (z nat) div(z2, u, v nat) (q, r nat) { return } - // q = (uIn-r)/v, with 0 <= r < y // Uses z as storage for q, and u as storage for r if possible. // See Knuth, Volume 2, section 4.3.1, Algorithm D. @@ -602,7 +578,6 @@ func (z nat) divLarge(u, uIn, v nat) (q, r nat) { return q, r } - // Length of x in bits. x must be normalized. func (x nat) bitLen() int { if i := len(x) - 1; i >= 0 { @@ -611,7 +586,6 @@ func (x nat) bitLen() int { return 0 } - // MaxBase is the largest number base accepted for string conversions. const MaxBase = 'z' - 'a' + 10 + 1 // = hexValue('z') + 1 @@ -629,7 +603,6 @@ func hexValue(ch int) Word { return Word(d) } - // scan sets z to the natural number corresponding to the longest possible prefix // read from r representing an unsigned integer in a given conversion base. // It returns z, the actual conversion base used, and an error, if any. In the @@ -727,21 +700,18 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) { return z.norm(), int(b), nil } - // Character sets for string conversion. const ( lowercaseDigits = "0123456789abcdefghijklmnopqrstuvwxyz" uppercaseDigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) - // decimalString returns a decimal representation of x. // It calls x.string with the charset "0123456789". func (x nat) decimalString() string { return x.string(lowercaseDigits[0:10]) } - // string converts x to a string using digits from a charset; a digit with // value d is represented by charset[d]. The conversion base is determined // by len(charset), which must be >= 2. @@ -863,7 +833,6 @@ func (x nat) string(charset string) string { return string(s[i:]) } - const deBruijn32 = 0x077CB531 var deBruijn32Lookup = []byte{ @@ -880,7 +849,6 @@ var deBruijn64Lookup = []byte{ 54, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19, 9, 13, 8, 7, 6, } - // trailingZeroBits returns the number of consecutive zero bits on the right // side of the given Word. // See Knuth, volume 4, section 7.3.1 @@ -905,7 +873,6 @@ func trailingZeroBits(x Word) int { return 0 } - // z = x << s func (z nat) shl(x nat, s uint) nat { m := len(x) @@ -922,7 +889,6 @@ func (z nat) shl(x nat, s uint) nat { return z.norm() } - // z = x >> s func (z nat) shr(x nat, s uint) nat { m := len(x) @@ -938,7 +904,6 @@ func (z nat) shr(x nat, s uint) nat { return z.norm() } - func (z nat) setBit(x nat, i uint, b uint) nat { j := int(i / _W) m := Word(1) << (i % _W) @@ -966,7 +931,6 @@ func (z nat) setBit(x nat, i uint, b uint) nat { panic("set bit is not 0 or 1") } - func (z nat) bit(i uint) uint { j := int(i / _W) if j >= len(z) { @@ -975,7 +939,6 @@ func (z nat) bit(i uint) uint { return uint(z[j] >> (i % _W) & 1) } - func (z nat) and(x, y nat) nat { m := len(x) n := len(y) @@ -992,7 +955,6 @@ func (z nat) and(x, y nat) nat { return z.norm() } - func (z nat) andNot(x, y nat) nat { m := len(x) n := len(y) @@ -1010,7 +972,6 @@ func (z nat) andNot(x, y nat) nat { return z.norm() } - func (z nat) or(x, y nat) nat { m := len(x) n := len(y) @@ -1030,7 +991,6 @@ func (z nat) or(x, y nat) nat { return z.norm() } - func (z nat) xor(x, y nat) nat { m := len(x) n := len(y) @@ -1050,13 +1010,11 @@ func (z nat) xor(x, y nat) nat { return z.norm() } - // greaterThan returns true iff (x1<<_W + x2) > (y1<<_W + y2) func greaterThan(x1, x2, y1, y2 Word) bool { return x1 > y1 || x1 == y1 && x2 > y2 } - // modW returns x % d. func (x nat) modW(d Word) (r Word) { // TODO(agl): we don't actually need to store the q value. @@ -1065,7 +1023,6 @@ func (x nat) modW(d Word) (r Word) { return divWVW(q, 0, x, d) } - // powersOfTwoDecompose finds q and k with x = q * 1<= len(z)*_S. The value of z is encoded in the // slice buf[i:]. The number i of unused bytes at the beginning of @@ -1294,7 +1247,6 @@ func (z nat) bytes(buf []byte) (i int) { return } - // setBytes interprets buf as the bytes of a big-endian unsigned // integer, sets z to that value, and returns z. func (z nat) setBytes(buf []byte) nat { diff --git a/src/pkg/big/nat_test.go b/src/pkg/big/nat_test.go index fd93592ddc..71d0860878 100755 --- a/src/pkg/big/nat_test.go +++ b/src/pkg/big/nat_test.go @@ -31,7 +31,6 @@ var cmpTests = []struct { {nat{34986, 41, 105, 1957}, nat{56, 7458, 104, 1957}, 1}, } - func TestCmp(t *testing.T) { for i, a := range cmpTests { r := a.x.cmp(a.y) @@ -41,13 +40,11 @@ func TestCmp(t *testing.T) { } } - type funNN func(z, x, y nat) nat type argNN struct { z, x, y nat } - var sumNN = []argNN{ {}, {nat{1}, nil, nat{1}}, @@ -57,7 +54,6 @@ var sumNN = []argNN{ {nat{0, 0, 0, 1}, nat{0, 0, _M}, nat{0, 0, 1}}, } - var prodNN = []argNN{ {}, {nil, nil, nil}, @@ -69,7 +65,6 @@ var prodNN = []argNN{ {nat{4, 11, 20, 30, 20, 11, 4}, nat{1, 2, 3, 4}, nat{4, 3, 2, 1}}, } - func TestSet(t *testing.T) { for _, a := range sumNN { z := nat(nil).set(a.z) @@ -79,7 +74,6 @@ func TestSet(t *testing.T) { } } - func testFunNN(t *testing.T, msg string, f funNN, a argNN) { z := f(nil, a.x, a.y) if z.cmp(a.z) != 0 { @@ -87,7 +81,6 @@ func testFunNN(t *testing.T, msg string, f funNN, a argNN) { } } - func TestFunNN(t *testing.T) { for _, a := range sumNN { arg := a @@ -112,7 +105,6 @@ func TestFunNN(t *testing.T) { } } - var mulRangesN = []struct { a, b uint64 prod string @@ -135,7 +127,6 @@ var mulRangesN = []struct { }, } - func TestMulRangeN(t *testing.T) { for i, r := range mulRangesN { prod := nat(nil).mulRange(r.a, r.b).decimalString() @@ -145,7 +136,6 @@ func TestMulRangeN(t *testing.T) { } } - var mulArg, mulTmp nat func init() { @@ -156,7 +146,6 @@ func init() { } } - func benchmarkMulLoad() { for j := 1; j <= 10; j++ { x := mulArg[0 : j*100] @@ -164,14 +153,12 @@ func benchmarkMulLoad() { } } - func BenchmarkMul(b *testing.B) { for i := 0; i < b.N; i++ { benchmarkMulLoad() } } - func toString(x nat, charset string) string { base := len(charset) @@ -201,7 +188,6 @@ func toString(x nat, charset string) string { return string(s[i:]) } - var strTests = []struct { x nat // nat value to be converted c string // conversion charset @@ -219,7 +205,6 @@ var strTests = []struct { {nat{0x309663e6}, uppercaseDigits[0:32], "O9COV6"}, } - func TestString(t *testing.T) { for _, a := range strTests { s := a.x.string(a.c) @@ -240,7 +225,6 @@ func TestString(t *testing.T) { } } - var natScanTests = []struct { s string // string to be scanned base int // input base @@ -284,7 +268,6 @@ var natScanTests = []struct { {"0XDEADBEEF", 0, nat{0xdeadbeef}, 16, true, 0}, } - func TestScanBase(t *testing.T) { for _, a := range natScanTests { r := strings.NewReader(a.s) @@ -315,7 +298,6 @@ func TestScanBase(t *testing.T) { } } - var pi = "3" + "14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651" + "32823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461" + @@ -369,7 +351,6 @@ var pi = "3" + "88281613323166636528619326686336062735676303544776280350450777235547105859548702790814356240145171806246436267" + "94561275318134078330336254232783944975382437205835311477119926063813346776879695970309833913077109870408591337" - // Test case for BenchmarkScanPi. func TestScanPi(t *testing.T) { var x nat @@ -382,7 +363,6 @@ func TestScanPi(t *testing.T) { } } - func BenchmarkScanPi(b *testing.B) { for i := 0; i < b.N; i++ { var x nat @@ -390,7 +370,6 @@ func BenchmarkScanPi(b *testing.B) { } } - const ( // 314**271 // base 2: 2249 digits @@ -417,67 +396,54 @@ const ( longExponent = 27182 ) - func BenchmarkScanShort2(b *testing.B) { ScanHelper(b, 2, shortBase, shortExponent) } - func BenchmarkScanShort8(b *testing.B) { ScanHelper(b, 8, shortBase, shortExponent) } - func BenchmarkScanSort10(b *testing.B) { ScanHelper(b, 10, shortBase, shortExponent) } - func BenchmarkScanShort16(b *testing.B) { ScanHelper(b, 16, shortBase, shortExponent) } - func BenchmarkScanMedium2(b *testing.B) { ScanHelper(b, 2, mediumBase, mediumExponent) } - func BenchmarkScanMedium8(b *testing.B) { ScanHelper(b, 8, mediumBase, mediumExponent) } - func BenchmarkScanMedium10(b *testing.B) { ScanHelper(b, 10, mediumBase, mediumExponent) } - func BenchmarkScanMedium16(b *testing.B) { ScanHelper(b, 16, mediumBase, mediumExponent) } - func BenchmarkScanLong2(b *testing.B) { ScanHelper(b, 2, longBase, longExponent) } - func BenchmarkScanLong8(b *testing.B) { ScanHelper(b, 8, longBase, longExponent) } - func BenchmarkScanLong10(b *testing.B) { ScanHelper(b, 10, longBase, longExponent) } - func BenchmarkScanLong16(b *testing.B) { ScanHelper(b, 16, longBase, longExponent) } - func ScanHelper(b *testing.B, base int, xv, yv Word) { b.StopTimer() var x, y, z nat @@ -497,67 +463,54 @@ func ScanHelper(b *testing.B, base int, xv, yv Word) { } } - func BenchmarkStringShort2(b *testing.B) { StringHelper(b, 2, shortBase, shortExponent) } - func BenchmarkStringShort8(b *testing.B) { StringHelper(b, 8, shortBase, shortExponent) } - func BenchmarkStringShort10(b *testing.B) { StringHelper(b, 10, shortBase, shortExponent) } - func BenchmarkStringShort16(b *testing.B) { StringHelper(b, 16, shortBase, shortExponent) } - func BenchmarkStringMedium2(b *testing.B) { StringHelper(b, 2, mediumBase, mediumExponent) } - func BenchmarkStringMedium8(b *testing.B) { StringHelper(b, 8, mediumBase, mediumExponent) } - func BenchmarkStringMedium10(b *testing.B) { StringHelper(b, 10, mediumBase, mediumExponent) } - func BenchmarkStringMedium16(b *testing.B) { StringHelper(b, 16, mediumBase, mediumExponent) } - func BenchmarkStringLong2(b *testing.B) { StringHelper(b, 2, longBase, longExponent) } - func BenchmarkStringLong8(b *testing.B) { StringHelper(b, 8, longBase, longExponent) } - func BenchmarkStringLong10(b *testing.B) { StringHelper(b, 10, longBase, longExponent) } - func BenchmarkStringLong16(b *testing.B) { StringHelper(b, 16, longBase, longExponent) } - func StringHelper(b *testing.B, base int, xv, yv Word) { b.StopTimer() var x, y, z nat @@ -571,7 +524,6 @@ func StringHelper(b *testing.B, base int, xv, yv Word) { } } - func TestLeadingZeros(t *testing.T) { var x Word = _B >> 1 for i := 0; i <= _W; i++ { @@ -582,14 +534,12 @@ func TestLeadingZeros(t *testing.T) { } } - type shiftTest struct { in nat shift uint out nat } - var leftShiftTests = []shiftTest{ {nil, 0, nil}, {nil, 1, nil}, @@ -599,7 +549,6 @@ var leftShiftTests = []shiftTest{ {nat{1 << (_W - 1), 0}, 1, nat{0, 1}}, } - func TestShiftLeft(t *testing.T) { for i, test := range leftShiftTests { var z nat @@ -613,7 +562,6 @@ func TestShiftLeft(t *testing.T) { } } - var rightShiftTests = []shiftTest{ {nil, 0, nil}, {nil, 1, nil}, @@ -624,7 +572,6 @@ var rightShiftTests = []shiftTest{ {nat{2, 1, 1}, 1, nat{1<<(_W-1) + 1, 1 << (_W - 1)}}, } - func TestShiftRight(t *testing.T) { for i, test := range rightShiftTests { var z nat @@ -638,24 +585,20 @@ func TestShiftRight(t *testing.T) { } } - type modWTest struct { in string dividend string out string } - var modWTests32 = []modWTest{ {"23492635982634928349238759823742", "252341", "220170"}, } - var modWTests64 = []modWTest{ {"6527895462947293856291561095690465243862946", "524326975699234", "375066989628668"}, } - func runModWTests(t *testing.T, tests []modWTest) { for i, test := range tests { in, _ := new(Int).SetString(test.in, 10) @@ -669,7 +612,6 @@ func runModWTests(t *testing.T, tests []modWTest) { } } - func TestModW(t *testing.T) { if _W >= 32 { runModWTests(t, modWTests32) @@ -679,7 +621,6 @@ func TestModW(t *testing.T) { } } - func TestTrailingZeroBits(t *testing.T) { var x Word x-- @@ -708,7 +649,6 @@ var expNNTests = []struct { }, } - func TestExpNN(t *testing.T) { for i, test := range expNNTests { x, _, _ := nat(nil).scan(strings.NewReader(test.x), 0) diff --git a/src/pkg/big/rat.go b/src/pkg/big/rat.go index b61cbb966b..327b9bd9ca 100644 --- a/src/pkg/big/rat.go +++ b/src/pkg/big/rat.go @@ -20,13 +20,11 @@ type Rat struct { b nat } - // NewRat creates a new Rat with numerator a and denominator b. func NewRat(a, b int64) *Rat { return new(Rat).SetFrac64(a, b) } - // SetFrac sets z to a/b and returns z. func (z *Rat) SetFrac(a, b *Int) *Rat { z.a.Set(a) @@ -35,7 +33,6 @@ func (z *Rat) SetFrac(a, b *Int) *Rat { return z.norm() } - // SetFrac64 sets z to a/b and returns z. func (z *Rat) SetFrac64(a, b int64) *Rat { z.a.SetInt64(a) @@ -47,7 +44,6 @@ func (z *Rat) SetFrac64(a, b int64) *Rat { return z.norm() } - // SetInt sets z to x (by making a copy of x) and returns z. func (z *Rat) SetInt(x *Int) *Rat { z.a.Set(x) @@ -55,7 +51,6 @@ func (z *Rat) SetInt(x *Int) *Rat { return z } - // SetInt64 sets z to x and returns z. func (z *Rat) SetInt64(x int64) *Rat { z.a.SetInt64(x) @@ -63,7 +58,6 @@ func (z *Rat) SetInt64(x int64) *Rat { return z } - // Sign returns: // // -1 if x < 0 @@ -74,13 +68,11 @@ func (x *Rat) Sign() int { return x.a.Sign() } - // IsInt returns true if the denominator of x is 1. func (x *Rat) IsInt() bool { return len(x.b) == 1 && x.b[0] == 1 } - // Num returns the numerator of z; it may be <= 0. // The result is a reference to z's numerator; it // may change if a new value is assigned to z. @@ -88,7 +80,6 @@ func (z *Rat) Num() *Int { return &z.a } - // Denom returns the denominator of z; it is always > 0. // The result is a reference to z's denominator; it // may change if a new value is assigned to z. @@ -96,7 +87,6 @@ func (z *Rat) Denom() *Int { return &Int{false, z.b} } - func gcd(x, y nat) nat { // Euclidean algorithm. var a, b nat @@ -111,7 +101,6 @@ func gcd(x, y nat) nat { return a } - func (z *Rat) norm() *Rat { f := gcd(z.a.abs, z.b) if len(z.a.abs) == 0 { @@ -127,7 +116,6 @@ func (z *Rat) norm() *Rat { return z } - func mulNat(x *Int, y nat) *Int { var z Int z.abs = z.abs.mul(x.abs, y) @@ -135,7 +123,6 @@ func mulNat(x *Int, y nat) *Int { return &z } - // Cmp compares x and y and returns: // // -1 if x < y @@ -146,7 +133,6 @@ func (x *Rat) Cmp(y *Rat) (r int) { return mulNat(&x.a, y.b).Cmp(mulNat(&y.a, x.b)) } - // Abs sets z to |x| (the absolute value of x) and returns z. func (z *Rat) Abs(x *Rat) *Rat { z.a.Abs(&x.a) @@ -154,7 +140,6 @@ func (z *Rat) Abs(x *Rat) *Rat { return z } - // Add sets z to the sum x+y and returns z. func (z *Rat) Add(x, y *Rat) *Rat { a1 := mulNat(&x.a, y.b) @@ -164,7 +149,6 @@ func (z *Rat) Add(x, y *Rat) *Rat { return z.norm() } - // Sub sets z to the difference x-y and returns z. func (z *Rat) Sub(x, y *Rat) *Rat { a1 := mulNat(&x.a, y.b) @@ -174,7 +158,6 @@ func (z *Rat) Sub(x, y *Rat) *Rat { return z.norm() } - // Mul sets z to the product x*y and returns z. func (z *Rat) Mul(x, y *Rat) *Rat { z.a.Mul(&x.a, &y.a) @@ -182,7 +165,6 @@ func (z *Rat) Mul(x, y *Rat) *Rat { return z.norm() } - // Quo sets z to the quotient x/y and returns z. // If y == 0, a division-by-zero run-time panic occurs. func (z *Rat) Quo(x, y *Rat) *Rat { @@ -197,7 +179,6 @@ func (z *Rat) Quo(x, y *Rat) *Rat { return z.norm() } - // Neg sets z to -x (by making a copy of x if necessary) and returns z. func (z *Rat) Neg(x *Rat) *Rat { z.a.Neg(&x.a) @@ -205,7 +186,6 @@ func (z *Rat) Neg(x *Rat) *Rat { return z } - // Set sets z to x (by making a copy of x if necessary) and returns z. func (z *Rat) Set(x *Rat) *Rat { z.a.Set(&x.a) @@ -213,12 +193,10 @@ func (z *Rat) Set(x *Rat) *Rat { return z } - func ratTok(ch int) bool { return strings.IndexRune("+-/0123456789.eE", ch) >= 0 } - // Scan is a support routine for fmt.Scanner. It accepts the formats // 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent. func (z *Rat) Scan(s fmt.ScanState, ch int) os.Error { @@ -235,7 +213,6 @@ func (z *Rat) Scan(s fmt.ScanState, ch int) os.Error { return nil } - // SetString sets z to the value of s and returns z and a boolean indicating // success. s can be given as a fraction "a/b" or as a floating-point number // optionally followed by an exponent. If the operation failed, the value of z @@ -294,13 +271,11 @@ func (z *Rat) SetString(s string) (*Rat, bool) { return z, true } - // String returns a string representation of z in the form "a/b" (even if b == 1). func (z *Rat) String() string { return z.a.String() + "/" + z.b.decimalString() } - // RatString returns a string representation of z in the form "a/b" if b != 1, // and in the form "a" if b == 1. func (z *Rat) RatString() string { @@ -310,7 +285,6 @@ func (z *Rat) RatString() string { return z.String() } - // FloatString returns a string representation of z in decimal form with prec // digits of precision after the decimal point and the last digit rounded. func (z *Rat) FloatString(prec int) string { @@ -356,7 +330,6 @@ func (z *Rat) FloatString(prec int) string { return s } - // Gob codec version. Permits backward-compatible changes to the encoding. const ratGobVersion byte = 1 @@ -380,7 +353,6 @@ func (z *Rat) GobEncode() ([]byte, os.Error) { return buf[j:], nil } - // GobDecode implements the gob.GobDecoder interface. func (z *Rat) GobDecode(buf []byte) os.Error { if len(buf) == 0 { diff --git a/src/pkg/big/rat_test.go b/src/pkg/big/rat_test.go index e64505ea3c..dbc5bb6cca 100644 --- a/src/pkg/big/rat_test.go +++ b/src/pkg/big/rat_test.go @@ -11,7 +11,6 @@ import ( "testing" ) - var setStringTests = []struct { in, out string ok bool @@ -57,7 +56,6 @@ func TestRatSetString(t *testing.T) { } } - func TestRatScan(t *testing.T) { var buf bytes.Buffer for i, test := range setStringTests { @@ -80,7 +78,6 @@ func TestRatScan(t *testing.T) { } } - var floatStringTests = []struct { in string prec int @@ -113,7 +110,6 @@ func TestFloatString(t *testing.T) { } } - func TestRatSign(t *testing.T) { zero := NewRat(0, 1) for _, a := range setStringTests { @@ -127,7 +123,6 @@ func TestRatSign(t *testing.T) { } } - var ratCmpTests = []struct { rat1, rat2 string out int @@ -155,7 +150,6 @@ func TestRatCmp(t *testing.T) { } } - func TestIsInt(t *testing.T) { one := NewInt(1) for _, a := range setStringTests { @@ -169,7 +163,6 @@ func TestIsInt(t *testing.T) { } } - func TestRatAbs(t *testing.T) { zero := NewRat(0, 1) for _, a := range setStringTests { @@ -187,7 +180,6 @@ func TestRatAbs(t *testing.T) { } } - type ratBinFun func(z, x, y *Rat) *Rat type ratBinArg struct { x, y, z string @@ -204,7 +196,6 @@ func testRatBin(t *testing.T, i int, name string, f ratBinFun, a ratBinArg) { } } - var ratBinTests = []struct { x, y string sum, prod string @@ -261,7 +252,6 @@ func TestRatBin(t *testing.T) { } } - func TestIssue820(t *testing.T) { x := NewRat(3, 1) y := NewRat(2, 1) @@ -287,7 +277,6 @@ func TestIssue820(t *testing.T) { } } - var setFrac64Tests = []struct { a, b int64 out string @@ -310,7 +299,6 @@ func TestRatSetFrac64Rat(t *testing.T) { } } - func TestRatGobEncoding(t *testing.T) { var medium bytes.Buffer enc := gob.NewEncoder(&medium) diff --git a/src/pkg/bufio/bufio.go b/src/pkg/bufio/bufio.go index cb2667b283..727ebfdbbe 100644 --- a/src/pkg/bufio/bufio.go +++ b/src/pkg/bufio/bufio.go @@ -15,7 +15,6 @@ import ( "utf8" ) - const ( defaultBufSize = 4096 ) @@ -42,7 +41,6 @@ func (b BufSizeError) String() string { return "bufio: bad buffer size " + strconv.Itoa(int(b)) } - // Buffered input. // Reader implements buffering for an io.Reader object. @@ -375,7 +373,6 @@ func (b *Reader) ReadString(delim byte) (line string, err os.Error) { return string(bytes), e } - // buffered output // Writer implements buffering for an io.Writer object. diff --git a/src/pkg/bufio/bufio_test.go b/src/pkg/bufio/bufio_test.go index 5709213c83..82c73d36a9 100644 --- a/src/pkg/bufio/bufio_test.go +++ b/src/pkg/bufio/bufio_test.go @@ -76,7 +76,6 @@ func TestReaderSimple(t *testing.T) { } } - type readMaker struct { name string fn func(io.Reader) io.Reader diff --git a/src/pkg/bytes/buffer_test.go b/src/pkg/bytes/buffer_test.go index 14f9501416..06d2a65c67 100644 --- a/src/pkg/bytes/buffer_test.go +++ b/src/pkg/bytes/buffer_test.go @@ -12,7 +12,6 @@ import ( "utf8" ) - const N = 10000 // make this bigger for a larger (and slower) test var data string // test data for write tests var bytes []byte // test data; same as data but as a slice. @@ -47,7 +46,6 @@ func check(t *testing.T, testname string, buf *Buffer, s string) { } } - // Fill buf through n writes of string fus. // The initial contents of buf corresponds to the string s; // the result is the final contents of buf returned as a string. @@ -67,7 +65,6 @@ func fillString(t *testing.T, testname string, buf *Buffer, s string, n int, fus return s } - // Fill buf through n writes of byte slice fub. // The initial contents of buf corresponds to the string s; // the result is the final contents of buf returned as a string. @@ -87,19 +84,16 @@ func fillBytes(t *testing.T, testname string, buf *Buffer, s string, n int, fub return s } - func TestNewBuffer(t *testing.T) { buf := NewBuffer(bytes) check(t, "NewBuffer", buf, data) } - func TestNewBufferString(t *testing.T) { buf := NewBufferString(data) check(t, "NewBufferString", buf, data) } - // Empty buf through repeated reads into fub. // The initial contents of buf corresponds to the string s. func empty(t *testing.T, testname string, buf *Buffer, s string, fub []byte) { @@ -120,7 +114,6 @@ func empty(t *testing.T, testname string, buf *Buffer, s string, fub []byte) { check(t, testname+" (empty 4)", buf, "") } - func TestBasicOperations(t *testing.T) { var buf Buffer @@ -175,7 +168,6 @@ func TestBasicOperations(t *testing.T) { } } - func TestLargeStringWrites(t *testing.T) { var buf Buffer limit := 30 @@ -189,7 +181,6 @@ func TestLargeStringWrites(t *testing.T) { check(t, "TestLargeStringWrites (3)", &buf, "") } - func TestLargeByteWrites(t *testing.T) { var buf Buffer limit := 30 @@ -203,7 +194,6 @@ func TestLargeByteWrites(t *testing.T) { check(t, "TestLargeByteWrites (3)", &buf, "") } - func TestLargeStringReads(t *testing.T) { var buf Buffer for i := 3; i < 30; i += 3 { @@ -213,7 +203,6 @@ func TestLargeStringReads(t *testing.T) { check(t, "TestLargeStringReads (3)", &buf, "") } - func TestLargeByteReads(t *testing.T) { var buf Buffer for i := 3; i < 30; i += 3 { @@ -223,7 +212,6 @@ func TestLargeByteReads(t *testing.T) { check(t, "TestLargeByteReads (3)", &buf, "") } - func TestMixedReadsAndWrites(t *testing.T) { var buf Buffer s := "" @@ -243,7 +231,6 @@ func TestMixedReadsAndWrites(t *testing.T) { empty(t, "TestMixedReadsAndWrites (2)", &buf, s, make([]byte, buf.Len())) } - func TestNil(t *testing.T) { var b *Buffer if b.String() != "" { @@ -251,7 +238,6 @@ func TestNil(t *testing.T) { } } - func TestReadFrom(t *testing.T) { var buf Buffer for i := 3; i < 30; i += 3 { @@ -262,7 +248,6 @@ func TestReadFrom(t *testing.T) { } } - func TestWriteTo(t *testing.T) { var buf Buffer for i := 3; i < 30; i += 3 { @@ -273,7 +258,6 @@ func TestWriteTo(t *testing.T) { } } - func TestRuneIO(t *testing.T) { const NRune = 1000 // Built a test array while we write the data @@ -323,7 +307,6 @@ func TestRuneIO(t *testing.T) { } } - func TestNext(t *testing.T) { b := []byte{0, 1, 2, 3, 4} tmp := make([]byte, 5) diff --git a/src/pkg/bytes/bytes.go b/src/pkg/bytes/bytes.go index 3cec60f96c..5119fce949 100644 --- a/src/pkg/bytes/bytes.go +++ b/src/pkg/bytes/bytes.go @@ -398,7 +398,6 @@ func ToTitleSpecial(_case unicode.SpecialCase, s []byte) []byte { return Map(func(r int) int { return _case.ToTitle(r) }, s) } - // isSeparator reports whether the rune could mark a word boundary. // TODO: update when package unicode captures more of the properties. func isSeparator(rune int) bool { diff --git a/src/pkg/bytes/bytes_test.go b/src/pkg/bytes/bytes_test.go index 7539353091..9444358a85 100644 --- a/src/pkg/bytes/bytes_test.go +++ b/src/pkg/bytes/bytes_test.go @@ -329,7 +329,6 @@ func TestExplode(t *testing.T) { } } - type SplitTest struct { s string sep string @@ -662,7 +661,6 @@ func TestRunes(t *testing.T) { } } - type TrimTest struct { f func([]byte, string) []byte in, cutset, out string diff --git a/src/pkg/compress/flate/deflate_test.go b/src/pkg/compress/flate/deflate_test.go index 2ac811c389..930823685f 100644 --- a/src/pkg/compress/flate/deflate_test.go +++ b/src/pkg/compress/flate/deflate_test.go @@ -225,7 +225,6 @@ func testSync(t *testing.T, level int, input []byte, name string) { } } - func testToFromWithLevel(t *testing.T, level int, input []byte, name string) os.Error { buffer := bytes.NewBuffer(nil) w := NewWriter(buffer, level) diff --git a/src/pkg/container/heap/heap.go b/src/pkg/container/heap/heap.go index 5b68827df0..2dfe5b43ca 100644 --- a/src/pkg/container/heap/heap.go +++ b/src/pkg/container/heap/heap.go @@ -21,7 +21,6 @@ type Interface interface { Pop() interface{} } - // A heap must be initialized before any of the heap operations // can be used. Init is idempotent with respect to the heap invariants // and may be called whenever the heap invariants may have been invalidated. @@ -35,7 +34,6 @@ func Init(h Interface) { } } - // Push pushes the element x onto the heap. The complexity is // O(log(n)) where n = h.Len(). // @@ -44,7 +42,6 @@ func Push(h Interface, x interface{}) { up(h, h.Len()-1) } - // Pop removes the minimum element (according to Less) from the heap // and returns it. The complexity is O(log(n)) where n = h.Len(). // Same as Remove(h, 0). @@ -56,7 +53,6 @@ func Pop(h Interface) interface{} { return h.Pop() } - // Remove removes the element at index i from the heap. // The complexity is O(log(n)) where n = h.Len(). // @@ -70,7 +66,6 @@ func Remove(h Interface, i int) interface{} { return h.Pop() } - func up(h Interface, j int) { for { i := (j - 1) / 2 // parent @@ -82,7 +77,6 @@ func up(h Interface, j int) { } } - func down(h Interface, i, n int) { for { j1 := 2*i + 1 diff --git a/src/pkg/container/heap/heap_test.go b/src/pkg/container/heap/heap_test.go index 5eb54374ab..c5c1f76e1e 100644 --- a/src/pkg/container/heap/heap_test.go +++ b/src/pkg/container/heap/heap_test.go @@ -10,17 +10,14 @@ import ( . "container/heap" ) - type myHeap struct { // A vector.Vector implements sort.Interface except for Less, // and it implements Push and Pop as required for heap.Interface. vector.Vector } - func (h *myHeap) Less(i, j int) bool { return h.At(i).(int) < h.At(j).(int) } - func (h *myHeap) verify(t *testing.T, i int) { n := h.Len() j1 := 2*i + 1 @@ -41,7 +38,6 @@ func (h *myHeap) verify(t *testing.T, i int) { } } - func TestInit0(t *testing.T) { h := new(myHeap) for i := 20; i > 0; i-- { @@ -59,7 +55,6 @@ func TestInit0(t *testing.T) { } } - func TestInit1(t *testing.T) { h := new(myHeap) for i := 20; i > 0; i-- { @@ -77,7 +72,6 @@ func TestInit1(t *testing.T) { } } - func Test(t *testing.T) { h := new(myHeap) h.verify(t, 0) @@ -105,7 +99,6 @@ func Test(t *testing.T) { } } - func TestRemove0(t *testing.T) { h := new(myHeap) for i := 0; i < 10; i++ { @@ -123,7 +116,6 @@ func TestRemove0(t *testing.T) { } } - func TestRemove1(t *testing.T) { h := new(myHeap) for i := 0; i < 10; i++ { @@ -140,7 +132,6 @@ func TestRemove1(t *testing.T) { } } - func TestRemove2(t *testing.T) { N := 10 diff --git a/src/pkg/container/ring/ring.go b/src/pkg/container/ring/ring.go index cc870ce936..1d96918d37 100644 --- a/src/pkg/container/ring/ring.go +++ b/src/pkg/container/ring/ring.go @@ -16,14 +16,12 @@ type Ring struct { Value interface{} // for use by client; untouched by this library } - func (r *Ring) init() *Ring { r.next = r r.prev = r return r } - // Next returns the next ring element. r must not be empty. func (r *Ring) Next() *Ring { if r.next == nil { @@ -32,7 +30,6 @@ func (r *Ring) Next() *Ring { return r.next } - // Prev returns the previous ring element. r must not be empty. func (r *Ring) Prev() *Ring { if r.next == nil { @@ -41,7 +38,6 @@ func (r *Ring) Prev() *Ring { return r.prev } - // Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0) // in the ring and returns that ring element. r must not be empty. // @@ -62,7 +58,6 @@ func (r *Ring) Move(n int) *Ring { return r } - // New creates a ring of n elements. func New(n int) *Ring { if n <= 0 { @@ -79,7 +74,6 @@ func New(n int) *Ring { return r } - // Link connects ring r with with ring s such that r.Next() // becomes s and returns the original value for r.Next(). // r must not be empty. @@ -110,7 +104,6 @@ func (r *Ring) Link(s *Ring) *Ring { return n } - // Unlink removes n % r.Len() elements from the ring r, starting // at r.Next(). If n % r.Len() == 0, r remains unchanged. // The result is the removed subring. r must not be empty. @@ -122,7 +115,6 @@ func (r *Ring) Unlink(n int) *Ring { return r.Link(r.Move(n + 1)) } - // Len computes the number of elements in ring r. // It executes in time proportional to the number of elements. // @@ -137,7 +129,6 @@ func (r *Ring) Len() int { return n } - // Do calls function f on each element of the ring, in forward order. // The behavior of Do is undefined if f changes *r. func (r *Ring) Do(f func(interface{})) { diff --git a/src/pkg/container/ring/ring_test.go b/src/pkg/container/ring/ring_test.go index 778c083d02..099d92b25b 100644 --- a/src/pkg/container/ring/ring_test.go +++ b/src/pkg/container/ring/ring_test.go @@ -9,7 +9,6 @@ import ( "testing" ) - // For debugging - keep around. func dump(r *Ring) { if r == nil { @@ -24,7 +23,6 @@ func dump(r *Ring) { fmt.Println() } - func verify(t *testing.T, r *Ring, N int, sum int) { // Len n := r.Len() @@ -96,7 +94,6 @@ func verify(t *testing.T, r *Ring, N int, sum int) { } } - func TestCornerCases(t *testing.T) { var ( r0 *Ring @@ -118,7 +115,6 @@ func TestCornerCases(t *testing.T) { verify(t, &r1, 1, 0) } - func makeN(n int) *Ring { r := New(n) for i := 1; i <= n; i++ { @@ -130,7 +126,6 @@ func makeN(n int) *Ring { func sumN(n int) int { return (n*n + n) / 2 } - func TestNew(t *testing.T) { for i := 0; i < 10; i++ { r := New(i) @@ -142,7 +137,6 @@ func TestNew(t *testing.T) { } } - func TestLink1(t *testing.T) { r1a := makeN(1) var r1b Ring @@ -163,7 +157,6 @@ func TestLink1(t *testing.T) { verify(t, r2b, 1, 0) } - func TestLink2(t *testing.T) { var r0 *Ring r1a := &Ring{Value: 42} @@ -183,7 +176,6 @@ func TestLink2(t *testing.T) { verify(t, r10, 12, sumN(10)+42+77) } - func TestLink3(t *testing.T) { var r Ring n := 1 @@ -193,7 +185,6 @@ func TestLink3(t *testing.T) { } } - func TestUnlink(t *testing.T) { r10 := makeN(10) s10 := r10.Move(6) @@ -215,7 +206,6 @@ func TestUnlink(t *testing.T) { verify(t, r10, 9, sum10-2) } - func TestLinkUnlink(t *testing.T) { for i := 1; i < 4; i++ { ri := New(i) diff --git a/src/pkg/container/vector/defs.go b/src/pkg/container/vector/defs.go index bfb5481fb8..6d6b2ac81a 100644 --- a/src/pkg/container/vector/defs.go +++ b/src/pkg/container/vector/defs.go @@ -6,29 +6,24 @@ // Vectors grow and shrink dynamically as necessary. package vector - // Vector is a container for numbered sequences of elements of type interface{}. // A vector's length and capacity adjusts automatically as necessary. // The zero value for Vector is an empty vector ready to use. type Vector []interface{} - // IntVector is a container for numbered sequences of elements of type int. // A vector's length and capacity adjusts automatically as necessary. // The zero value for IntVector is an empty vector ready to use. type IntVector []int - // StringVector is a container for numbered sequences of elements of type string. // A vector's length and capacity adjusts automatically as necessary. // The zero value for StringVector is an empty vector ready to use. type StringVector []string - // Initial underlying array size const initialSize = 8 - // Partial sort.Interface support // LessInterface provides partial support of the sort.Interface. @@ -36,16 +31,13 @@ type LessInterface interface { Less(y interface{}) bool } - // Less returns a boolean denoting whether the i'th element is less than the j'th element. func (p *Vector) Less(i, j int) bool { return (*p)[i].(LessInterface).Less((*p)[j]) } - // sort.Interface support // Less returns a boolean denoting whether the i'th element is less than the j'th element. func (p *IntVector) Less(i, j int) bool { return (*p)[i] < (*p)[j] } - // Less returns a boolean denoting whether the i'th element is less than the j'th element. func (p *StringVector) Less(i, j int) bool { return (*p)[i] < (*p)[j] } diff --git a/src/pkg/container/vector/intvector.go b/src/pkg/container/vector/intvector.go index 5ad9e294b7..aa88cfeb36 100644 --- a/src/pkg/container/vector/intvector.go +++ b/src/pkg/container/vector/intvector.go @@ -7,7 +7,6 @@ package vector - func (p *IntVector) realloc(length, capacity int) (b []int) { if capacity < initialSize { capacity = initialSize @@ -21,7 +20,6 @@ func (p *IntVector) realloc(length, capacity int) (b []int) { return } - // Insert n elements at position i. func (p *IntVector) Expand(i, n int) { a := *p @@ -51,11 +49,9 @@ func (p *IntVector) Expand(i, n int) { *p = a } - // Insert n elements at the end of a vector. func (p *IntVector) Extend(n int) { p.Expand(len(*p), n) } - // Resize changes the length and capacity of a vector. // If the new length is shorter than the current length, Resize discards // trailing elements. If the new length is longer than the current length, @@ -80,30 +76,24 @@ func (p *IntVector) Resize(length, capacity int) *IntVector { return p } - // Len returns the number of elements in the vector. // Same as len(*p). func (p *IntVector) Len() int { return len(*p) } - // Cap returns the capacity of the vector; that is, the // maximum length the vector can grow without resizing. // Same as cap(*p). func (p *IntVector) Cap() int { return cap(*p) } - // At returns the i'th element of the vector. func (p *IntVector) At(i int) int { return (*p)[i] } - // Set sets the i'th element of the vector to value x. func (p *IntVector) Set(i int, x int) { (*p)[i] = x } - // Last returns the element in the vector of highest index. func (p *IntVector) Last() int { return (*p)[len(*p)-1] } - // Copy makes a copy of the vector and returns it. func (p *IntVector) Copy() IntVector { arr := make(IntVector, len(*p)) @@ -111,7 +101,6 @@ func (p *IntVector) Copy() IntVector { return arr } - // Insert inserts into the vector an element of value x before // the current element at index i. func (p *IntVector) Insert(i int, x int) { @@ -119,7 +108,6 @@ func (p *IntVector) Insert(i int, x int) { (*p)[i] = x } - // Delete deletes the i'th element of the vector. The gap is closed so the old // element at index i+1 has index i afterwards. func (p *IntVector) Delete(i int) { @@ -132,7 +120,6 @@ func (p *IntVector) Delete(i int) { *p = a[0 : n-1] } - // InsertVector inserts into the vector the contents of the vector // x such that the 0th element of x appears at index i after insertion. func (p *IntVector) InsertVector(i int, x *IntVector) { @@ -142,7 +129,6 @@ func (p *IntVector) InsertVector(i int, x *IntVector) { copy((*p)[i:i+len(b)], b) } - // Cut deletes elements i through j-1, inclusive. func (p *IntVector) Cut(i, j int) { a := *p @@ -158,7 +144,6 @@ func (p *IntVector) Cut(i, j int) { *p = a[0:m] } - // Slice returns a new sub-vector by slicing the old one to extract slice [i:j]. // The elements are copied. The original vector is unchanged. func (p *IntVector) Slice(i, j int) *IntVector { @@ -168,13 +153,11 @@ func (p *IntVector) Slice(i, j int) *IntVector { return &s } - // Convenience wrappers // Push appends x to the end of the vector. func (p *IntVector) Push(x int) { p.Insert(len(*p), x) } - // Pop deletes the last element of the vector. func (p *IntVector) Pop() int { a := *p @@ -187,18 +170,15 @@ func (p *IntVector) Pop() int { return x } - // AppendVector appends the entire vector x to the end of this vector. func (p *IntVector) AppendVector(x *IntVector) { p.InsertVector(len(*p), x) } - // Swap exchanges the elements at indexes i and j. func (p *IntVector) Swap(i, j int) { a := *p a[i], a[j] = a[j], a[i] } - // Do calls function f for each element of the vector, in order. // The behavior of Do is undefined if f changes *p. func (p *IntVector) Do(f func(elem int)) { diff --git a/src/pkg/container/vector/intvector_test.go b/src/pkg/container/vector/intvector_test.go index 1e38a1982f..b825af9122 100644 --- a/src/pkg/container/vector/intvector_test.go +++ b/src/pkg/container/vector/intvector_test.go @@ -9,7 +9,6 @@ package vector import "testing" - func TestIntZeroLen(t *testing.T) { a := new(IntVector) if a.Len() != 0 { @@ -27,7 +26,6 @@ func TestIntZeroLen(t *testing.T) { } } - func TestIntResize(t *testing.T) { var a IntVector checkSize(t, &a, 0, 0) @@ -40,7 +38,6 @@ func TestIntResize(t *testing.T) { checkSize(t, a.Resize(11, 100), 11, 100) } - func TestIntResize2(t *testing.T) { var a IntVector checkSize(t, &a, 0, 0) @@ -62,7 +59,6 @@ func TestIntResize2(t *testing.T) { } } - func checkIntZero(t *testing.T, a *IntVector, i int) { for j := 0; j < i; j++ { if a.At(j) == intzero { @@ -82,7 +78,6 @@ func checkIntZero(t *testing.T, a *IntVector, i int) { } } - func TestIntTrailingElements(t *testing.T) { var a IntVector for i := 0; i < 10; i++ { @@ -95,7 +90,6 @@ func TestIntTrailingElements(t *testing.T) { checkIntZero(t, &a, 5) } - func TestIntAccess(t *testing.T) { const n = 100 var a IntVector @@ -120,7 +114,6 @@ func TestIntAccess(t *testing.T) { } } - func TestIntInsertDeleteClear(t *testing.T) { const n = 100 var a IntVector @@ -207,7 +200,6 @@ func TestIntInsertDeleteClear(t *testing.T) { } } - func verify_sliceInt(t *testing.T, x *IntVector, elt, i, j int) { for k := i; k < j; k++ { if elem2IntValue(x.At(k)) != int2IntValue(elt) { @@ -223,7 +215,6 @@ func verify_sliceInt(t *testing.T, x *IntVector, elt, i, j int) { } } - func verify_patternInt(t *testing.T, x *IntVector, a, b, c int) { n := a + b + c if x.Len() != n { @@ -237,7 +228,6 @@ func verify_patternInt(t *testing.T, x *IntVector, a, b, c int) { verify_sliceInt(t, x, 0, a+b, n) } - func make_vectorInt(elt, len int) *IntVector { x := new(IntVector).Resize(len, 0) for i := 0; i < len; i++ { @@ -246,7 +236,6 @@ func make_vectorInt(elt, len int) *IntVector { return x } - func TestIntInsertVector(t *testing.T) { // 1 a := make_vectorInt(0, 0) @@ -270,7 +259,6 @@ func TestIntInsertVector(t *testing.T) { verify_patternInt(t, a, 8, 1000, 2) } - func TestIntDo(t *testing.T) { const n = 25 const salt = 17 @@ -325,7 +313,6 @@ func TestIntDo(t *testing.T) { } - func TestIntVectorCopy(t *testing.T) { // verify Copy() returns a copy, not simply a slice of the original vector const Len = 10 diff --git a/src/pkg/container/vector/nogen_test.go b/src/pkg/container/vector/nogen_test.go index 790d3749fc..7b6a25952b 100644 --- a/src/pkg/container/vector/nogen_test.go +++ b/src/pkg/container/vector/nogen_test.go @@ -4,7 +4,6 @@ package vector - import ( "fmt" "sort" @@ -17,28 +16,23 @@ var ( strzero string ) - func int2Value(x int) int { return x } func int2IntValue(x int) int { return x } func int2StrValue(x int) string { return string(x) } - func elem2Value(x interface{}) int { return x.(int) } func elem2IntValue(x int) int { return x } func elem2StrValue(x string) string { return x } - func intf2Value(x interface{}) int { return x.(int) } func intf2IntValue(x interface{}) int { return x.(int) } func intf2StrValue(x interface{}) string { return x.(string) } - type VectorInterface interface { Len() int Cap() int } - func checkSize(t *testing.T, v VectorInterface, len, cap int) { if v.Len() != len { t.Errorf("%T expected len = %d; found %d", v, len, v.Len()) @@ -48,10 +42,8 @@ func checkSize(t *testing.T, v VectorInterface, len, cap int) { } } - func val(i int) int { return i*991 - 1234 } - func TestSorting(t *testing.T) { const n = 100 @@ -72,5 +64,4 @@ func TestSorting(t *testing.T) { } } - func tname(x interface{}) string { return fmt.Sprintf("%T: ", x) } diff --git a/src/pkg/container/vector/numbers_test.go b/src/pkg/container/vector/numbers_test.go index b83b0bfeef..abe01a8fb1 100644 --- a/src/pkg/container/vector/numbers_test.go +++ b/src/pkg/container/vector/numbers_test.go @@ -11,10 +11,8 @@ import ( "testing" ) - const memTestN = 1000000 - func s(n uint64) string { str := fmt.Sprintf("%d", n) lens := len(str) @@ -31,7 +29,6 @@ func s(n uint64) string { return strings.Join(a, " ") } - func TestVectorNums(t *testing.T) { if testing.Short() { return @@ -52,7 +49,6 @@ func TestVectorNums(t *testing.T) { t.Logf("%T.Push(%#v), n = %s: Alloc/n = %.2f\n", v, c, s(memTestN), float64(n)/memTestN) } - func TestIntVectorNums(t *testing.T) { if testing.Short() { return @@ -73,7 +69,6 @@ func TestIntVectorNums(t *testing.T) { t.Logf("%T.Push(%#v), n = %s: Alloc/n = %.2f\n", v, c, s(memTestN), float64(n)/memTestN) } - func TestStringVectorNums(t *testing.T) { if testing.Short() { return @@ -94,7 +89,6 @@ func TestStringVectorNums(t *testing.T) { t.Logf("%T.Push(%#v), n = %s: Alloc/n = %.2f\n", v, c, s(memTestN), float64(n)/memTestN) } - func BenchmarkVectorNums(b *testing.B) { c := int(0) var v Vector @@ -106,7 +100,6 @@ func BenchmarkVectorNums(b *testing.B) { } } - func BenchmarkIntVectorNums(b *testing.B) { c := int(0) var v IntVector @@ -118,7 +111,6 @@ func BenchmarkIntVectorNums(b *testing.B) { } } - func BenchmarkStringVectorNums(b *testing.B) { c := "" var v StringVector diff --git a/src/pkg/container/vector/stringvector.go b/src/pkg/container/vector/stringvector.go index 852685f5a1..dc81f06b74 100644 --- a/src/pkg/container/vector/stringvector.go +++ b/src/pkg/container/vector/stringvector.go @@ -7,7 +7,6 @@ package vector - func (p *StringVector) realloc(length, capacity int) (b []string) { if capacity < initialSize { capacity = initialSize @@ -21,7 +20,6 @@ func (p *StringVector) realloc(length, capacity int) (b []string) { return } - // Insert n elements at position i. func (p *StringVector) Expand(i, n int) { a := *p @@ -51,11 +49,9 @@ func (p *StringVector) Expand(i, n int) { *p = a } - // Insert n elements at the end of a vector. func (p *StringVector) Extend(n int) { p.Expand(len(*p), n) } - // Resize changes the length and capacity of a vector. // If the new length is shorter than the current length, Resize discards // trailing elements. If the new length is longer than the current length, @@ -80,30 +76,24 @@ func (p *StringVector) Resize(length, capacity int) *StringVector { return p } - // Len returns the number of elements in the vector. // Same as len(*p). func (p *StringVector) Len() int { return len(*p) } - // Cap returns the capacity of the vector; that is, the // maximum length the vector can grow without resizing. // Same as cap(*p). func (p *StringVector) Cap() int { return cap(*p) } - // At returns the i'th element of the vector. func (p *StringVector) At(i int) string { return (*p)[i] } - // Set sets the i'th element of the vector to value x. func (p *StringVector) Set(i int, x string) { (*p)[i] = x } - // Last returns the element in the vector of highest index. func (p *StringVector) Last() string { return (*p)[len(*p)-1] } - // Copy makes a copy of the vector and returns it. func (p *StringVector) Copy() StringVector { arr := make(StringVector, len(*p)) @@ -111,7 +101,6 @@ func (p *StringVector) Copy() StringVector { return arr } - // Insert inserts into the vector an element of value x before // the current element at index i. func (p *StringVector) Insert(i int, x string) { @@ -119,7 +108,6 @@ func (p *StringVector) Insert(i int, x string) { (*p)[i] = x } - // Delete deletes the i'th element of the vector. The gap is closed so the old // element at index i+1 has index i afterwards. func (p *StringVector) Delete(i int) { @@ -132,7 +120,6 @@ func (p *StringVector) Delete(i int) { *p = a[0 : n-1] } - // InsertVector inserts into the vector the contents of the vector // x such that the 0th element of x appears at index i after insertion. func (p *StringVector) InsertVector(i int, x *StringVector) { @@ -142,7 +129,6 @@ func (p *StringVector) InsertVector(i int, x *StringVector) { copy((*p)[i:i+len(b)], b) } - // Cut deletes elements i through j-1, inclusive. func (p *StringVector) Cut(i, j int) { a := *p @@ -158,7 +144,6 @@ func (p *StringVector) Cut(i, j int) { *p = a[0:m] } - // Slice returns a new sub-vector by slicing the old one to extract slice [i:j]. // The elements are copied. The original vector is unchanged. func (p *StringVector) Slice(i, j int) *StringVector { @@ -168,13 +153,11 @@ func (p *StringVector) Slice(i, j int) *StringVector { return &s } - // Convenience wrappers // Push appends x to the end of the vector. func (p *StringVector) Push(x string) { p.Insert(len(*p), x) } - // Pop deletes the last element of the vector. func (p *StringVector) Pop() string { a := *p @@ -187,18 +170,15 @@ func (p *StringVector) Pop() string { return x } - // AppendVector appends the entire vector x to the end of this vector. func (p *StringVector) AppendVector(x *StringVector) { p.InsertVector(len(*p), x) } - // Swap exchanges the elements at indexes i and j. func (p *StringVector) Swap(i, j int) { a := *p a[i], a[j] = a[j], a[i] } - // Do calls function f for each element of the vector, in order. // The behavior of Do is undefined if f changes *p. func (p *StringVector) Do(f func(elem string)) { diff --git a/src/pkg/container/vector/stringvector_test.go b/src/pkg/container/vector/stringvector_test.go index 776ae26dea..c75676f786 100644 --- a/src/pkg/container/vector/stringvector_test.go +++ b/src/pkg/container/vector/stringvector_test.go @@ -9,7 +9,6 @@ package vector import "testing" - func TestStrZeroLen(t *testing.T) { a := new(StringVector) if a.Len() != 0 { @@ -27,7 +26,6 @@ func TestStrZeroLen(t *testing.T) { } } - func TestStrResize(t *testing.T) { var a StringVector checkSize(t, &a, 0, 0) @@ -40,7 +38,6 @@ func TestStrResize(t *testing.T) { checkSize(t, a.Resize(11, 100), 11, 100) } - func TestStrResize2(t *testing.T) { var a StringVector checkSize(t, &a, 0, 0) @@ -62,7 +59,6 @@ func TestStrResize2(t *testing.T) { } } - func checkStrZero(t *testing.T, a *StringVector, i int) { for j := 0; j < i; j++ { if a.At(j) == strzero { @@ -82,7 +78,6 @@ func checkStrZero(t *testing.T, a *StringVector, i int) { } } - func TestStrTrailingElements(t *testing.T) { var a StringVector for i := 0; i < 10; i++ { @@ -95,7 +90,6 @@ func TestStrTrailingElements(t *testing.T) { checkStrZero(t, &a, 5) } - func TestStrAccess(t *testing.T) { const n = 100 var a StringVector @@ -120,7 +114,6 @@ func TestStrAccess(t *testing.T) { } } - func TestStrInsertDeleteClear(t *testing.T) { const n = 100 var a StringVector @@ -207,7 +200,6 @@ func TestStrInsertDeleteClear(t *testing.T) { } } - func verify_sliceStr(t *testing.T, x *StringVector, elt, i, j int) { for k := i; k < j; k++ { if elem2StrValue(x.At(k)) != int2StrValue(elt) { @@ -223,7 +215,6 @@ func verify_sliceStr(t *testing.T, x *StringVector, elt, i, j int) { } } - func verify_patternStr(t *testing.T, x *StringVector, a, b, c int) { n := a + b + c if x.Len() != n { @@ -237,7 +228,6 @@ func verify_patternStr(t *testing.T, x *StringVector, a, b, c int) { verify_sliceStr(t, x, 0, a+b, n) } - func make_vectorStr(elt, len int) *StringVector { x := new(StringVector).Resize(len, 0) for i := 0; i < len; i++ { @@ -246,7 +236,6 @@ func make_vectorStr(elt, len int) *StringVector { return x } - func TestStrInsertVector(t *testing.T) { // 1 a := make_vectorStr(0, 0) @@ -270,7 +259,6 @@ func TestStrInsertVector(t *testing.T) { verify_patternStr(t, a, 8, 1000, 2) } - func TestStrDo(t *testing.T) { const n = 25 const salt = 17 @@ -325,7 +313,6 @@ func TestStrDo(t *testing.T) { } - func TestStrVectorCopy(t *testing.T) { // verify Copy() returns a copy, not simply a slice of the original vector const Len = 10 diff --git a/src/pkg/container/vector/vector.go b/src/pkg/container/vector/vector.go index f43e4d23ca..8470ec067a 100644 --- a/src/pkg/container/vector/vector.go +++ b/src/pkg/container/vector/vector.go @@ -7,7 +7,6 @@ package vector - func (p *Vector) realloc(length, capacity int) (b []interface{}) { if capacity < initialSize { capacity = initialSize @@ -21,7 +20,6 @@ func (p *Vector) realloc(length, capacity int) (b []interface{}) { return } - // Insert n elements at position i. func (p *Vector) Expand(i, n int) { a := *p @@ -51,11 +49,9 @@ func (p *Vector) Expand(i, n int) { *p = a } - // Insert n elements at the end of a vector. func (p *Vector) Extend(n int) { p.Expand(len(*p), n) } - // Resize changes the length and capacity of a vector. // If the new length is shorter than the current length, Resize discards // trailing elements. If the new length is longer than the current length, @@ -80,30 +76,24 @@ func (p *Vector) Resize(length, capacity int) *Vector { return p } - // Len returns the number of elements in the vector. // Same as len(*p). func (p *Vector) Len() int { return len(*p) } - // Cap returns the capacity of the vector; that is, the // maximum length the vector can grow without resizing. // Same as cap(*p). func (p *Vector) Cap() int { return cap(*p) } - // At returns the i'th element of the vector. func (p *Vector) At(i int) interface{} { return (*p)[i] } - // Set sets the i'th element of the vector to value x. func (p *Vector) Set(i int, x interface{}) { (*p)[i] = x } - // Last returns the element in the vector of highest index. func (p *Vector) Last() interface{} { return (*p)[len(*p)-1] } - // Copy makes a copy of the vector and returns it. func (p *Vector) Copy() Vector { arr := make(Vector, len(*p)) @@ -111,7 +101,6 @@ func (p *Vector) Copy() Vector { return arr } - // Insert inserts into the vector an element of value x before // the current element at index i. func (p *Vector) Insert(i int, x interface{}) { @@ -119,7 +108,6 @@ func (p *Vector) Insert(i int, x interface{}) { (*p)[i] = x } - // Delete deletes the i'th element of the vector. The gap is closed so the old // element at index i+1 has index i afterwards. func (p *Vector) Delete(i int) { @@ -132,7 +120,6 @@ func (p *Vector) Delete(i int) { *p = a[0 : n-1] } - // InsertVector inserts into the vector the contents of the vector // x such that the 0th element of x appears at index i after insertion. func (p *Vector) InsertVector(i int, x *Vector) { @@ -142,7 +129,6 @@ func (p *Vector) InsertVector(i int, x *Vector) { copy((*p)[i:i+len(b)], b) } - // Cut deletes elements i through j-1, inclusive. func (p *Vector) Cut(i, j int) { a := *p @@ -158,7 +144,6 @@ func (p *Vector) Cut(i, j int) { *p = a[0:m] } - // Slice returns a new sub-vector by slicing the old one to extract slice [i:j]. // The elements are copied. The original vector is unchanged. func (p *Vector) Slice(i, j int) *Vector { @@ -168,13 +153,11 @@ func (p *Vector) Slice(i, j int) *Vector { return &s } - // Convenience wrappers // Push appends x to the end of the vector. func (p *Vector) Push(x interface{}) { p.Insert(len(*p), x) } - // Pop deletes the last element of the vector. func (p *Vector) Pop() interface{} { a := *p @@ -187,18 +170,15 @@ func (p *Vector) Pop() interface{} { return x } - // AppendVector appends the entire vector x to the end of this vector. func (p *Vector) AppendVector(x *Vector) { p.InsertVector(len(*p), x) } - // Swap exchanges the elements at indexes i and j. func (p *Vector) Swap(i, j int) { a := *p a[i], a[j] = a[j], a[i] } - // Do calls function f for each element of the vector, in order. // The behavior of Do is undefined if f changes *p. func (p *Vector) Do(f func(elem interface{})) { diff --git a/src/pkg/container/vector/vector_test.go b/src/pkg/container/vector/vector_test.go index a9c4ceb55a..a7f47b8c2a 100644 --- a/src/pkg/container/vector/vector_test.go +++ b/src/pkg/container/vector/vector_test.go @@ -9,7 +9,6 @@ package vector import "testing" - func TestZeroLen(t *testing.T) { a := new(Vector) if a.Len() != 0 { @@ -27,7 +26,6 @@ func TestZeroLen(t *testing.T) { } } - func TestResize(t *testing.T) { var a Vector checkSize(t, &a, 0, 0) @@ -40,7 +38,6 @@ func TestResize(t *testing.T) { checkSize(t, a.Resize(11, 100), 11, 100) } - func TestResize2(t *testing.T) { var a Vector checkSize(t, &a, 0, 0) @@ -62,7 +59,6 @@ func TestResize2(t *testing.T) { } } - func checkZero(t *testing.T, a *Vector, i int) { for j := 0; j < i; j++ { if a.At(j) == zero { @@ -82,7 +78,6 @@ func checkZero(t *testing.T, a *Vector, i int) { } } - func TestTrailingElements(t *testing.T) { var a Vector for i := 0; i < 10; i++ { @@ -95,7 +90,6 @@ func TestTrailingElements(t *testing.T) { checkZero(t, &a, 5) } - func TestAccess(t *testing.T) { const n = 100 var a Vector @@ -120,7 +114,6 @@ func TestAccess(t *testing.T) { } } - func TestInsertDeleteClear(t *testing.T) { const n = 100 var a Vector @@ -207,7 +200,6 @@ func TestInsertDeleteClear(t *testing.T) { } } - func verify_slice(t *testing.T, x *Vector, elt, i, j int) { for k := i; k < j; k++ { if elem2Value(x.At(k)) != int2Value(elt) { @@ -223,7 +215,6 @@ func verify_slice(t *testing.T, x *Vector, elt, i, j int) { } } - func verify_pattern(t *testing.T, x *Vector, a, b, c int) { n := a + b + c if x.Len() != n { @@ -237,7 +228,6 @@ func verify_pattern(t *testing.T, x *Vector, a, b, c int) { verify_slice(t, x, 0, a+b, n) } - func make_vector(elt, len int) *Vector { x := new(Vector).Resize(len, 0) for i := 0; i < len; i++ { @@ -246,7 +236,6 @@ func make_vector(elt, len int) *Vector { return x } - func TestInsertVector(t *testing.T) { // 1 a := make_vector(0, 0) @@ -270,7 +259,6 @@ func TestInsertVector(t *testing.T) { verify_pattern(t, a, 8, 1000, 2) } - func TestDo(t *testing.T) { const n = 25 const salt = 17 @@ -325,7 +313,6 @@ func TestDo(t *testing.T) { } - func TestVectorCopy(t *testing.T) { // verify Copy() returns a copy, not simply a slice of the original vector const Len = 10 diff --git a/src/pkg/crypto/ocsp/ocsp.go b/src/pkg/crypto/ocsp/ocsp.go index e725bded81..7ea7a1e825 100644 --- a/src/pkg/crypto/ocsp/ocsp.go +++ b/src/pkg/crypto/ocsp/ocsp.go @@ -33,7 +33,6 @@ const ( ocspUnauthorized = 5 ) - type certID struct { HashAlgorithm pkix.AlgorithmIdentifier NameHash []byte diff --git a/src/pkg/crypto/openpgp/canonical_text_test.go b/src/pkg/crypto/openpgp/canonical_text_test.go index 69ecf91a83..ccf2910cc6 100644 --- a/src/pkg/crypto/openpgp/canonical_text_test.go +++ b/src/pkg/crypto/openpgp/canonical_text_test.go @@ -30,7 +30,6 @@ func (r recordingHash) Size() int { panic("shouldn't be called") } - func testCanonicalText(t *testing.T, input, expected string) { r := recordingHash{bytes.NewBuffer(nil)} c := NewCanonicalTextHash(r) diff --git a/src/pkg/crypto/openpgp/packet/encrypted_key_test.go b/src/pkg/crypto/openpgp/packet/encrypted_key_test.go index b0a14904a8..b402245bda 100644 --- a/src/pkg/crypto/openpgp/packet/encrypted_key_test.go +++ b/src/pkg/crypto/openpgp/packet/encrypted_key_test.go @@ -21,7 +21,6 @@ func bigFromBase10(s string) *big.Int { return b } - var encryptedKeyPub = rsa.PublicKey{ E: 65537, N: bigFromBase10("115804063926007623305902631768113868327816898845124614648849934718568541074358183759250136204762053879858102352159854352727097033322663029387610959884180306668628526686121021235757016368038585212410610742029286439607686208110250133174279811431933746643015923132833417396844716207301518956640020862630546868823"), diff --git a/src/pkg/crypto/openpgp/s2k/s2k_test.go b/src/pkg/crypto/openpgp/s2k/s2k_test.go index 27d2e9ae0b..ec4012c238 100644 --- a/src/pkg/crypto/openpgp/s2k/s2k_test.go +++ b/src/pkg/crypto/openpgp/s2k/s2k_test.go @@ -37,7 +37,6 @@ func TestSalted(t *testing.T) { } } - var iteratedTests = []struct { in, out string }{ @@ -63,7 +62,6 @@ func TestIterated(t *testing.T) { } } - var parseTests = []struct { spec, in, out string }{ @@ -97,7 +95,6 @@ func TestParse(t *testing.T) { } } - func TestSerialize(t *testing.T) { buf := bytes.NewBuffer(nil) key := make([]byte, 16) diff --git a/src/pkg/crypto/tls/handshake_server_test.go b/src/pkg/crypto/tls/handshake_server_test.go index 5a1e754dcf..b77646e438 100644 --- a/src/pkg/crypto/tls/handshake_server_test.go +++ b/src/pkg/crypto/tls/handshake_server_test.go @@ -106,7 +106,6 @@ func TestClose(t *testing.T) { } } - func testServerScript(t *testing.T, name string, serverScript [][]byte, config *Config) { c, s := net.Pipe() srv := Server(s, config) diff --git a/src/pkg/crypto/tls/key_agreement.go b/src/pkg/crypto/tls/key_agreement.go index 48472fb6a9..a40d18fd9c 100644 --- a/src/pkg/crypto/tls/key_agreement.go +++ b/src/pkg/crypto/tls/key_agreement.go @@ -78,7 +78,6 @@ func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello return preMasterSecret, ckx, nil } - // md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the // concatenation of an MD5 and SHA1 hash. func md5SHA1Hash(slices ...[]byte) []byte { diff --git a/src/pkg/crypto/x509/verify.go b/src/pkg/crypto/x509/verify.go index cad863db82..4c0fecccbd 100644 --- a/src/pkg/crypto/x509/verify.go +++ b/src/pkg/crypto/x509/verify.go @@ -62,7 +62,6 @@ func (h HostnameError) String() string { return "certificate is valid for " + valid + ", not " + h.Host } - // UnknownAuthorityError results when the certificate issuer is unknown type UnknownAuthorityError struct { cert *Certificate diff --git a/src/pkg/csv/reader.go b/src/pkg/csv/reader.go index c59312ad6d..ea2c266a47 100644 --- a/src/pkg/csv/reader.go +++ b/src/pkg/csv/reader.go @@ -249,7 +249,6 @@ func (r *Reader) parseRecord() (fields []string, err os.Error) { panic("unreachable") } - // parseField parses the next field in the record. The read field is // located in r.field. Delim is the first character not part of the field // (r.Comma or '\n'). diff --git a/src/pkg/debug/dwarf/type_test.go b/src/pkg/debug/dwarf/type_test.go index e01f7353a4..b9470a4fcb 100644 --- a/src/pkg/debug/dwarf/type_test.go +++ b/src/pkg/debug/dwarf/type_test.go @@ -58,7 +58,6 @@ func machoData(t *testing.T, name string) *Data { return d } - func TestTypedefsELF(t *testing.T) { testTypedefs(t, elfData(t, "testdata/typedef.elf")) } func TestTypedefsMachO(t *testing.T) { diff --git a/src/pkg/debug/elf/elf.go b/src/pkg/debug/elf/elf.go index 5d45b24863..c71b230bd9 100644 --- a/src/pkg/debug/elf/elf.go +++ b/src/pkg/debug/elf/elf.go @@ -1289,7 +1289,6 @@ func (i R_SPARC) GoString() string { return stringName(uint32(i), rsparcStrings, // Magic number for the elf trampoline, chosen wisely to be an immediate value. const ARM_MAGIC_TRAMP_NUMBER = 0x5c000003 - // ELF32 File header. type Header32 struct { Ident [EI_NIDENT]byte /* File identification. */ @@ -1455,7 +1454,6 @@ func R_SYM64(info uint64) uint32 { return uint32(info >> 32) } func R_TYPE64(info uint64) uint32 { return uint32(info) } func R_INFO(sym, typ uint32) uint64 { return uint64(sym)<<32 | uint64(typ) } - // ELF64 symbol table entries. type Sym64 struct { Name uint32 /* String table index of name. */ diff --git a/src/pkg/debug/pe/file.go b/src/pkg/debug/pe/file.go index c934dd4477..d86d916f50 100644 --- a/src/pkg/debug/pe/file.go +++ b/src/pkg/debug/pe/file.go @@ -35,7 +35,6 @@ type SectionHeader struct { Characteristics uint32 } - type Section struct { SectionHeader @@ -69,7 +68,6 @@ func (s *Section) Data() ([]byte, os.Error) { // Open returns a new ReadSeeker reading the PE section. func (s *Section) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) } - type FormatError struct { off int64 msg string diff --git a/src/pkg/ebnf/ebnf.go b/src/pkg/ebnf/ebnf.go index 661afdd35c..69da117672 100644 --- a/src/pkg/ebnf/ebnf.go +++ b/src/pkg/ebnf/ebnf.go @@ -30,7 +30,6 @@ import ( "utf8" ) - // ---------------------------------------------------------------------------- // Internal representation @@ -100,7 +99,6 @@ type ( Grammar map[string]*Production ) - func (x Alternative) Pos() token.Pos { return x[0].Pos() } // the parser always generates non-empty Alternative func (x Sequence) Pos() token.Pos { return x[0].Pos() } // the parser always generates non-empty Sequences func (x *Name) Pos() token.Pos { return x.StringPos } @@ -112,7 +110,6 @@ func (x *Repetition) Pos() token.Pos { return x.Lbrace } func (x *Bad) Pos() token.Pos { return x.TokPos } func (x *Production) Pos() token.Pos { return x.Name.Pos() } - // ---------------------------------------------------------------------------- // Grammar verification @@ -121,7 +118,6 @@ func isLexical(name string) bool { return !unicode.IsUpper(ch) } - type verifier struct { fset *token.FileSet scanner.ErrorVector @@ -130,12 +126,10 @@ type verifier struct { grammar Grammar } - func (v *verifier) error(pos token.Pos, msg string) { v.Error(v.fset.Position(pos), msg) } - func (v *verifier) push(prod *Production) { name := prod.Name.String if _, found := v.reached[name]; !found { @@ -144,7 +138,6 @@ func (v *verifier) push(prod *Production) { } } - func (v *verifier) verifyChar(x *Token) int { s := x.String if utf8.RuneCountInString(s) != 1 { @@ -155,7 +148,6 @@ func (v *verifier) verifyChar(x *Token) int { return ch } - func (v *verifier) verifyExpr(expr Expression, lexical bool) { switch x := expr.(type) { case nil: @@ -200,7 +192,6 @@ func (v *verifier) verifyExpr(expr Expression, lexical bool) { } } - func (v *verifier) verify(fset *token.FileSet, grammar Grammar, start string) { // find root production root, found := grammar[start] @@ -240,7 +231,6 @@ func (v *verifier) verify(fset *token.FileSet, grammar Grammar, start string) { } } - // Verify checks that: // - all productions used are defined // - all productions defined are used when beginning at start diff --git a/src/pkg/ebnf/ebnf_test.go b/src/pkg/ebnf/ebnf_test.go index 30301748d2..b086facc3e 100644 --- a/src/pkg/ebnf/ebnf_test.go +++ b/src/pkg/ebnf/ebnf_test.go @@ -10,10 +10,8 @@ import ( "testing" ) - var fset = token.NewFileSet() - var goodGrammars = []string{ `Program = .`, @@ -37,7 +35,6 @@ var goodGrammars = []string{ ti = "b" .`, } - var badGrammars = []string{ `Program = | .`, `Program = | b .`, @@ -49,7 +46,6 @@ var badGrammars = []string{ `Program = {} .`, } - func checkGood(t *testing.T, filename string, src []byte) { grammar, err := Parse(fset, filename, src) if err != nil { @@ -60,7 +56,6 @@ func checkGood(t *testing.T, filename string, src []byte) { } } - func checkBad(t *testing.T, filename string, src []byte) { _, err := Parse(fset, filename, src) if err == nil { @@ -68,7 +63,6 @@ func checkBad(t *testing.T, filename string, src []byte) { } } - func TestGrammars(t *testing.T) { for _, src := range goodGrammars { checkGood(t, "", []byte(src)) @@ -78,12 +72,10 @@ func TestGrammars(t *testing.T) { } } - var files = []string{ // TODO(gri) add some test files } - func TestFiles(t *testing.T) { for _, filename := range files { src, err := ioutil.ReadFile(filename) diff --git a/src/pkg/ebnf/parser.go b/src/pkg/ebnf/parser.go index ede4f7073a..ef2fac0000 100644 --- a/src/pkg/ebnf/parser.go +++ b/src/pkg/ebnf/parser.go @@ -11,7 +11,6 @@ import ( "strconv" ) - type parser struct { fset *token.FileSet scanner.ErrorVector @@ -21,7 +20,6 @@ type parser struct { lit string // token literal } - func (p *parser) next() { p.pos, p.tok, p.lit = p.scanner.Scan() if p.tok.IsKeyword() { @@ -31,12 +29,10 @@ func (p *parser) next() { } } - func (p *parser) error(pos token.Pos, msg string) { p.Error(p.fset.Position(pos), msg) } - func (p *parser) errorExpected(pos token.Pos, msg string) { msg = "expected " + msg if pos == p.pos { @@ -50,7 +46,6 @@ func (p *parser) errorExpected(pos token.Pos, msg string) { p.error(pos, msg) } - func (p *parser) expect(tok token.Token) token.Pos { pos := p.pos if p.tok != tok { @@ -60,7 +55,6 @@ func (p *parser) expect(tok token.Token) token.Pos { return pos } - func (p *parser) parseIdentifier() *Name { pos := p.pos name := p.lit @@ -68,7 +62,6 @@ func (p *parser) parseIdentifier() *Name { return &Name{pos, name} } - func (p *parser) parseToken() *Token { pos := p.pos value := "" @@ -84,7 +77,6 @@ func (p *parser) parseToken() *Token { return &Token{pos, value} } - // ParseTerm returns nil if no term was found. func (p *parser) parseTerm() (x Expression) { pos := p.pos @@ -121,7 +113,6 @@ func (p *parser) parseTerm() (x Expression) { return x } - func (p *parser) parseSequence() Expression { var list Sequence @@ -141,7 +132,6 @@ func (p *parser) parseSequence() Expression { return list } - func (p *parser) parseExpression() Expression { var list Alternative @@ -162,7 +152,6 @@ func (p *parser) parseExpression() Expression { return list } - func (p *parser) parseProduction() *Production { name := p.parseIdentifier() p.expect(token.ASSIGN) @@ -174,7 +163,6 @@ func (p *parser) parseProduction() *Production { return &Production{name, expr} } - func (p *parser) parse(fset *token.FileSet, filename string, src []byte) Grammar { // initialize parser p.fset = fset @@ -196,7 +184,6 @@ func (p *parser) parse(fset *token.FileSet, filename string, src []byte) Grammar return grammar } - // Parse parses a set of EBNF productions from source src. // It returns a set of productions. Errors are reported // for incorrect syntax and if a production is declared diff --git a/src/pkg/encoding/base32/base32_test.go b/src/pkg/encoding/base32/base32_test.go index 792e4dc635..3fa1c2b266 100644 --- a/src/pkg/encoding/base32/base32_test.go +++ b/src/pkg/encoding/base32/base32_test.go @@ -25,7 +25,6 @@ var pairs = []testpair{ {"fooba", "MZXW6YTB"}, {"foobar", "MZXW6YTBOI======"}, - // Wikipedia examples, converted to base32 {"sure.", "ON2XEZJO"}, {"sure", "ON2XEZI="}, diff --git a/src/pkg/encoding/hex/hex.go b/src/pkg/encoding/hex/hex.go index 47cdedd607..e7ea8b0f2a 100644 --- a/src/pkg/encoding/hex/hex.go +++ b/src/pkg/encoding/hex/hex.go @@ -42,7 +42,6 @@ func (e InvalidHexCharError) String() string { return "invalid hex char: " + strconv.Itoa(int(e)) } - func DecodedLen(x int) int { return x / 2 } // Decode decodes src into DecodedLen(len(src)) bytes, returning the actual diff --git a/src/pkg/exec/exec_test.go b/src/pkg/exec/exec_test.go index f6cebb9055..242120faab 100644 --- a/src/pkg/exec/exec_test.go +++ b/src/pkg/exec/exec_test.go @@ -68,7 +68,6 @@ func TestCatGoodAndBadFile(t *testing.T) { } } - func TestNoExistBinary(t *testing.T) { // Can't run a non-existent binary err := Command("/no-exist-binary").Run() diff --git a/src/pkg/exp/datafmt/datafmt.go b/src/pkg/exp/datafmt/datafmt.go index b4f83a8edf..6d7e764427 100644 --- a/src/pkg/exp/datafmt/datafmt.go +++ b/src/pkg/exp/datafmt/datafmt.go @@ -211,7 +211,6 @@ import ( "runtime" ) - // ---------------------------------------------------------------------------- // Format representation @@ -228,13 +227,11 @@ import ( // type Formatter func(state *State, value interface{}, ruleName string) bool - // A FormatterMap is a set of custom formatters. // It maps a rule name to a formatter function. // type FormatterMap map[string]Formatter - // A parsed format expression is built from the following nodes. // type ( @@ -269,13 +266,11 @@ type ( } ) - // A Format is the result of parsing a format specification. // The format may be applied repeatedly to format values. // type Format map[string]expr - // ---------------------------------------------------------------------------- // Formatting @@ -293,7 +288,6 @@ type Environment interface { Copy() Environment } - // State represents the current formatting state. // It is provided as argument to custom formatters. // @@ -309,7 +303,6 @@ type State struct { separator expr // possibly nil } - func newState(fmt Format, env Environment, errors chan os.Error) *State { s := new(State) s.fmt = fmt @@ -330,17 +323,14 @@ func newState(fmt Format, env Environment, errors chan os.Error) *State { return s } - // Env returns the environment passed to Format.Apply. func (s *State) Env() interface{} { return s.env } - // LinePos returns the position of the current line beginning // in the state's output buffer. Line numbers start at 1. // func (s *State) LinePos() token.Position { return s.linePos } - // Pos returns the position of the next byte to be written to the // output buffer. Line numbers start at 1. // @@ -349,7 +339,6 @@ func (s *State) Pos() token.Position { return token.Position{Line: s.linePos.Line, Column: offs - s.linePos.Offset, Offset: offs} } - // Write writes data to the output buffer, inserting the indentation // string after each newline or form feed character. It cannot return an error. // @@ -371,7 +360,6 @@ func (s *State) Write(data []byte) (int, os.Error) { return n + n3, nil } - type checkpoint struct { env Environment hasOutput bool @@ -379,7 +367,6 @@ type checkpoint struct { linePos token.Position } - func (s *State) save() checkpoint { saved := checkpoint{nil, s.hasOutput, s.output.Len(), s.linePos} if s.env != nil { @@ -388,19 +375,16 @@ func (s *State) save() checkpoint { return saved } - func (s *State) restore(m checkpoint) { s.env = m.env s.output.Truncate(m.outputLen) } - func (s *State) error(msg string) { s.errors <- os.NewError(msg) runtime.Goexit() } - // TODO At the moment, unnamed types are simply mapped to the default // names below. For instance, all unnamed arrays are mapped to // 'array' which is not really sufficient. Eventually one may want @@ -440,7 +424,6 @@ func (s *State) getFormat(name string) expr { return nil } - // eval applies a format expression fexpr to a value. If the expression // evaluates internally to a non-nil []byte, that slice is appended to // the state's output buffer and eval returns true. Otherwise, eval @@ -653,7 +636,6 @@ func (s *State) eval(fexpr expr, value reflect.Value, index int) bool { return false } - // Eval formats each argument according to the format // f and returns the resulting []byte and os.Error. If // an error occurred, the []byte contains the partially @@ -688,7 +670,6 @@ func (f Format) Eval(env Environment, args ...interface{}) ([]byte, os.Error) { return s.output.Bytes(), err } - // ---------------------------------------------------------------------------- // Convenience functions @@ -705,7 +686,6 @@ func (f Format) Fprint(w io.Writer, env Environment, args ...interface{}) (int, return w.Write(data) } - // Print formats each argument according to the format f // and writes to standard output. The result is the total // number of bytes written and an os.Error, if any. @@ -714,7 +694,6 @@ func (f Format) Print(args ...interface{}) (int, os.Error) { return f.Fprint(os.Stdout, nil, args...) } - // Sprint formats each argument according to the format f // and returns the resulting string. If an error occurs // during formatting, the result string contains the diff --git a/src/pkg/exp/datafmt/datafmt_test.go b/src/pkg/exp/datafmt/datafmt_test.go index d7c70b21de..87d0716593 100644 --- a/src/pkg/exp/datafmt/datafmt_test.go +++ b/src/pkg/exp/datafmt/datafmt_test.go @@ -10,10 +10,8 @@ import ( "go/token" ) - var fset = token.NewFileSet() - func parse(t *testing.T, form string, fmap FormatterMap) Format { f, err := Parse(fset, "", []byte(form), fmap) if err != nil { @@ -23,7 +21,6 @@ func parse(t *testing.T, form string, fmap FormatterMap) Format { return f } - func verify(t *testing.T, f Format, expected string, args ...interface{}) { if f == nil { return // allow other tests to run @@ -36,7 +33,6 @@ func verify(t *testing.T, f Format, expected string, args ...interface{}) { } } - func formatter(s *State, value interface{}, rule_name string) bool { switch rule_name { case "/": @@ -62,7 +58,6 @@ func formatter(s *State, value interface{}, rule_name string) bool { return false } - func TestCustomFormatters(t *testing.T) { fmap0 := FormatterMap{"/": formatter} fmap1 := FormatterMap{"int": formatter, "blank": formatter, "nil": formatter} @@ -92,7 +87,6 @@ func TestCustomFormatters(t *testing.T) { // TODO needs more tests } - // ---------------------------------------------------------------------------- // Formatting of basic and simple composite types @@ -109,7 +103,6 @@ func check(t *testing.T, form, expected string, args ...interface{}) { } } - func TestBasicTypes(t *testing.T) { check(t, ``, ``) check(t, `bool=":%v"`, `:true:false`, true, false) @@ -144,7 +137,6 @@ func TestBasicTypes(t *testing.T) { check(t, `float64="%g"`, fs, float64(f)) } - func TestArrayTypes(t *testing.T) { var a0 [10]int check(t, `array="array";`, `array`, a0) @@ -159,7 +151,6 @@ func TestArrayTypes(t *testing.T) { check(t, `array={* / ", "}; interface=*; string="bar"; default="%v";`, `42, bar, 3.14`, a2) } - func TestChanTypes(t *testing.T) { var c0 chan int check(t, `chan="chan"`, `chan`, c0) @@ -170,7 +161,6 @@ func TestChanTypes(t *testing.T) { // check(t, `chan=*`, `42`, c1); // reflection support for chans incomplete } - func TestFuncTypes(t *testing.T) { var f0 func() int check(t, `func="func"`, `func`, f0) @@ -180,7 +170,6 @@ func TestFuncTypes(t *testing.T) { // check(t, `func=*`, `42`, f1); // reflection support for funcs incomplete } - func TestMapTypes(t *testing.T) { var m0 map[string]int check(t, `map="map"`, `map`, m0) @@ -190,7 +179,6 @@ func TestMapTypes(t *testing.T) { // check(t, `map=*`, ``, m1); // reflection support for maps incomplete } - func TestPointerTypes(t *testing.T) { var p0 *int check(t, `ptr="ptr"`, `ptr`, p0) @@ -203,7 +191,6 @@ func TestPointerTypes(t *testing.T) { check(t, `ptr=*; int="%d"`, `99991`, p1) } - func TestDefaultRule(t *testing.T) { check(t, `default="%v"`, `42foo3.14`, 42, "foo", 3.14) check(t, `default="%v"; int="%x"`, `abcdef`, 10, 11, 12, 13, 14, 15) @@ -211,13 +198,11 @@ func TestDefaultRule(t *testing.T) { check(t, `default="%x"; int=@:default`, `abcdef`, 10, 11, 12, 13, 14, 15) } - func TestGlobalSeparatorRule(t *testing.T) { check(t, `int="%d"; / ="-"`, `1-2-3-4`, 1, 2, 3, 4) check(t, `int="%x%x"; / ="*"`, `aa*aa`, 10, 10) } - // ---------------------------------------------------------------------------- // Formatting of a struct @@ -231,7 +216,6 @@ const F1 = `datafmt "datafmt";` + func TestStruct1(t *testing.T) { check(t, F1, "<42>", T1{42}) } - // ---------------------------------------------------------------------------- // Formatting of a struct with an optional field (ptr) @@ -256,7 +240,6 @@ func TestStruct2(t *testing.T) { check(t, F2b, "fooempty", T2{"foo", nil}) } - // ---------------------------------------------------------------------------- // Formatting of a struct with a repetitive field (slice) @@ -285,7 +268,6 @@ func TestStruct3(t *testing.T) { check(t, F3b, "bal: 2-3-5", T3{"bal", []int{2, 3, 5}}) } - // ---------------------------------------------------------------------------- // Formatting of a struct with alternative field @@ -318,7 +300,6 @@ func TestStruct4(t *testing.T) { check(t, F4b, "<2, 3, 7>", T4{nil, []int{2, 3, 7}}) } - // ---------------------------------------------------------------------------- // Formatting a struct (documentation example) @@ -338,7 +319,6 @@ func TestStructPoint(t *testing.T) { check(t, FPoint, "---foo---{3, 0xf}", p) } - // ---------------------------------------------------------------------------- // Formatting a slice (documentation example) @@ -347,5 +327,4 @@ const FSlice = `int = "%b";` + func TestSlice(t *testing.T) { check(t, FSlice, "10, 11, 101, 111", []int{2, 3, 5, 7}) } - // TODO add more tests diff --git a/src/pkg/exp/datafmt/parser.go b/src/pkg/exp/datafmt/parser.go index 7dedb531a5..45d7d50a8f 100644 --- a/src/pkg/exp/datafmt/parser.go +++ b/src/pkg/exp/datafmt/parser.go @@ -28,7 +28,6 @@ type parser struct { rules map[string]expr // RuleName -> Expression } - func (p *parser) next() { p.pos, p.tok, p.lit = p.scanner.Scan() switch p.tok { @@ -39,7 +38,6 @@ func (p *parser) next() { } } - func (p *parser) init(fset *token.FileSet, filename string, src []byte) { p.ErrorVector.Reset() p.file = fset.AddFile(filename, fset.Base(), len(src)) @@ -49,12 +47,10 @@ func (p *parser) init(fset *token.FileSet, filename string, src []byte) { p.rules = make(map[string]expr) } - func (p *parser) error(pos token.Pos, msg string) { p.Error(p.file.Position(pos), msg) } - func (p *parser) errorExpected(pos token.Pos, msg string) { msg = "expected " + msg if pos == p.pos { @@ -68,7 +64,6 @@ func (p *parser) errorExpected(pos token.Pos, msg string) { p.error(pos, msg) } - func (p *parser) expect(tok token.Token) token.Pos { pos := p.pos if p.tok != tok { @@ -78,14 +73,12 @@ func (p *parser) expect(tok token.Token) token.Pos { return pos } - func (p *parser) parseIdentifier() string { name := p.lit p.expect(token.IDENT) return name } - func (p *parser) parseTypeName() (string, bool) { pos := p.pos name, isIdent := p.parseIdentifier(), true @@ -102,7 +95,6 @@ func (p *parser) parseTypeName() (string, bool) { return name, isIdent } - // Parses a rule name and returns it. If the rule name is // a package-qualified type name, the package name is resolved. // The 2nd result value is true iff the rule name consists of a @@ -126,7 +118,6 @@ func (p *parser) parseRuleName() (string, bool) { return name, isIdent } - func (p *parser) parseString() string { s := "" if p.tok == token.STRING { @@ -142,7 +133,6 @@ func (p *parser) parseString() string { return s } - func (p *parser) parseLiteral() literal { s := []byte(p.parseString()) @@ -176,7 +166,6 @@ func (p *parser) parseLiteral() literal { return lit } - func (p *parser) parseField() expr { var fname string switch p.tok { @@ -204,7 +193,6 @@ func (p *parser) parseField() expr { return &field{fname, ruleName} } - func (p *parser) parseOperand() (x expr) { switch p.tok { case token.STRING: @@ -242,7 +230,6 @@ func (p *parser) parseOperand() (x expr) { return x } - func (p *parser) parseSequence() expr { var list vector.Vector @@ -266,7 +253,6 @@ func (p *parser) parseSequence() expr { return seq } - func (p *parser) parseExpression() expr { var list vector.Vector @@ -297,7 +283,6 @@ func (p *parser) parseExpression() expr { return alt } - func (p *parser) parseFormat() { for p.tok != token.EOF { pos := p.pos @@ -343,7 +328,6 @@ func (p *parser) parseFormat() { p.expect(token.EOF) } - func remap(p *parser, name string) string { i := strings.Index(name, ".") if i >= 0 { @@ -359,7 +343,6 @@ func remap(p *parser, name string) string { return name } - // Parse parses a set of format productions from source src. Custom // formatters may be provided via a map of formatter functions. If // there are no errors, the result is a Format and the error is nil. diff --git a/src/pkg/exp/regexp/syntax/parse.go b/src/pkg/exp/regexp/syntax/parse.go index b6c91f7e1d..4eed182687 100644 --- a/src/pkg/exp/regexp/syntax/parse.go +++ b/src/pkg/exp/regexp/syntax/parse.go @@ -1760,7 +1760,6 @@ func (ra ranges) Swap(i, j int) { p[i], p[i+1], p[j], p[j+1] = p[j], p[j+1], p[i], p[i+1] } - func checkUTF8(s string) os.Error { for s != "" { rune, size := utf8.DecodeRuneInString(s) diff --git a/src/pkg/exp/regexp/syntax/prog.go b/src/pkg/exp/regexp/syntax/prog.go index 4af4a32e16..9b0e3e7aae 100644 --- a/src/pkg/exp/regexp/syntax/prog.go +++ b/src/pkg/exp/regexp/syntax/prog.go @@ -124,7 +124,6 @@ func (i *Inst) MatchEmptyWidth(before int, after int) bool { panic("unknown empty width arg") } - func (i *Inst) String() string { var b bytes.Buffer dumpInst(&b, i) diff --git a/src/pkg/exp/template/funcs.go b/src/pkg/exp/template/funcs.go index fd66a1f415..58b2bafd84 100644 --- a/src/pkg/exp/template/funcs.go +++ b/src/pkg/exp/template/funcs.go @@ -237,7 +237,6 @@ var ( jsGt = []byte(`\x3E`) ) - // JSEscape writes to w the escaped JavaScript equivalent of the plain text data b. func JSEscape(w io.Writer, b []byte) { last := 0 diff --git a/src/pkg/exp/template/parse.go b/src/pkg/exp/template/parse.go index d8ec30fa9e..ed7a587bdf 100644 --- a/src/pkg/exp/template/parse.go +++ b/src/pkg/exp/template/parse.go @@ -512,7 +512,6 @@ func (w *withNode) String() string { return fmt.Sprintf("({{with %s}} %s)", w.pipe, w.list) } - // Parsing. // New allocates a new template with the given name. diff --git a/src/pkg/exp/template/set_test.go b/src/pkg/exp/template/set_test.go index 056ba43831..2f347c37dc 100644 --- a/src/pkg/exp/template/set_test.go +++ b/src/pkg/exp/template/set_test.go @@ -72,7 +72,6 @@ func TestSetParse(t *testing.T) { } } - var setExecTests = []execTest{ {"empty", "", "", nil, true}, {"text", "some text", "some text", nil, true}, diff --git a/src/pkg/expvar/expvar.go b/src/pkg/expvar/expvar.go index 7123d4b0f7..7b733faf67 100644 --- a/src/pkg/expvar/expvar.go +++ b/src/pkg/expvar/expvar.go @@ -189,7 +189,6 @@ func (f Func) String() string { return string(v) } - // All published variables. var vars map[string]Var = make(map[string]Var) var mutex sync.Mutex diff --git a/src/pkg/fmt/fmt_test.go b/src/pkg/fmt/fmt_test.go index 9a80245284..2ede11cfc8 100644 --- a/src/pkg/fmt/fmt_test.go +++ b/src/pkg/fmt/fmt_test.go @@ -43,7 +43,6 @@ func TestFmtInterface(t *testing.T) { } } - const b32 uint32 = 1<<32 - 1 const b64 uint64 = 1<<64 - 1 @@ -634,7 +633,6 @@ func TestBlankln(t *testing.T) { } } - // Check Formatter with Sprint, Sprintln, Sprintf func TestFormatterPrintln(t *testing.T) { f := F(1) diff --git a/src/pkg/fmt/print.go b/src/pkg/fmt/print.go index 5c083e5e9e..ba91bcd9f6 100644 --- a/src/pkg/fmt/print.go +++ b/src/pkg/fmt/print.go @@ -253,7 +253,6 @@ func Sprintln(a ...interface{}) string { return s } - // Get the i'th arg of the struct value. // If the arg itself is an interface, return a value for // the thing inside the interface, not the interface itself. diff --git a/src/pkg/fmt/scan.go b/src/pkg/fmt/scan.go index d93a8c1da5..a8d423d458 100644 --- a/src/pkg/fmt/scan.go +++ b/src/pkg/fmt/scan.go @@ -271,14 +271,12 @@ func notSpace(r int) bool { return !unicode.IsSpace(r) } - // skipSpace provides Scan() methods the ability to skip space and newline characters // in keeping with the current scanning mode set by format strings and Scan()/Scanln(). func (s *ss) SkipSpace() { s.skipSpace(false) } - // readRune is a structure to enable reading UTF-8 encoded code points // from an io.Reader. It is used if the Reader given to the scanner does // not already implement io.RuneReader. @@ -337,7 +335,6 @@ func (r *readRune) ReadRune() (rune int, size int, err os.Error) { return } - var ssFree = newCache(func() interface{} { return new(ss) }) // Allocate a new ss struct or grab a cached one. @@ -411,7 +408,6 @@ func (s *ss) skipSpace(stopAtNewline bool) { } } - // token returns the next space-delimited string from the input. It // skips white space. For Scanln, it stops at newlines. For Scan, // newlines are treated as spaces. diff --git a/src/pkg/go/ast/ast.go b/src/pkg/go/ast/ast.go index b1c7d4ab1c..22bd5ee226 100644 --- a/src/pkg/go/ast/ast.go +++ b/src/pkg/go/ast/ast.go @@ -13,7 +13,6 @@ import ( "utf8" ) - // ---------------------------------------------------------------------------- // Interfaces // @@ -31,35 +30,30 @@ import ( // That position information is needed to properly position comments // when printing the construct. - // All node types implement the Node interface. type Node interface { Pos() token.Pos // position of first character belonging to the node End() token.Pos // position of first character immediately after the node } - // All expression nodes implement the Expr interface. type Expr interface { Node exprNode() } - // All statement nodes implement the Stmt interface. type Stmt interface { Node stmtNode() } - // All declaration nodes implement the Decl interface. type Decl interface { Node declNode() } - // ---------------------------------------------------------------------------- // Comments @@ -69,11 +63,9 @@ type Comment struct { Text string // comment text (excluding '\n' for //-style comments) } - func (c *Comment) Pos() token.Pos { return c.Slash } func (c *Comment) End() token.Pos { return token.Pos(int(c.Slash) + len(c.Text)) } - // A CommentGroup represents a sequence of comments // with no other tokens and no empty lines between. // @@ -81,11 +73,9 @@ type CommentGroup struct { List []*Comment // len(List) > 0 } - func (g *CommentGroup) Pos() token.Pos { return g.List[0].Pos() } func (g *CommentGroup) End() token.Pos { return g.List[len(g.List)-1].End() } - // ---------------------------------------------------------------------------- // Expressions and types @@ -101,7 +91,6 @@ type Field struct { Comment *CommentGroup // line comments; or nil } - func (f *Field) Pos() token.Pos { if len(f.Names) > 0 { return f.Names[0].Pos() @@ -109,7 +98,6 @@ func (f *Field) Pos() token.Pos { return f.Type.Pos() } - func (f *Field) End() token.Pos { if f.Tag != nil { return f.Tag.End() @@ -117,7 +105,6 @@ func (f *Field) End() token.Pos { return f.Type.End() } - // A FieldList represents a list of Fields, enclosed by parentheses or braces. type FieldList struct { Opening token.Pos // position of opening parenthesis/brace, if any @@ -125,7 +112,6 @@ type FieldList struct { Closing token.Pos // position of closing parenthesis/brace, if any } - func (f *FieldList) Pos() token.Pos { if f.Opening.IsValid() { return f.Opening @@ -138,7 +124,6 @@ func (f *FieldList) Pos() token.Pos { return token.NoPos } - func (f *FieldList) End() token.Pos { if f.Closing.IsValid() { return f.Closing + 1 @@ -151,7 +136,6 @@ func (f *FieldList) End() token.Pos { return token.NoPos } - // NumFields returns the number of (named and anonymous fields) in a FieldList. func (f *FieldList) NumFields() int { n := 0 @@ -167,7 +151,6 @@ func (f *FieldList) NumFields() int { return n } - // An expression is represented by a tree consisting of one // or more of the following concrete expression nodes. // @@ -298,7 +281,6 @@ type ( } ) - // The direction of a channel type is indicated by one // of the following constants. // @@ -309,7 +291,6 @@ const ( RECV ) - // A type is represented by a tree consisting of one // or more of the following type-specific expression // nodes. @@ -360,7 +341,6 @@ type ( } ) - // Pos and End implementations for expression/type nodes. // func (x *BadExpr) Pos() token.Pos { return x.From } @@ -391,7 +371,6 @@ func (x *InterfaceType) Pos() token.Pos { return x.Interface } func (x *MapType) Pos() token.Pos { return x.Map } func (x *ChanType) Pos() token.Pos { return x.Begin } - func (x *BadExpr) End() token.Pos { return x.To } func (x *Ident) End() token.Pos { return token.Pos(int(x.NamePos) + len(x.Name)) } func (x *Ellipsis) End() token.Pos { @@ -430,7 +409,6 @@ func (x *InterfaceType) End() token.Pos { return x.Methods.End() } func (x *MapType) End() token.Pos { return x.Value.End() } func (x *ChanType) End() token.Pos { return x.Value.End() } - // exprNode() ensures that only expression/type nodes can be // assigned to an ExprNode. // @@ -458,7 +436,6 @@ func (x *InterfaceType) exprNode() {} func (x *MapType) exprNode() {} func (x *ChanType) exprNode() {} - // ---------------------------------------------------------------------------- // Convenience functions for Idents @@ -469,7 +446,6 @@ var noPos token.Pos // func NewIdent(name string) *Ident { return &Ident{noPos, name, nil} } - // IsExported returns whether name is an exported Go symbol // (i.e., whether it begins with an uppercase letter). // @@ -478,13 +454,11 @@ func IsExported(name string) bool { return unicode.IsUpper(ch) } - // IsExported returns whether id is an exported Go symbol // (i.e., whether it begins with an uppercase letter). // func (id *Ident) IsExported() bool { return IsExported(id.Name) } - func (id *Ident) String() string { if id != nil { return id.Name @@ -492,7 +466,6 @@ func (id *Ident) String() string { return "" } - // ---------------------------------------------------------------------------- // Statements @@ -660,7 +633,6 @@ type ( } ) - // Pos and End implementations for statement nodes. // func (s *BadStmt) Pos() token.Pos { return s.From } @@ -685,7 +657,6 @@ func (s *SelectStmt) Pos() token.Pos { return s.Select } func (s *ForStmt) Pos() token.Pos { return s.For } func (s *RangeStmt) Pos() token.Pos { return s.For } - func (s *BadStmt) End() token.Pos { return s.To } func (s *DeclStmt) End() token.Pos { return s.Decl.End() } func (s *EmptyStmt) End() token.Pos { @@ -737,7 +708,6 @@ func (s *SelectStmt) End() token.Pos { return s.Body.End() } func (s *ForStmt) End() token.Pos { return s.Body.End() } func (s *RangeStmt) End() token.Pos { return s.Body.End() } - // stmtNode() ensures that only statement nodes can be // assigned to a StmtNode. // @@ -763,7 +733,6 @@ func (s *SelectStmt) stmtNode() {} func (s *ForStmt) stmtNode() {} func (s *RangeStmt) stmtNode() {} - // ---------------------------------------------------------------------------- // Declarations @@ -805,7 +774,6 @@ type ( } ) - // Pos and End implementations for spec nodes. // func (s *ImportSpec) Pos() token.Pos { @@ -817,7 +785,6 @@ func (s *ImportSpec) Pos() token.Pos { func (s *ValueSpec) Pos() token.Pos { return s.Names[0].Pos() } func (s *TypeSpec) Pos() token.Pos { return s.Name.Pos() } - func (s *ImportSpec) End() token.Pos { return s.Path.End() } func (s *ValueSpec) End() token.Pos { if n := len(s.Values); n > 0 { @@ -830,7 +797,6 @@ func (s *ValueSpec) End() token.Pos { } func (s *TypeSpec) End() token.Pos { return s.Type.End() } - // specNode() ensures that only spec nodes can be // assigned to a Spec. // @@ -838,7 +804,6 @@ func (s *ImportSpec) specNode() {} func (s *ValueSpec) specNode() {} func (s *TypeSpec) specNode() {} - // A declaration is represented by one of the following declaration nodes. // type ( @@ -880,14 +845,12 @@ type ( } ) - // Pos and End implementations for declaration nodes. // func (d *BadDecl) Pos() token.Pos { return d.From } func (d *GenDecl) Pos() token.Pos { return d.TokPos } func (d *FuncDecl) Pos() token.Pos { return d.Type.Pos() } - func (d *BadDecl) End() token.Pos { return d.To } func (d *GenDecl) End() token.Pos { if d.Rparen.IsValid() { @@ -902,7 +865,6 @@ func (d *FuncDecl) End() token.Pos { return d.Type.End() } - // declNode() ensures that only declaration nodes can be // assigned to a DeclNode. // @@ -910,7 +872,6 @@ func (d *BadDecl) declNode() {} func (d *GenDecl) declNode() {} func (d *FuncDecl) declNode() {} - // ---------------------------------------------------------------------------- // Files and packages @@ -931,7 +892,6 @@ type File struct { Comments []*CommentGroup // list of all comments in the source file } - func (f *File) Pos() token.Pos { return f.Package } func (f *File) End() token.Pos { if n := len(f.Decls); n > 0 { @@ -940,7 +900,6 @@ func (f *File) End() token.Pos { return f.Name.End() } - // A Package node represents a set of source files // collectively building a Go package. // @@ -951,6 +910,5 @@ type Package struct { Files map[string]*File // Go source files by filename } - func (p *Package) Pos() token.Pos { return token.NoPos } func (p *Package) End() token.Pos { return token.NoPos } diff --git a/src/pkg/go/ast/filter.go b/src/pkg/go/ast/filter.go index 0907fd53da..26733430d6 100644 --- a/src/pkg/go/ast/filter.go +++ b/src/pkg/go/ast/filter.go @@ -20,7 +20,6 @@ func identListExports(list []*Ident) []*Ident { return list[0:j] } - // fieldName assumes that x is the type of an anonymous field and // returns the corresponding field name. If x is not an acceptable // anonymous field, the result is nil. @@ -39,7 +38,6 @@ func fieldName(x Expr) *Ident { return nil } - func fieldListExports(fields *FieldList) (removedFields bool) { if fields == nil { return @@ -78,7 +76,6 @@ func fieldListExports(fields *FieldList) (removedFields bool) { return } - func paramListExports(fields *FieldList) { if fields == nil { return @@ -88,7 +85,6 @@ func paramListExports(fields *FieldList) { } } - func typeExports(typ Expr) { switch t := typ.(type) { case *ArrayType: @@ -112,7 +108,6 @@ func typeExports(typ Expr) { } } - func specExports(spec Spec) bool { switch s := spec.(type) { case *ValueSpec: @@ -130,7 +125,6 @@ func specExports(spec Spec) bool { return false } - func specListExports(list []Spec) []Spec { j := 0 for _, s := range list { @@ -142,7 +136,6 @@ func specListExports(list []Spec) []Spec { return list[0:j] } - func declExports(decl Decl) bool { switch d := decl.(type) { case *GenDecl: @@ -155,7 +148,6 @@ func declExports(decl Decl) bool { return false } - // FileExports trims the AST for a Go source file in place such that only // exported nodes remain: all top-level identifiers which are not exported // and their associated information (such as type, initial value, or function @@ -178,7 +170,6 @@ func FileExports(src *File) bool { return j > 0 } - // PackageExports trims the AST for a Go package in place such that only // exported nodes remain. The pkg.Files list is not changed, so that file // names and top-level package comments don't get lost. @@ -196,7 +187,6 @@ func PackageExports(pkg *Package) bool { return hasExports } - // ---------------------------------------------------------------------------- // General filtering @@ -213,7 +203,6 @@ func filterIdentList(list []*Ident, f Filter) []*Ident { return list[0:j] } - func filterFieldList(fields *FieldList, filter Filter) (removedFields bool) { if fields == nil { return false @@ -246,7 +235,6 @@ func filterFieldList(fields *FieldList, filter Filter) (removedFields bool) { return } - func filterSpec(spec Spec, f Filter) bool { switch s := spec.(type) { case *ValueSpec: @@ -272,7 +260,6 @@ func filterSpec(spec Spec, f Filter) bool { return false } - func filterSpecList(list []Spec, f Filter) []Spec { j := 0 for _, s := range list { @@ -284,7 +271,6 @@ func filterSpecList(list []Spec, f Filter) []Spec { return list[0:j] } - // FilterDecl trims the AST for a Go declaration in place by removing // all names (including struct field and interface method names, but // not from parameter lists) that don't pass through the filter f. @@ -303,7 +289,6 @@ func FilterDecl(decl Decl, f Filter) bool { return false } - // FilterFile trims the AST for a Go file in place by removing all // names from top-level declarations (including struct field and // interface method names, but not from parameter lists) that don't @@ -326,7 +311,6 @@ func FilterFile(src *File, f Filter) bool { return j > 0 } - // FilterPackage trims the AST for a Go package in place by removing all // names from top-level declarations (including struct field and // interface method names, but not from parameter lists) that don't @@ -348,7 +332,6 @@ func FilterPackage(pkg *Package, f Filter) bool { return hasDecls } - // ---------------------------------------------------------------------------- // Merging of package files @@ -368,7 +351,6 @@ const ( // var separator = &Comment{noPos, "//"} - // MergePackageFiles creates a file AST by merging the ASTs of the // files belonging to a package. The mode flags control merging behavior. // diff --git a/src/pkg/go/ast/print.go b/src/pkg/go/ast/print.go index 81e1da1d0a..62a30481d5 100644 --- a/src/pkg/go/ast/print.go +++ b/src/pkg/go/ast/print.go @@ -14,11 +14,9 @@ import ( "reflect" ) - // A FieldFilter may be provided to Fprint to control the output. type FieldFilter func(name string, value reflect.Value) bool - // NotNilFilter returns true for field values that are not nil; // it returns false otherwise. func NotNilFilter(_ string, v reflect.Value) bool { @@ -29,7 +27,6 @@ func NotNilFilter(_ string, v reflect.Value) bool { return true } - // Fprint prints the (sub-)tree starting at AST node x to w. // If fset != nil, position information is interpreted relative // to that file set. Otherwise positions are printed as integer @@ -68,14 +65,12 @@ func Fprint(w io.Writer, fset *token.FileSet, x interface{}, f FieldFilter) (n i return } - // Print prints x to standard output, skipping nil fields. // Print(fset, x) is the same as Fprint(os.Stdout, fset, x, NotNilFilter). func Print(fset *token.FileSet, x interface{}) (int, os.Error) { return Fprint(os.Stdout, fset, x, NotNilFilter) } - type printer struct { output io.Writer fset *token.FileSet @@ -87,7 +82,6 @@ type printer struct { line int // current line number } - var indent = []byte(". ") func (p *printer) Write(data []byte) (n int, err os.Error) { @@ -120,14 +114,12 @@ func (p *printer) Write(data []byte) (n int, err os.Error) { return } - // localError wraps locally caught os.Errors so we can distinguish // them from genuine panics which we don't want to return as errors. type localError struct { err os.Error } - // printf is a convenience wrapper that takes care of print errors. func (p *printer) printf(format string, args ...interface{}) { n, err := fmt.Fprintf(p, format, args...) @@ -137,7 +129,6 @@ func (p *printer) printf(format string, args ...interface{}) { } } - // Implementation note: Print is written for AST nodes but could be // used to print arbitrary data structures; such a version should // probably be in a different package. diff --git a/src/pkg/go/ast/print_test.go b/src/pkg/go/ast/print_test.go index 30b396fcf6..f4e8f7a78f 100644 --- a/src/pkg/go/ast/print_test.go +++ b/src/pkg/go/ast/print_test.go @@ -10,7 +10,6 @@ import ( "testing" ) - var tests = []struct { x interface{} // x is printed as s s string @@ -49,7 +48,6 @@ var tests = []struct { 3 }`}, } - // Split s into lines, trim whitespace from all lines, and return // the concatenated non-empty lines. func trim(s string) string { @@ -65,7 +63,6 @@ func trim(s string) string { return strings.Join(lines[0:i], "\n") } - func TestPrint(t *testing.T) { var buf bytes.Buffer for _, test := range tests { diff --git a/src/pkg/go/ast/resolve.go b/src/pkg/go/ast/resolve.go index ecd2e8a7c3..3927a799e0 100644 --- a/src/pkg/go/ast/resolve.go +++ b/src/pkg/go/ast/resolve.go @@ -14,23 +14,19 @@ import ( "strconv" ) - type pkgBuilder struct { scanner.ErrorVector fset *token.FileSet } - func (p *pkgBuilder) error(pos token.Pos, msg string) { p.Error(p.fset.Position(pos), msg) } - func (p *pkgBuilder) errorf(pos token.Pos, format string, args ...interface{}) { p.error(pos, fmt.Sprintf(format, args...)) } - func (p *pkgBuilder) declare(scope, altScope *Scope, obj *Object) { alt := scope.Insert(obj) if alt == nil && altScope != nil { @@ -46,7 +42,6 @@ func (p *pkgBuilder) declare(scope, altScope *Scope, obj *Object) { } } - func resolve(scope *Scope, ident *Ident) bool { for ; scope != nil; scope = scope.Outer { if obj := scope.Lookup(ident.Name); obj != nil { @@ -57,7 +52,6 @@ func resolve(scope *Scope, ident *Ident) bool { return false } - // An Importer resolves import paths to package Objects. // The imports map records the packages already imported, // indexed by package id (canonical import path). @@ -69,7 +63,6 @@ func resolve(scope *Scope, ident *Ident) bool { // return pkg. type Importer func(imports map[string]*Object, path string) (pkg *Object, err os.Error) - // NewPackage creates a new Package node from a set of File nodes. It resolves // unresolved identifiers across files and updates each file's Unresolved list // accordingly. If a non-nil importer and universe scope are provided, they are diff --git a/src/pkg/go/ast/scope.go b/src/pkg/go/ast/scope.go index b966f786fb..92e3669808 100644 --- a/src/pkg/go/ast/scope.go +++ b/src/pkg/go/ast/scope.go @@ -12,7 +12,6 @@ import ( "go/token" ) - // A Scope maintains the set of named language entities declared // in the scope and a link to the immediately surrounding (outer) // scope. @@ -22,14 +21,12 @@ type Scope struct { Objects map[string]*Object } - // NewScope creates a new scope nested in the outer scope. func NewScope(outer *Scope) *Scope { const n = 4 // initial scope capacity return &Scope{outer, make(map[string]*Object, n)} } - // Lookup returns the object with the given name if it is // found in scope s, otherwise it returns nil. Outer scopes // are ignored. @@ -38,7 +35,6 @@ func (s *Scope) Lookup(name string) *Object { return s.Objects[name] } - // Insert attempts to insert a named object obj into the scope s. // If the scope already contains an object alt with the same name, // Insert leaves the scope unchanged and returns alt. Otherwise @@ -51,7 +47,6 @@ func (s *Scope) Insert(obj *Object) (alt *Object) { return } - // Debugging support func (s *Scope) String() string { var buf bytes.Buffer @@ -66,7 +61,6 @@ func (s *Scope) String() string { return buf.String() } - // ---------------------------------------------------------------------------- // Objects @@ -91,13 +85,11 @@ type Object struct { Type interface{} // place holder for type information; may be nil } - // NewObj creates a new object of a given kind and name. func NewObj(kind ObjKind, name string) *Object { return &Object{Kind: kind, Name: name} } - // Pos computes the source position of the declaration of an object name. // The result may be an invalid position if it cannot be computed // (obj.Decl may be nil or not correct). @@ -137,7 +129,6 @@ func (obj *Object) Pos() token.Pos { return token.NoPos } - // ObKind describes what an object represents. type ObjKind int @@ -152,7 +143,6 @@ const ( Lbl // label ) - var objKindStrings = [...]string{ Bad: "bad", Pkg: "package", @@ -163,5 +153,4 @@ var objKindStrings = [...]string{ Lbl: "label", } - func (kind ObjKind) String() string { return objKindStrings[kind] } diff --git a/src/pkg/go/ast/walk.go b/src/pkg/go/ast/walk.go index 95c4b3a356..181cfd1491 100644 --- a/src/pkg/go/ast/walk.go +++ b/src/pkg/go/ast/walk.go @@ -13,7 +13,6 @@ type Visitor interface { Visit(node Node) (w Visitor) } - // Helper functions for common node lists. They may be empty. func walkIdentList(v Visitor, list []*Ident) { @@ -22,28 +21,24 @@ func walkIdentList(v Visitor, list []*Ident) { } } - func walkExprList(v Visitor, list []Expr) { for _, x := range list { Walk(v, x) } } - func walkStmtList(v Visitor, list []Stmt) { for _, x := range list { Walk(v, x) } } - func walkDeclList(v Visitor, list []Decl) { for _, x := range list { Walk(v, x) } } - // TODO(gri): Investigate if providing a closure to Walk leads to // simpler use (and may help eliminate Inspect in turn). @@ -369,7 +364,6 @@ func Walk(v Visitor, node Node) { v.Visit(nil) } - type inspector func(Node) bool func (f inspector) Visit(node Node) Visitor { @@ -379,7 +373,6 @@ func (f inspector) Visit(node Node) Visitor { return nil } - // Inspect traverses an AST in depth-first order: It starts by calling // f(node); node must not be nil. If f returns true, Inspect invokes f // for all the non-nil children of node, recursively. diff --git a/src/pkg/go/doc/comment.go b/src/pkg/go/doc/comment.go index 85640af796..2a24b14556 100644 --- a/src/pkg/go/doc/comment.go +++ b/src/pkg/go/doc/comment.go @@ -14,10 +14,8 @@ import ( "template" // for htmlEscape ) - func isWhitespace(ch byte) bool { return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' } - func stripTrailingWhitespace(s string) string { i := len(s) for i > 0 && isWhitespace(s[i-1]) { @@ -26,7 +24,6 @@ func stripTrailingWhitespace(s string) string { return s[0:i] } - // CommentText returns the text of comment, // with the comment markers - //, /*, and */ - removed. func CommentText(comment *ast.CommentGroup) string { @@ -85,7 +82,6 @@ func CommentText(comment *ast.CommentGroup) string { return strings.Join(lines, "\n") } - // Split bytes into lines. func split(text []byte) [][]byte { // count lines @@ -119,7 +115,6 @@ func split(text []byte) [][]byte { return out } - var ( ldquo = []byte("“") rdquo = []byte("”") @@ -148,7 +143,6 @@ func commentEscape(w io.Writer, s []byte, nice bool) { template.HTMLEscape(w, s[last:]) } - const ( // Regexp for Go identifiers identRx = `[a-zA-Z_][a-zA-Z_0-9]*` // TODO(gri) ASCII only for now - fix this @@ -176,7 +170,6 @@ var ( html_endpre = []byte("\n") ) - // Emphasize and escape a line of text for HTML. URLs are converted into links; // if the URL also appears in the words map, the link is taken from the map (if // the corresponding map value is the empty string, the URL is not converted @@ -235,7 +228,6 @@ func emphasize(w io.Writer, line []byte, words map[string]string, nice bool) { commentEscape(w, line, nice) } - func indentLen(s []byte) int { i := 0 for i < len(s) && (s[i] == ' ' || s[i] == '\t') { @@ -244,10 +236,8 @@ func indentLen(s []byte) int { return i } - func isBlank(s []byte) bool { return len(s) == 0 || (len(s) == 1 && s[0] == '\n') } - func commonPrefix(a, b []byte) []byte { i := 0 for i < len(a) && i < len(b) && a[i] == b[i] { @@ -256,7 +246,6 @@ func commonPrefix(a, b []byte) []byte { return a[0:i] } - func unindent(block [][]byte) { if len(block) == 0 { return @@ -279,7 +268,6 @@ func unindent(block [][]byte) { } } - // Convert comment text to formatted HTML. // The comment was prepared by DocReader, // so it is known not to have leading, trailing blank lines diff --git a/src/pkg/go/doc/doc.go b/src/pkg/go/doc/doc.go index b26cd2bed5..c7fed97841 100644 --- a/src/pkg/go/doc/doc.go +++ b/src/pkg/go/doc/doc.go @@ -12,7 +12,6 @@ import ( "sort" ) - // ---------------------------------------------------------------------------- type typeDoc struct { @@ -25,7 +24,6 @@ type typeDoc struct { methods map[string]*ast.FuncDecl } - // docReader accumulates documentation for a single package. // It modifies the AST: Comments (declaration documentation) // that have been collected by the DocReader are set to nil @@ -42,14 +40,12 @@ type docReader struct { bugs []*ast.CommentGroup } - func (doc *docReader) init(pkgName string) { doc.pkgName = pkgName doc.types = make(map[string]*typeDoc) doc.funcs = make(map[string]*ast.FuncDecl) } - func (doc *docReader) addDoc(comments *ast.CommentGroup) { if doc.doc == nil { // common case: just one package comment @@ -71,7 +67,6 @@ func (doc *docReader) addDoc(comments *ast.CommentGroup) { doc.doc = &ast.CommentGroup{list} } - func (doc *docReader) addType(decl *ast.GenDecl) { spec := decl.Specs[0].(*ast.TypeSpec) typ := doc.lookupTypeDoc(spec.Name.Name) @@ -84,7 +79,6 @@ func (doc *docReader) addType(decl *ast.GenDecl) { } } - func (doc *docReader) lookupTypeDoc(name string) *typeDoc { if name == "" { return nil // no type docs for anonymous types @@ -98,7 +92,6 @@ func (doc *docReader) lookupTypeDoc(name string) *typeDoc { return tdoc } - func baseTypeName(typ ast.Expr) string { switch t := typ.(type) { case *ast.Ident: @@ -113,7 +106,6 @@ func baseTypeName(typ ast.Expr) string { return "" } - func (doc *docReader) addValue(decl *ast.GenDecl) { // determine if decl should be associated with a type // Heuristic: For each typed entry, determine the type name, if any. @@ -165,7 +157,6 @@ func (doc *docReader) addValue(decl *ast.GenDecl) { *values = append(*values, decl) } - // Helper function to set the table entry for function f. Makes sure that // at least one f with associated documentation is stored in table, if there // are multiple f's with the same name. @@ -183,7 +174,6 @@ func setFunc(table map[string]*ast.FuncDecl, f *ast.FuncDecl) { table[name] = f } - func (doc *docReader) addFunc(fun *ast.FuncDecl) { name := fun.Name.Name @@ -238,7 +228,6 @@ func (doc *docReader) addFunc(fun *ast.FuncDecl) { setFunc(doc.funcs, fun) } - func (doc *docReader) addDecl(decl ast.Decl) { switch d := decl.(type) { case *ast.GenDecl: @@ -271,7 +260,6 @@ func (doc *docReader) addDecl(decl ast.Decl) { } } - func copyCommentList(list []*ast.Comment) []*ast.Comment { return append([]*ast.Comment(nil), list...) } @@ -281,7 +269,6 @@ var ( bug_content = regexp.MustCompile("[^ \n\r\t]+") // at least one non-whitespace char ) - // addFile adds the AST for a source file to the docReader. // Adding the same AST multiple times is a no-op. // @@ -313,7 +300,6 @@ func (doc *docReader) addFile(src *ast.File) { src.Comments = nil // consumed unassociated comments - remove from ast.File node } - func NewFileDoc(file *ast.File) *PackageDoc { var r docReader r.init(file.Name.Name) @@ -321,7 +307,6 @@ func NewFileDoc(file *ast.File) *PackageDoc { return r.newDoc("", nil) } - func NewPackageDoc(pkg *ast.Package, importpath string) *PackageDoc { var r docReader r.init(pkg.Name) @@ -335,7 +320,6 @@ func NewPackageDoc(pkg *ast.Package, importpath string) *PackageDoc { return r.newDoc(importpath, filenames) } - // ---------------------------------------------------------------------------- // Conversion to external representation @@ -353,7 +337,6 @@ type sortValueDoc []*ValueDoc func (p sortValueDoc) Len() int { return len(p) } func (p sortValueDoc) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - func declName(d *ast.GenDecl) string { if len(d.Specs) != 1 { return "" @@ -369,7 +352,6 @@ func declName(d *ast.GenDecl) string { return "" } - func (p sortValueDoc) Less(i, j int) bool { // sort by name // pull blocks (name = "") up to top @@ -380,7 +362,6 @@ func (p sortValueDoc) Less(i, j int) bool { return p[i].order < p[j].order } - func makeValueDocs(list []*ast.GenDecl, tok token.Token) []*ValueDoc { d := make([]*ValueDoc, len(list)) // big enough in any case n := 0 @@ -396,7 +377,6 @@ func makeValueDocs(list []*ast.GenDecl, tok token.Token) []*ValueDoc { return d } - // FuncDoc is the documentation for a func declaration, // either a top-level function or a method function. // @@ -413,7 +393,6 @@ func (p sortFuncDoc) Len() int { return len(p) } func (p sortFuncDoc) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p sortFuncDoc) Less(i, j int) bool { return p[i].Name < p[j].Name } - func makeFuncDocs(m map[string]*ast.FuncDecl) []*FuncDoc { d := make([]*FuncDoc, len(m)) i := 0 @@ -433,7 +412,6 @@ func makeFuncDocs(m map[string]*ast.FuncDecl) []*FuncDoc { return d } - // TypeDoc is the documentation for a declared type. // Consts and Vars are sorted lists of constants and variables of (mostly) that type. // Factories is a sorted list of factory functions that return that type. @@ -463,7 +441,6 @@ func (p sortTypeDoc) Less(i, j int) bool { return p[i].order < p[j].order } - // NOTE(rsc): This would appear not to be correct for type ( ) // blocks, but the doc extractor above has split them into // individual declarations. @@ -520,7 +497,6 @@ func (doc *docReader) makeTypeDocs(m map[string]*typeDoc) []*TypeDoc { return d } - func makeBugDocs(list []*ast.CommentGroup) []string { d := make([]string, len(list)) for i, g := range list { @@ -529,7 +505,6 @@ func makeBugDocs(list []*ast.CommentGroup) []string { return d } - // PackageDoc is the documentation for an entire package. // type PackageDoc struct { @@ -544,7 +519,6 @@ type PackageDoc struct { Bugs []string } - // newDoc returns the accumulated documentation for the package. // func (doc *docReader) newDoc(importpath string, filenames []string) *PackageDoc { @@ -565,13 +539,11 @@ func (doc *docReader) newDoc(importpath string, filenames []string) *PackageDoc return p } - // ---------------------------------------------------------------------------- // Filtering by name type Filter func(string) bool - func matchFields(fields *ast.FieldList, f Filter) bool { if fields != nil { for _, field := range fields.List { @@ -585,7 +557,6 @@ func matchFields(fields *ast.FieldList, f Filter) bool { return false } - func matchDecl(d *ast.GenDecl, f Filter) bool { for _, d := range d.Specs { switch v := d.(type) { @@ -614,7 +585,6 @@ func matchDecl(d *ast.GenDecl, f Filter) bool { return false } - func filterValueDocs(a []*ValueDoc, f Filter) []*ValueDoc { w := 0 for _, vd := range a { @@ -626,7 +596,6 @@ func filterValueDocs(a []*ValueDoc, f Filter) []*ValueDoc { return a[0:w] } - func filterFuncDocs(a []*FuncDoc, f Filter) []*FuncDoc { w := 0 for _, fd := range a { @@ -638,7 +607,6 @@ func filterFuncDocs(a []*FuncDoc, f Filter) []*FuncDoc { return a[0:w] } - func filterTypeDocs(a []*TypeDoc, f Filter) []*TypeDoc { w := 0 for _, td := range a { @@ -661,7 +629,6 @@ func filterTypeDocs(a []*TypeDoc, f Filter) []*TypeDoc { return a[0:w] } - // Filter eliminates documentation for names that don't pass through the filter f. // TODO: Recognize "Type.Method" as a name. // diff --git a/src/pkg/go/parser/interface.go b/src/pkg/go/parser/interface.go index 1764c38e4f..77459fc373 100644 --- a/src/pkg/go/parser/interface.go +++ b/src/pkg/go/parser/interface.go @@ -17,7 +17,6 @@ import ( "path/filepath" ) - // If src != nil, readSource converts src to a []byte if possible; // otherwise it returns an error. If src == nil, readSource returns // the result of reading the file specified by filename. @@ -49,13 +48,11 @@ func readSource(filename string, src interface{}) ([]byte, os.Error) { return ioutil.ReadFile(filename) } - func (p *parser) parseEOF() os.Error { p.expect(token.EOF) return p.GetError(scanner.Sorted) } - // ParseExpr parses a Go expression and returns the corresponding // AST node. The fset, filename, and src arguments have the same interpretation // as for ParseFile. If there is an error, the result expression @@ -76,7 +73,6 @@ func ParseExpr(fset *token.FileSet, filename string, src interface{}) (ast.Expr, return x, p.parseEOF() } - // ParseStmtList parses a list of Go statements and returns the list // of corresponding AST nodes. The fset, filename, and src arguments have the same // interpretation as for ParseFile. If there is an error, the node @@ -93,7 +89,6 @@ func ParseStmtList(fset *token.FileSet, filename string, src interface{}) ([]ast return p.parseStmtList(), p.parseEOF() } - // ParseDeclList parses a list of Go declarations and returns the list // of corresponding AST nodes. The fset, filename, and src arguments have the same // interpretation as for ParseFile. If there is an error, the node @@ -110,7 +105,6 @@ func ParseDeclList(fset *token.FileSet, filename string, src interface{}) ([]ast return p.parseDeclList(), p.parseEOF() } - // ParseFile parses the source code of a single Go source file and returns // the corresponding ast.File node. The source code may be provided via // the filename of the source file, or via the src parameter. @@ -142,7 +136,6 @@ func ParseFile(fset *token.FileSet, filename string, src interface{}, mode uint) return p.parseFile(), p.GetError(scanner.NoMultiples) // parseFile() reads to EOF } - // ParseFiles calls ParseFile for each file in the filenames list and returns // a map of package name -> package AST with all the packages found. The mode // bits are passed to ParseFile unchanged. Position information is recorded @@ -171,7 +164,6 @@ func ParseFiles(fset *token.FileSet, filenames []string, mode uint) (pkgs map[st return } - // ParseDir calls ParseFile for the files in the directory specified by path and // returns a map of package name -> package AST with all the packages found. If // filter != nil, only the files with os.FileInfo entries passing through the filter diff --git a/src/pkg/go/parser/parser.go b/src/pkg/go/parser/parser.go index 586ee3a9a4..6965f9c91e 100644 --- a/src/pkg/go/parser/parser.go +++ b/src/pkg/go/parser/parser.go @@ -16,7 +16,6 @@ import ( "go/token" ) - // The mode parameter to the Parse* functions is a set of flags (or 0). // They control the amount of source code parsed and other optional // parser functionality. @@ -29,7 +28,6 @@ const ( DeclarationErrors // report declaration errors ) - // The parser structure holds the parser's internal state. type parser struct { file *token.File @@ -66,7 +64,6 @@ type parser struct { targetStack [][]*ast.Ident // stack of unresolved labels } - // scannerMode returns the scanner mode bits given the parser's mode bits. func scannerMode(mode uint) uint { var m uint = scanner.InsertSemis @@ -76,7 +73,6 @@ func scannerMode(mode uint) uint { return m } - func (p *parser) init(fset *token.FileSet, filename string, src []byte, mode uint) { p.file = fset.AddFile(filename, fset.Base(), len(src)) p.scanner.Init(p.file, src, p, scannerMode(mode)) @@ -95,7 +91,6 @@ func (p *parser) init(fset *token.FileSet, filename string, src []byte, mode uin p.openLabelScope() } - // ---------------------------------------------------------------------------- // Scoping support @@ -103,18 +98,15 @@ func (p *parser) openScope() { p.topScope = ast.NewScope(p.topScope) } - func (p *parser) closeScope() { p.topScope = p.topScope.Outer } - func (p *parser) openLabelScope() { p.labelScope = ast.NewScope(p.labelScope) p.targetStack = append(p.targetStack, nil) } - func (p *parser) closeLabelScope() { // resolve labels n := len(p.targetStack) - 1 @@ -130,7 +122,6 @@ func (p *parser) closeLabelScope() { p.labelScope = p.labelScope.Outer } - func (p *parser) declare(decl, data interface{}, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) { for _, ident := range idents { assert(ident.Obj == nil, "identifier already declared or resolved") @@ -152,7 +143,6 @@ func (p *parser) declare(decl, data interface{}, scope *ast.Scope, kind ast.ObjK } } - func (p *parser) shortVarDecl(idents []*ast.Ident) { // Go spec: A short variable declaration may redeclare variables // provided they were originally declared in the same block with @@ -178,13 +168,11 @@ func (p *parser) shortVarDecl(idents []*ast.Ident) { } } - // The unresolved object is a sentinel to mark identifiers that have been added // to the list of unresolved identifiers. The sentinel is only used for verifying // internal consistency. var unresolved = new(ast.Object) - func (p *parser) resolve(x ast.Expr) { // nothing to do if x is not an identifier or the blank identifier ident, _ := x.(*ast.Ident) @@ -210,7 +198,6 @@ func (p *parser) resolve(x ast.Expr) { p.unresolved = append(p.unresolved, ident) } - // ---------------------------------------------------------------------------- // Parsing support @@ -228,21 +215,18 @@ func (p *parser) printTrace(a ...interface{}) { fmt.Println(a...) } - func trace(p *parser, msg string) *parser { p.printTrace(msg, "(") p.indent++ return p } - // Usage pattern: defer un(trace(p, "...")); func un(p *parser) { p.indent-- p.printTrace(")") } - // Advance to the next token. func (p *parser) next0() { // Because of one-token look-ahead, print the previous token @@ -284,7 +268,6 @@ func (p *parser) consumeComment() (comment *ast.Comment, endline int) { return } - // Consume a group of adjacent comments, add it to the parser's // comments list, and return it together with the line at which // the last comment in the group ends. An empty line or non-comment @@ -306,7 +289,6 @@ func (p *parser) consumeCommentGroup() (comments *ast.CommentGroup, endline int) return } - // Advance to the next non-comment token. In the process, collect // any comment groups encountered, and remember the last lead and // and line comments. @@ -357,12 +339,10 @@ func (p *parser) next() { } } - func (p *parser) error(pos token.Pos, msg string) { p.Error(p.file.Position(pos), msg) } - func (p *parser) errorExpected(pos token.Pos, msg string) { msg = "expected " + msg if pos == p.pos { @@ -380,7 +360,6 @@ func (p *parser) errorExpected(pos token.Pos, msg string) { p.error(pos, msg) } - func (p *parser) expect(tok token.Token) token.Pos { pos := p.pos if p.tok != tok { @@ -390,21 +369,18 @@ func (p *parser) expect(tok token.Token) token.Pos { return pos } - func (p *parser) expectSemi() { if p.tok != token.RPAREN && p.tok != token.RBRACE { p.expect(token.SEMICOLON) } } - func assert(cond bool, msg string) { if !cond { panic("go/parser internal error: " + msg) } } - // ---------------------------------------------------------------------------- // Identifiers @@ -420,7 +396,6 @@ func (p *parser) parseIdent() *ast.Ident { return &ast.Ident{pos, name, nil} } - func (p *parser) parseIdentList() (list []*ast.Ident) { if p.trace { defer un(trace(p, "IdentList")) @@ -435,7 +410,6 @@ func (p *parser) parseIdentList() (list []*ast.Ident) { return } - // ---------------------------------------------------------------------------- // Common productions @@ -454,7 +428,6 @@ func (p *parser) parseExprList(lhs bool) (list []ast.Expr) { return } - func (p *parser) parseLhsList() []ast.Expr { list := p.parseExprList(true) switch p.tok { @@ -478,12 +451,10 @@ func (p *parser) parseLhsList() []ast.Expr { return list } - func (p *parser) parseRhsList() []ast.Expr { return p.parseExprList(false) } - // ---------------------------------------------------------------------------- // Types @@ -504,7 +475,6 @@ func (p *parser) parseType() ast.Expr { return typ } - // If the result is an identifier, it is not resolved. func (p *parser) parseTypeName() ast.Expr { if p.trace { @@ -525,7 +495,6 @@ func (p *parser) parseTypeName() ast.Expr { return ident } - func (p *parser) parseArrayType(ellipsisOk bool) ast.Expr { if p.trace { defer un(trace(p, "ArrayType")) @@ -545,7 +514,6 @@ func (p *parser) parseArrayType(ellipsisOk bool) ast.Expr { return &ast.ArrayType{lbrack, len, elt} } - func (p *parser) makeIdentList(list []ast.Expr) []*ast.Ident { idents := make([]*ast.Ident, len(list)) for i, x := range list { @@ -560,7 +528,6 @@ func (p *parser) makeIdentList(list []ast.Expr) []*ast.Ident { return idents } - func (p *parser) parseFieldDecl(scope *ast.Scope) *ast.Field { if p.trace { defer un(trace(p, "FieldDecl")) @@ -602,7 +569,6 @@ func (p *parser) parseFieldDecl(scope *ast.Scope) *ast.Field { return field } - func (p *parser) parseStructType() *ast.StructType { if p.trace { defer un(trace(p, "StructType")) @@ -624,7 +590,6 @@ func (p *parser) parseStructType() *ast.StructType { return &ast.StructType{pos, &ast.FieldList{lbrace, list, rbrace}, false} } - func (p *parser) parsePointerType() *ast.StarExpr { if p.trace { defer un(trace(p, "PointerType")) @@ -636,7 +601,6 @@ func (p *parser) parsePointerType() *ast.StarExpr { return &ast.StarExpr{star, base} } - func (p *parser) tryVarType(isParam bool) ast.Expr { if isParam && p.tok == token.ELLIPSIS { pos := p.pos @@ -654,7 +618,6 @@ func (p *parser) tryVarType(isParam bool) ast.Expr { return p.tryIdentOrType(false) } - func (p *parser) parseVarType(isParam bool) ast.Expr { typ := p.tryVarType(isParam) if typ == nil { @@ -666,7 +629,6 @@ func (p *parser) parseVarType(isParam bool) ast.Expr { return typ } - func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) { if p.trace { defer un(trace(p, "VarList")) @@ -694,7 +656,6 @@ func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) { return } - func (p *parser) parseParameterList(scope *ast.Scope, ellipsisOk bool) (params []*ast.Field) { if p.trace { defer un(trace(p, "ParameterList")) @@ -739,7 +700,6 @@ func (p *parser) parseParameterList(scope *ast.Scope, ellipsisOk bool) (params [ return } - func (p *parser) parseParameters(scope *ast.Scope, ellipsisOk bool) *ast.FieldList { if p.trace { defer un(trace(p, "Parameters")) @@ -755,7 +715,6 @@ func (p *parser) parseParameters(scope *ast.Scope, ellipsisOk bool) *ast.FieldLi return &ast.FieldList{lparen, params, rparen} } - func (p *parser) parseResult(scope *ast.Scope) *ast.FieldList { if p.trace { defer un(trace(p, "Result")) @@ -775,7 +734,6 @@ func (p *parser) parseResult(scope *ast.Scope) *ast.FieldList { return nil } - func (p *parser) parseSignature(scope *ast.Scope) (params, results *ast.FieldList) { if p.trace { defer un(trace(p, "Signature")) @@ -787,7 +745,6 @@ func (p *parser) parseSignature(scope *ast.Scope) (params, results *ast.FieldLis return } - func (p *parser) parseFuncType() (*ast.FuncType, *ast.Scope) { if p.trace { defer un(trace(p, "FuncType")) @@ -800,7 +757,6 @@ func (p *parser) parseFuncType() (*ast.FuncType, *ast.Scope) { return &ast.FuncType{pos, params, results}, scope } - func (p *parser) parseMethodSpec(scope *ast.Scope) *ast.Field { if p.trace { defer un(trace(p, "MethodSpec")) @@ -829,7 +785,6 @@ func (p *parser) parseMethodSpec(scope *ast.Scope) *ast.Field { return spec } - func (p *parser) parseInterfaceType() *ast.InterfaceType { if p.trace { defer un(trace(p, "InterfaceType")) @@ -848,7 +803,6 @@ func (p *parser) parseInterfaceType() *ast.InterfaceType { return &ast.InterfaceType{pos, &ast.FieldList{lbrace, list, rbrace}, false} } - func (p *parser) parseMapType() *ast.MapType { if p.trace { defer un(trace(p, "MapType")) @@ -863,7 +817,6 @@ func (p *parser) parseMapType() *ast.MapType { return &ast.MapType{pos, key, value} } - func (p *parser) parseChanType() *ast.ChanType { if p.trace { defer un(trace(p, "ChanType")) @@ -887,7 +840,6 @@ func (p *parser) parseChanType() *ast.ChanType { return &ast.ChanType{pos, dir, value} } - // If the result is an identifier, it is not resolved. func (p *parser) tryIdentOrType(ellipsisOk bool) ast.Expr { switch p.tok { @@ -920,7 +872,6 @@ func (p *parser) tryIdentOrType(ellipsisOk bool) ast.Expr { return nil } - func (p *parser) tryType() ast.Expr { typ := p.tryIdentOrType(false) if typ != nil { @@ -929,7 +880,6 @@ func (p *parser) tryType() ast.Expr { return typ } - // ---------------------------------------------------------------------------- // Blocks @@ -945,7 +895,6 @@ func (p *parser) parseStmtList() (list []ast.Stmt) { return } - func (p *parser) parseBody(scope *ast.Scope) *ast.BlockStmt { if p.trace { defer un(trace(p, "Body")) @@ -962,7 +911,6 @@ func (p *parser) parseBody(scope *ast.Scope) *ast.BlockStmt { return &ast.BlockStmt{lbrace, list, rbrace} } - func (p *parser) parseBlockStmt() *ast.BlockStmt { if p.trace { defer un(trace(p, "BlockStmt")) @@ -977,7 +925,6 @@ func (p *parser) parseBlockStmt() *ast.BlockStmt { return &ast.BlockStmt{lbrace, list, rbrace} } - // ---------------------------------------------------------------------------- // Expressions @@ -999,7 +946,6 @@ func (p *parser) parseFuncTypeOrLit() ast.Expr { return &ast.FuncLit{typ, body} } - // parseOperand may return an expression or a raw type (incl. array // types of the form [...]T. Callers must verify the result. // If lhs is set and the result is an identifier, it is not resolved. @@ -1049,7 +995,6 @@ func (p *parser) parseOperand(lhs bool) ast.Expr { return &ast.BadExpr{pos, p.pos} } - func (p *parser) parseSelector(x ast.Expr) ast.Expr { if p.trace { defer un(trace(p, "Selector")) @@ -1060,7 +1005,6 @@ func (p *parser) parseSelector(x ast.Expr) ast.Expr { return &ast.SelectorExpr{x, sel} } - func (p *parser) parseTypeAssertion(x ast.Expr) ast.Expr { if p.trace { defer un(trace(p, "TypeAssertion")) @@ -1079,7 +1023,6 @@ func (p *parser) parseTypeAssertion(x ast.Expr) ast.Expr { return &ast.TypeAssertExpr{x, typ} } - func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr { if p.trace { defer un(trace(p, "IndexOrSlice")) @@ -1108,7 +1051,6 @@ func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr { return &ast.IndexExpr{x, lbrack, low, rbrack} } - func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr { if p.trace { defer un(trace(p, "CallOrConversion")) @@ -1135,7 +1077,6 @@ func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr { return &ast.CallExpr{fun, lparen, list, ellipsis, rparen} } - func (p *parser) parseElement(keyOk bool) ast.Expr { if p.trace { defer un(trace(p, "Element")) @@ -1158,7 +1099,6 @@ func (p *parser) parseElement(keyOk bool) ast.Expr { return x } - func (p *parser) parseElementList() (list []ast.Expr) { if p.trace { defer un(trace(p, "ElementList")) @@ -1175,7 +1115,6 @@ func (p *parser) parseElementList() (list []ast.Expr) { return } - func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr { if p.trace { defer un(trace(p, "LiteralValue")) @@ -1192,7 +1131,6 @@ func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr { return &ast.CompositeLit{typ, lbrace, elts, rbrace} } - // checkExpr checks that x is an expression (and not a type). func (p *parser) checkExpr(x ast.Expr) ast.Expr { switch t := unparen(x).(type) { @@ -1229,7 +1167,6 @@ func (p *parser) checkExpr(x ast.Expr) ast.Expr { return x } - // isTypeName returns true iff x is a (qualified) TypeName. func isTypeName(x ast.Expr) bool { switch t := x.(type) { @@ -1244,7 +1181,6 @@ func isTypeName(x ast.Expr) bool { return true } - // isLiteralType returns true iff x is a legal composite literal type. func isLiteralType(x ast.Expr) bool { switch t := x.(type) { @@ -1262,7 +1198,6 @@ func isLiteralType(x ast.Expr) bool { return true } - // If x is of the form *T, deref returns T, otherwise it returns x. func deref(x ast.Expr) ast.Expr { if p, isPtr := x.(*ast.StarExpr); isPtr { @@ -1271,7 +1206,6 @@ func deref(x ast.Expr) ast.Expr { return x } - // If x is of the form (T), unparen returns unparen(T), otherwise it returns x. func unparen(x ast.Expr) ast.Expr { if p, isParen := x.(*ast.ParenExpr); isParen { @@ -1280,7 +1214,6 @@ func unparen(x ast.Expr) ast.Expr { return x } - // checkExprOrType checks that x is an expression or a type // (and not a raw type such as [...]T). // @@ -1305,7 +1238,6 @@ func (p *parser) checkExprOrType(x ast.Expr) ast.Expr { return x } - // If lhs is set and the result is an identifier, it is not resolved. func (p *parser) parsePrimaryExpr(lhs bool) ast.Expr { if p.trace { @@ -1360,7 +1292,6 @@ L: return x } - // If lhs is set and the result is an identifier, it is not resolved. func (p *parser) parseUnaryExpr(lhs bool) ast.Expr { if p.trace { @@ -1398,7 +1329,6 @@ func (p *parser) parseUnaryExpr(lhs bool) ast.Expr { return p.parsePrimaryExpr(lhs) } - // If lhs is set and the result is an identifier, it is not resolved. func (p *parser) parseBinaryExpr(lhs bool, prec1 int) ast.Expr { if p.trace { @@ -1422,7 +1352,6 @@ func (p *parser) parseBinaryExpr(lhs bool, prec1 int) ast.Expr { return x } - // If lhs is set and the result is an identifier, it is not resolved. // TODO(gri): parseExpr may return a type or even a raw type ([..]int) - // should reject when a type/raw type is obviously not allowed @@ -1434,12 +1363,10 @@ func (p *parser) parseExpr(lhs bool) ast.Expr { return p.parseBinaryExpr(lhs, token.LowestPrec+1) } - func (p *parser) parseRhs() ast.Expr { return p.parseExpr(false) } - // ---------------------------------------------------------------------------- // Statements @@ -1502,7 +1429,6 @@ func (p *parser) parseSimpleStmt(labelOk bool) ast.Stmt { return &ast.ExprStmt{x[0]} } - func (p *parser) parseCallExpr() *ast.CallExpr { x := p.parseRhs() if call, isCall := x.(*ast.CallExpr); isCall { @@ -1512,7 +1438,6 @@ func (p *parser) parseCallExpr() *ast.CallExpr { return nil } - func (p *parser) parseGoStmt() ast.Stmt { if p.trace { defer un(trace(p, "GoStmt")) @@ -1528,7 +1453,6 @@ func (p *parser) parseGoStmt() ast.Stmt { return &ast.GoStmt{pos, call} } - func (p *parser) parseDeferStmt() ast.Stmt { if p.trace { defer un(trace(p, "DeferStmt")) @@ -1544,7 +1468,6 @@ func (p *parser) parseDeferStmt() ast.Stmt { return &ast.DeferStmt{pos, call} } - func (p *parser) parseReturnStmt() *ast.ReturnStmt { if p.trace { defer un(trace(p, "ReturnStmt")) @@ -1561,7 +1484,6 @@ func (p *parser) parseReturnStmt() *ast.ReturnStmt { return &ast.ReturnStmt{pos, x} } - func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt { if p.trace { defer un(trace(p, "BranchStmt")) @@ -1580,7 +1502,6 @@ func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt { return &ast.BranchStmt{pos, tok, label} } - func (p *parser) makeExpr(s ast.Stmt) ast.Expr { if s == nil { return nil @@ -1592,7 +1513,6 @@ func (p *parser) makeExpr(s ast.Stmt) ast.Expr { return &ast.BadExpr{s.Pos(), s.End()} } - func (p *parser) parseIfStmt() *ast.IfStmt { if p.trace { defer un(trace(p, "IfStmt")) @@ -1635,7 +1555,6 @@ func (p *parser) parseIfStmt() *ast.IfStmt { return &ast.IfStmt{pos, s, x, body, else_} } - func (p *parser) parseTypeList() (list []ast.Expr) { if p.trace { defer un(trace(p, "TypeList")) @@ -1650,7 +1569,6 @@ func (p *parser) parseTypeList() (list []ast.Expr) { return } - func (p *parser) parseCaseClause(exprSwitch bool) *ast.CaseClause { if p.trace { defer un(trace(p, "CaseClause")) @@ -1677,7 +1595,6 @@ func (p *parser) parseCaseClause(exprSwitch bool) *ast.CaseClause { return &ast.CaseClause{pos, list, colon, body} } - func isExprSwitch(s ast.Stmt) bool { if s == nil { return true @@ -1691,7 +1608,6 @@ func isExprSwitch(s ast.Stmt) bool { return false } - func (p *parser) parseSwitchStmt() ast.Stmt { if p.trace { defer un(trace(p, "SwitchStmt")) @@ -1737,7 +1653,6 @@ func (p *parser) parseSwitchStmt() ast.Stmt { return &ast.TypeSwitchStmt{pos, s1, s2, body} } - func (p *parser) parseCommClause() *ast.CommClause { if p.trace { defer un(trace(p, "CommClause")) @@ -1799,7 +1714,6 @@ func (p *parser) parseCommClause() *ast.CommClause { return &ast.CommClause{pos, comm, colon, body} } - func (p *parser) parseSelectStmt() *ast.SelectStmt { if p.trace { defer un(trace(p, "SelectStmt")) @@ -1818,7 +1732,6 @@ func (p *parser) parseSelectStmt() *ast.SelectStmt { return &ast.SelectStmt{pos, body} } - func (p *parser) parseForStmt() ast.Stmt { if p.trace { defer un(trace(p, "ForStmt")) @@ -1888,7 +1801,6 @@ func (p *parser) parseForStmt() ast.Stmt { return &ast.ForStmt{pos, s1, p.makeExpr(s2), s3, body} } - func (p *parser) parseStmt() (s ast.Stmt) { if p.trace { defer un(trace(p, "Statement")) @@ -1945,13 +1857,11 @@ func (p *parser) parseStmt() (s ast.Stmt) { return } - // ---------------------------------------------------------------------------- // Declarations type parseSpecFunction func(p *parser, doc *ast.CommentGroup, iota int) ast.Spec - func parseImportSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { if p.trace { defer un(trace(p, "ImportSpec")) @@ -1982,7 +1892,6 @@ func parseImportSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { return spec } - func parseConstSpec(p *parser, doc *ast.CommentGroup, iota int) ast.Spec { if p.trace { defer un(trace(p, "ConstSpec")) @@ -2007,7 +1916,6 @@ func parseConstSpec(p *parser, doc *ast.CommentGroup, iota int) ast.Spec { return spec } - func parseTypeSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { if p.trace { defer un(trace(p, "TypeSpec")) @@ -2029,7 +1937,6 @@ func parseTypeSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { return spec } - func parseVarSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { if p.trace { defer un(trace(p, "VarSpec")) @@ -2054,7 +1961,6 @@ func parseVarSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { return spec } - func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl { if p.trace { defer un(trace(p, "GenDecl("+keyword.String()+")")) @@ -2079,7 +1985,6 @@ func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.Gen return &ast.GenDecl{doc, pos, keyword, lparen, list, rparen} } - func (p *parser) parseReceiver(scope *ast.Scope) *ast.FieldList { if p.trace { defer un(trace(p, "Receiver")) @@ -2107,7 +2012,6 @@ func (p *parser) parseReceiver(scope *ast.Scope) *ast.FieldList { return par } - func (p *parser) parseFuncDecl() *ast.FuncDecl { if p.trace { defer un(trace(p, "FunctionDecl")) @@ -2148,7 +2052,6 @@ func (p *parser) parseFuncDecl() *ast.FuncDecl { return decl } - func (p *parser) parseDecl() ast.Decl { if p.trace { defer un(trace(p, "Declaration")) @@ -2179,7 +2082,6 @@ func (p *parser) parseDecl() ast.Decl { return p.parseGenDecl(p.tok, f) } - func (p *parser) parseDeclList() (list []ast.Decl) { if p.trace { defer un(trace(p, "DeclList")) @@ -2192,7 +2094,6 @@ func (p *parser) parseDeclList() (list []ast.Decl) { return } - // ---------------------------------------------------------------------------- // Source files diff --git a/src/pkg/go/parser/parser_test.go b/src/pkg/go/parser/parser_test.go index 5b52f51d4a..8269db839b 100644 --- a/src/pkg/go/parser/parser_test.go +++ b/src/pkg/go/parser/parser_test.go @@ -10,7 +10,6 @@ import ( "testing" ) - var fset = token.NewFileSet() var illegalInputs = []interface{}{ @@ -24,7 +23,6 @@ var illegalInputs = []interface{}{ `package p; const c; /* should have constant value */`, } - func TestParseIllegalInputs(t *testing.T) { for _, src := range illegalInputs { _, err := ParseFile(fset, "", src, 0) @@ -34,7 +32,6 @@ func TestParseIllegalInputs(t *testing.T) { } } - var validPrograms = []interface{}{ "package p\n", `package p;`, @@ -56,7 +53,6 @@ var validPrograms = []interface{}{ `package p; func f() { switch ; {} };`, } - func TestParseValidPrograms(t *testing.T) { for _, src := range validPrograms { _, err := ParseFile(fset, "", src, 0) @@ -66,13 +62,11 @@ func TestParseValidPrograms(t *testing.T) { } } - var validFiles = []string{ "parser.go", "parser_test.go", } - func TestParse3(t *testing.T) { for _, filename := range validFiles { _, err := ParseFile(fset, filename, nil, DeclarationErrors) @@ -82,7 +76,6 @@ func TestParse3(t *testing.T) { } } - func nameFilter(filename string) bool { switch filename { case "parser.go": @@ -94,10 +87,8 @@ func nameFilter(filename string) bool { return true } - func dirFilter(f *os.FileInfo) bool { return nameFilter(f.Name) } - func TestParse4(t *testing.T) { path := "." pkgs, err := ParseDir(fset, path, dirFilter, 0) diff --git a/src/pkg/go/printer/nodes.go b/src/pkg/go/printer/nodes.go index f2b79d8103..c8c641e32b 100644 --- a/src/pkg/go/printer/nodes.go +++ b/src/pkg/go/printer/nodes.go @@ -14,7 +14,6 @@ import ( "go/token" ) - // Other formatting issues: // - better comment formatting for /*-style comments at the end of a line (e.g. a declaration) // when the comment spans multiple lines; if such a comment is just two lines, formatting is @@ -23,7 +22,6 @@ import ( // - should use blank instead of tab to separate one-line function bodies from // the function header unless there is a group of consecutive one-liners - // ---------------------------------------------------------------------------- // Common AST nodes. @@ -56,7 +54,6 @@ func (p *printer) linebreak(line, min int, ws whiteSpace, newSection bool) (prin return } - // setComment sets g as the next comment if g != nil and if node comments // are enabled - this mode is used when printing source code fragments such // as exports only. It assumes that there are no other pending comments to @@ -78,7 +75,6 @@ func (p *printer) setComment(g *ast.CommentGroup) { p.cindex = 0 } - type exprListMode uint const ( @@ -90,7 +86,6 @@ const ( periodSep // elements are separated by periods ) - // Sets multiLine to true if the identifier list spans multiple lines. // If indent is set, a multi-line identifier list is indented after the // first linebreak encountered. @@ -107,7 +102,6 @@ func (p *printer) identList(list []*ast.Ident, indent bool, multiLine *bool) { p.exprList(token.NoPos, xlist, 1, mode, multiLine, token.NoPos) } - // Print a list of expressions. If the list spans multiple // source lines, the original line breaks are respected between // expressions. Sets multiLine to true if the list spans multiple @@ -271,7 +265,6 @@ func (p *printer) exprList(prev0 token.Pos, list []ast.Expr, depth int, mode exp } } - // Sets multiLine to true if the the parameter list spans multiple lines. func (p *printer) parameters(fields *ast.FieldList, multiLine *bool) { p.print(fields.Opening, token.LPAREN) @@ -302,7 +295,6 @@ func (p *printer) parameters(fields *ast.FieldList, multiLine *bool) { p.print(fields.Closing, token.RPAREN) } - // Sets multiLine to true if the signature spans multiple lines. func (p *printer) signature(params, result *ast.FieldList, multiLine *bool) { p.parameters(params, multiLine) @@ -318,7 +310,6 @@ func (p *printer) signature(params, result *ast.FieldList, multiLine *bool) { } } - func identListSize(list []*ast.Ident, maxSize int) (size int) { for i, x := range list { if i > 0 { @@ -332,7 +323,6 @@ func identListSize(list []*ast.Ident, maxSize int) (size int) { return } - func (p *printer) isOneLineFieldList(list []*ast.Field) bool { if len(list) != 1 { return false // allow only one field @@ -351,12 +341,10 @@ func (p *printer) isOneLineFieldList(list []*ast.Field) bool { return namesSize+typeSize <= maxSize } - func (p *printer) setLineComment(text string) { p.setComment(&ast.CommentGroup{[]*ast.Comment{&ast.Comment{token.NoPos, text}}}) } - func (p *printer) fieldList(fields *ast.FieldList, isStruct, isIncomplete bool) { p.nesting++ defer func() { @@ -475,7 +463,6 @@ func (p *printer) fieldList(fields *ast.FieldList, isStruct, isIncomplete bool) p.print(unindent, formfeed, rbrace, token.RBRACE) } - // ---------------------------------------------------------------------------- // Expressions @@ -534,7 +521,6 @@ func walkBinary(e *ast.BinaryExpr) (has4, has5 bool, maxProblem int) { return } - func cutoff(e *ast.BinaryExpr, depth int) int { has4, has5, maxProblem := walkBinary(e) if maxProblem > 0 { @@ -552,7 +538,6 @@ func cutoff(e *ast.BinaryExpr, depth int) int { return 4 } - func diffPrec(expr ast.Expr, prec int) int { x, ok := expr.(*ast.BinaryExpr) if !ok || prec != x.Op.Precedence() { @@ -561,7 +546,6 @@ func diffPrec(expr ast.Expr, prec int) int { return 0 } - func reduceDepth(depth int) int { depth-- if depth < 1 { @@ -570,7 +554,6 @@ func reduceDepth(depth int) int { return depth } - // Format the binary expression: decide the cutoff and then format. // Let's call depth == 1 Normal mode, and depth > 1 Compact mode. // (Algorithm suggestion by Russ Cox.) @@ -648,13 +631,11 @@ func (p *printer) binaryExpr(x *ast.BinaryExpr, prec1, cutoff, depth int, multiL } } - func isBinary(expr ast.Expr) bool { _, ok := expr.(*ast.BinaryExpr) return ok } - // If the expression contains one or more selector expressions, splits it into // two expressions at the rightmost period. Writes entire expr to suffix when // selector isn't found. Rewrites AST nodes for calls, index expressions and @@ -694,7 +675,6 @@ func splitSelector(expr ast.Expr) (body, suffix ast.Expr) { return } - // Convert an expression into an expression list split at the periods of // selector expressions. func selectorExprList(expr ast.Expr) (list []ast.Expr) { @@ -713,7 +693,6 @@ func selectorExprList(expr ast.Expr) (list []ast.Expr) { return } - // Sets multiLine to true if the expression spans multiple lines. func (p *printer) expr1(expr ast.Expr, prec1, depth int, multiLine *bool) { p.print(expr.Pos()) @@ -900,19 +879,16 @@ func (p *printer) expr1(expr ast.Expr, prec1, depth int, multiLine *bool) { return } - func (p *printer) expr0(x ast.Expr, depth int, multiLine *bool) { p.expr1(x, token.LowestPrec, depth, multiLine) } - // Sets multiLine to true if the expression spans multiple lines. func (p *printer) expr(x ast.Expr, multiLine *bool) { const depth = 1 p.expr1(x, token.LowestPrec, depth, multiLine) } - // ---------------------------------------------------------------------------- // Statements @@ -937,7 +913,6 @@ func (p *printer) stmtList(list []ast.Stmt, _indent int, nextIsRBrace bool) { } } - // block prints an *ast.BlockStmt; it always spans at least two lines. func (p *printer) block(s *ast.BlockStmt, indent int) { p.print(s.Pos(), token.LBRACE) @@ -946,7 +921,6 @@ func (p *printer) block(s *ast.BlockStmt, indent int) { p.print(s.Rbrace, token.RBRACE) } - func isTypeName(x ast.Expr) bool { switch t := x.(type) { case *ast.Ident: @@ -957,7 +931,6 @@ func isTypeName(x ast.Expr) bool { return false } - func stripParens(x ast.Expr) ast.Expr { if px, strip := x.(*ast.ParenExpr); strip { // parentheses must not be stripped if there are any @@ -984,7 +957,6 @@ func stripParens(x ast.Expr) ast.Expr { return x } - func (p *printer) controlClause(isForStmt bool, init ast.Stmt, expr ast.Expr, post ast.Stmt) { p.print(blank) needsBlank := false @@ -1019,7 +991,6 @@ func (p *printer) controlClause(isForStmt bool, init ast.Stmt, expr ast.Expr, po } } - // Sets multiLine to true if the statements spans multiple lines. func (p *printer) stmt(stmt ast.Stmt, nextIsRBrace bool, multiLine *bool) { p.print(stmt.Pos()) @@ -1193,7 +1164,6 @@ func (p *printer) stmt(stmt ast.Stmt, nextIsRBrace bool, multiLine *bool) { return } - // ---------------------------------------------------------------------------- // Declarations @@ -1262,7 +1232,6 @@ func keepTypeColumn(specs []ast.Spec) []bool { return m } - func (p *printer) valueSpec(s *ast.ValueSpec, keepType, doIndent bool, multiLine *bool) { p.setComment(s.Doc) p.identList(s.Names, doIndent, multiLine) // always present @@ -1287,7 +1256,6 @@ func (p *printer) valueSpec(s *ast.ValueSpec, keepType, doIndent bool, multiLine } } - // The parameter n is the number of specs in the group. If doIndent is set, // multi-line identifier lists in the spec are indented when the first // linebreak is encountered. @@ -1336,7 +1304,6 @@ func (p *printer) spec(spec ast.Spec, n int, doIndent bool, multiLine *bool) { } } - // Sets multiLine to true if the declaration spans multiple lines. func (p *printer) genDecl(d *ast.GenDecl, multiLine *bool) { p.setComment(d.Doc) @@ -1380,7 +1347,6 @@ func (p *printer) genDecl(d *ast.GenDecl, multiLine *bool) { } } - // nodeSize determines the size of n in chars after formatting. // The result is <= maxSize if the node fits on one line with at // most maxSize chars and the formatted output doesn't contain @@ -1418,7 +1384,6 @@ func (p *printer) nodeSize(n ast.Node, maxSize int) (size int) { return } - func (p *printer) isOneLineFunc(b *ast.BlockStmt, headerSize int) bool { pos1 := b.Pos() pos2 := b.Rbrace @@ -1442,7 +1407,6 @@ func (p *printer) isOneLineFunc(b *ast.BlockStmt, headerSize int) bool { return headerSize+bodySize <= maxSize } - // Sets multiLine to true if the function body spans multiple lines. func (p *printer) funcBody(b *ast.BlockStmt, headerSize int, isLit bool, multiLine *bool) { if b == nil { @@ -1479,7 +1443,6 @@ func (p *printer) funcBody(b *ast.BlockStmt, headerSize int, isLit bool, multiLi *multiLine = true } - // distance returns the column difference between from and to if both // are on the same line; if they are on different lines (or unknown) // the result is infinity. @@ -1491,7 +1454,6 @@ func (p *printer) distance(from0 token.Pos, to token.Position) int { return infinity } - // Sets multiLine to true if the declaration spans multiple lines. func (p *printer) funcDecl(d *ast.FuncDecl, multiLine *bool) { p.setComment(d.Doc) @@ -1505,7 +1467,6 @@ func (p *printer) funcDecl(d *ast.FuncDecl, multiLine *bool) { p.funcBody(d.Body, p.distance(d.Pos(), p.pos), false, multiLine) } - // Sets multiLine to true if the declaration spans multiple lines. func (p *printer) decl(decl ast.Decl, multiLine *bool) { switch d := decl.(type) { @@ -1520,7 +1481,6 @@ func (p *printer) decl(decl ast.Decl, multiLine *bool) { } } - // ---------------------------------------------------------------------------- // Files @@ -1535,7 +1495,6 @@ func declToken(decl ast.Decl) (tok token.Token) { return } - func (p *printer) file(src *ast.File) { p.setComment(src.Doc) p.print(src.Pos(), token.PACKAGE, blank) diff --git a/src/pkg/go/printer/performance_test.go b/src/pkg/go/printer/performance_test.go index 31de0b7ad4..84fb2808eb 100644 --- a/src/pkg/go/printer/performance_test.go +++ b/src/pkg/go/printer/performance_test.go @@ -17,17 +17,14 @@ import ( "testing" ) - var testfile *ast.File - func testprint(out io.Writer, file *ast.File) { if _, err := (&Config{TabIndent | UseSpaces, 8}).Fprint(out, fset, file); err != nil { log.Fatalf("print error: %s", err) } } - // cannot initialize in init because (printer) Fprint launches goroutines. func initialize() { const filename = "testdata/parser.go" @@ -51,7 +48,6 @@ func initialize() { testfile = file } - func BenchmarkPrint(b *testing.B) { if testfile == nil { initialize() diff --git a/src/pkg/go/printer/printer.go b/src/pkg/go/printer/printer.go index 40b15dd79b..30431ef6c7 100644 --- a/src/pkg/go/printer/printer.go +++ b/src/pkg/go/printer/printer.go @@ -17,7 +17,6 @@ import ( "tabwriter" ) - const debug = false // enable for debugging @@ -33,7 +32,6 @@ const ( unindent = whiteSpace('<') ) - var ( esc = []byte{tabwriter.Escape} htab = []byte{'\t'} @@ -42,16 +40,13 @@ var ( formfeeds = []byte("\f\f\f\f\f\f\f\f") // more than the max determined by nlines ) - // Special positions var noPos token.Position // use noPos when a position is needed but not known var infinity = 1 << 30 - // Use ignoreMultiLine if the multiLine information is not important. var ignoreMultiLine = new(bool) - // A pmode value represents the current printer mode. type pmode int @@ -60,7 +55,6 @@ const ( noExtraLinebreak ) - type printer struct { // Configuration (does not change after initialization) output io.Writer @@ -98,7 +92,6 @@ type printer struct { nodeSizes map[ast.Node]int } - func (p *printer) init(output io.Writer, cfg *Config, fset *token.FileSet, nodeSizes map[ast.Node]int) { p.output = output p.Config = *cfg @@ -108,7 +101,6 @@ func (p *printer) init(output io.Writer, cfg *Config, fset *token.FileSet, nodeS p.nodeSizes = nodeSizes } - func (p *printer) internalError(msg ...interface{}) { if debug { fmt.Print(p.pos.String() + ": ") @@ -117,7 +109,6 @@ func (p *printer) internalError(msg ...interface{}) { } } - // escape escapes string s by bracketing it with tabwriter.Escape. // Escaped strings pass through tabwriter unchanged. (Note that // valid Go programs cannot contain tabwriter.Escape bytes since @@ -131,7 +122,6 @@ func (p *printer) escape(s string) string { return p.litbuf.String() } - // nlines returns the adjusted number of linebreaks given the desired number // of breaks n such that min <= result <= max where max depends on the current // nesting level. @@ -140,7 +130,7 @@ func (p *printer) nlines(n, min int) int { if n < min { return min } - max := 3 // max. number of newlines at the top level (p.nesting == 0) + max := 2 // max. number of newlines at the top level (p.nesting == 0) if p.nesting > 0 { max = 2 // max. number of newlines everywhere else } @@ -150,7 +140,6 @@ func (p *printer) nlines(n, min int) int { return n } - // write0 writes raw (uninterpreted) data to p.output and handles errors. // write0 does not indent after newlines, and does not HTML-escape or update p.pos. // @@ -165,7 +154,6 @@ func (p *printer) write0(data []byte) { } } - // write interprets data and writes it to p.output. It inserts indentation // after a line break unless in a tabwriter escape sequence. // It updates p.pos as a side-effect. @@ -220,7 +208,6 @@ func (p *printer) write(data []byte) { p.pos.Column += d } - func (p *printer) writeNewlines(n int, useFF bool) { if n > 0 { n = p.nlines(n, 0) @@ -232,7 +219,6 @@ func (p *printer) writeNewlines(n int, useFF bool) { } } - // writeItem writes data at position pos. data is the text corresponding to // a single lexical token, but may also be comment text. pos is the actual // (or at least very accurately estimated) position of the data in the original @@ -261,7 +247,6 @@ func (p *printer) writeItem(pos token.Position, data string) { p.last = p.pos } - // writeCommentPrefix writes the whitespace before a comment. // If there is any pending whitespace, it consumes as much of // it as is likely to help position the comment nicely. @@ -368,7 +353,6 @@ func (p *printer) writeCommentPrefix(pos, next token.Position, prev *ast.Comment } } - // TODO(gri): It should be possible to convert the code below from using // []byte to string and in the process eliminate some conversions. @@ -398,7 +382,6 @@ func split(text []byte) [][]byte { return lines } - func isBlank(s []byte) bool { for _, b := range s { if b > ' ' { @@ -408,7 +391,6 @@ func isBlank(s []byte) bool { return true } - func commonPrefix(a, b []byte) []byte { i := 0 for i < len(a) && i < len(b) && a[i] == b[i] && (a[i] <= ' ' || a[i] == '*') { @@ -417,7 +399,6 @@ func commonPrefix(a, b []byte) []byte { return a[0:i] } - func stripCommonPrefix(lines [][]byte) { if len(lines) < 2 { return // at most one line - nothing to do @@ -545,7 +526,6 @@ func stripCommonPrefix(lines [][]byte) { } } - func (p *printer) writeComment(comment *ast.Comment) { text := comment.Text @@ -575,7 +555,6 @@ func (p *printer) writeComment(comment *ast.Comment) { } } - // writeCommentSuffix writes a line break after a comment if indicated // and processes any leftover indentation information. If a line break // is needed, the kind of break (newline vs formfeed) depends on the @@ -613,7 +592,6 @@ func (p *printer) writeCommentSuffix(needsLinebreak bool) (droppedFF bool) { return } - // intersperseComments consumes all comments that appear before the next token // tok and prints it together with the buffered whitespace (i.e., the whitespace // that needs to be written before the next token). A heuristic is used to mix @@ -651,7 +629,6 @@ func (p *printer) intersperseComments(next token.Position, tok token.Token) (dro return false } - // whiteWhitespace writes the first n whitespace entries. func (p *printer) writeWhitespace(n int) { // write entries @@ -701,7 +678,6 @@ func (p *printer) writeWhitespace(n int) { p.wsbuf = p.wsbuf[0:i] } - // ---------------------------------------------------------------------------- // Printing interface @@ -724,7 +700,6 @@ func mayCombine(prev token.Token, next byte) (b bool) { return } - // print prints a list of "items" (roughly corresponding to syntactic // tokens, but also including whitespace and formatting information). // It is the only print function that should be called directly from @@ -812,7 +787,6 @@ func (p *printer) print(args ...interface{}) { } } - // commentBefore returns true iff the current comment occurs // before the next position in the source code. // @@ -820,7 +794,6 @@ func (p *printer) commentBefore(next token.Position) bool { return p.cindex < len(p.comments) && p.fset.Position(p.comments[p.cindex].List[0].Pos()).Offset < next.Offset } - // Flush prints any pending comments and whitespace occurring // textually before the position of the next token tok. Flush // returns true if a pending formfeed character was dropped @@ -838,7 +811,6 @@ func (p *printer) flush(next token.Position, tok token.Token) (droppedFF bool) { return } - // ---------------------------------------------------------------------------- // Trimmer @@ -854,7 +826,6 @@ type trimmer struct { space bytes.Buffer } - // trimmer is implemented as a state machine. // It can be in one of the following states: const ( @@ -863,7 +834,6 @@ const ( inText // inside text ) - // Design note: It is tempting to eliminate extra blanks occurring in // whitespace in this function as it could simplify some // of the blanks logic in the node printing functions. @@ -941,7 +911,6 @@ func (p *trimmer) Write(data []byte) (n int, err os.Error) { return } - // ---------------------------------------------------------------------------- // Public interface @@ -952,14 +921,12 @@ const ( UseSpaces // use spaces instead of tabs for alignment ) - // A Config node controls the output of Fprint. type Config struct { Mode uint // default: 0 Tabwidth int // default: 8 } - // fprint implements Fprint and takes a nodesSizes map for setting up the printer state. func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node interface{}, nodeSizes map[ast.Node]int) (int, os.Error) { // redirect output through a trimmer to eliminate trailing whitespace @@ -1036,7 +1003,6 @@ func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node interface{ return p.written, err } - // Fprint "pretty-prints" an AST node to output and returns the number // of bytes written and an error (if any) for a given configuration cfg. // Position information is interpreted relative to the file set fset. @@ -1047,7 +1013,6 @@ func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node interface{ return cfg.fprint(output, fset, node, make(map[ast.Node]int)) } - // Fprint "pretty-prints" an AST node to output. // It calls Config.Fprint with default settings. // diff --git a/src/pkg/go/printer/printer_test.go b/src/pkg/go/printer/printer_test.go index 090f92af18..ff2d906b56 100644 --- a/src/pkg/go/printer/printer_test.go +++ b/src/pkg/go/printer/printer_test.go @@ -16,19 +16,15 @@ import ( "time" ) - const ( dataDir = "testdata" tabwidth = 8 ) - var update = flag.Bool("update", false, "update golden files") - var fset = token.NewFileSet() - func lineString(text []byte, i int) string { i0 := i for i < len(text) && text[i] != '\n' { @@ -37,7 +33,6 @@ func lineString(text []byte, i int) string { return string(text[i0:i]) } - type checkMode uint const ( @@ -45,7 +40,6 @@ const ( rawFormat ) - func runcheck(t *testing.T, source, golden string, mode checkMode) { // parse source prog, err := parser.ParseFile(fset, source, nil, parser.ParseComments) @@ -109,7 +103,6 @@ func runcheck(t *testing.T, source, golden string, mode checkMode) { } } - func check(t *testing.T, source, golden string, mode checkMode) { // start a timer to produce a time-out signal tc := make(chan int) @@ -135,7 +128,6 @@ func check(t *testing.T, source, golden string, mode checkMode) { } } - type entry struct { source, golden string mode checkMode @@ -154,7 +146,6 @@ var data = []entry{ {"slow.input", "slow.golden", 0}, } - func TestFiles(t *testing.T) { for i, e := range data { source := filepath.Join(dataDir, e.source) @@ -168,7 +159,6 @@ func TestFiles(t *testing.T) { } } - // TestLineComments, using a simple test case, checks that consequtive line // comments are properly terminated with a newline even if the AST position // information is incorrect. diff --git a/src/pkg/go/printer/testdata/comments.golden b/src/pkg/go/printer/testdata/comments.golden index b177c35719..7b332252c4 100644 --- a/src/pkg/go/printer/testdata/comments.golden +++ b/src/pkg/go/printer/testdata/comments.golden @@ -106,7 +106,6 @@ type S3 struct { var x int // x var () - // This comment SHOULD be associated with the next declaration. func f0() { const pi = 3.14 // pi @@ -128,12 +127,10 @@ func f1() { f0() } - func _() { // this comment should be properly indented } - func _(x int) int { if x < 0 { // the tab printed before this comment's // must not affect the remaining lines return -x // this statement should be properly indented @@ -144,7 +141,6 @@ func _(x int) int { return x } - func typeswitch(x interface{}) { switch v := x.(type) { case bool, int, float: @@ -211,7 +207,6 @@ func _() { aligned line */ } - func _() { /* freestanding comment @@ -292,7 +287,6 @@ func _() { aligned line */ } - func _() { /* freestanding comment @@ -409,7 +403,6 @@ func _() { */ } - // Some interesting interspersed comments func _( /* this */ x /* is */ /* an */ int) { } @@ -434,7 +427,6 @@ func _() { _ = []int{0, 1 /* don't introduce a newline after this comment - was issue 1365 */ } } - // Comments immediately adjacent to punctuation (for which the go/printer // may only have estimated position information) must remain after the punctuation. func _() { @@ -466,7 +458,6 @@ func _() { } } - // Line comments with tabs func _() { var finput *bufio.Reader // input file @@ -479,5 +470,4 @@ func _() { var lflag bool // -l - disable line directives } - /* This comment is the last entry in this file. It must be printed and should be followed by a newline */ diff --git a/src/pkg/go/printer/testdata/comments.x b/src/pkg/go/printer/testdata/comments.x index 30a182f490..ae7729286e 100644 --- a/src/pkg/go/printer/testdata/comments.x +++ b/src/pkg/go/printer/testdata/comments.x @@ -2,7 +2,6 @@ // package main - // The SZ struct; it is empty. type SZ struct{} diff --git a/src/pkg/go/printer/testdata/declarations.golden b/src/pkg/go/printer/testdata/declarations.golden index fac72f6512..970533e8cf 100644 --- a/src/pkg/go/printer/testdata/declarations.golden +++ b/src/pkg/go/printer/testdata/declarations.golden @@ -44,7 +44,6 @@ import _ "os" import _ "os" import _ "os" - import _ "fmt" import _ "fmt" import _ "fmt" @@ -116,7 +115,6 @@ import _ "io" var _ int - // printing of constant literals const ( _ = "foobar" @@ -158,7 +156,6 @@ const ( bar` ) - func _() { type _ int type _ *int @@ -203,7 +200,6 @@ func _() { var _ func() interface{} } - // don't lose blank lines in grouped declarations const ( _ int = 0 @@ -220,7 +216,6 @@ const ( _ ) - type ( _ int _ struct{} @@ -231,7 +226,6 @@ type ( _ map[string]int ) - var ( _ int = 0 _ float = 1 @@ -244,7 +238,6 @@ var ( _ bool ) - // don't lose blank lines in this struct type _ struct { String struct { @@ -293,7 +286,6 @@ type _ struct { } } - // no tabs for single or ungrouped decls func _() { const xxxxxx = 0 @@ -426,7 +418,6 @@ var ( filterDelay delayTime // actual filter update interval in minutes; usually filterDelay == filterMin, but filterDelay may back off exponentially ) - // formatting of structs type _ struct{} @@ -494,14 +485,12 @@ type _ struct { r, s float // this line should be indented } - // difficult cases type _ struct { bool // comment text []byte // comment } - // formatting of interfaces type EI interface{} @@ -527,7 +516,6 @@ type _ interface { // this comment must not change indentation gggggggggggg(x, y, z int) // hurray } - // formatting of variable declarations func _() { type day struct { @@ -545,7 +533,6 @@ func _() { ) } - // formatting of multi-line variable declarations var a1, b1, c1 int // all on one line @@ -558,7 +545,6 @@ var ( a4, b4, c4 int // this line should be indented ) - func _() { var privateKey2 = &Block{Type: "RSA PRIVATE KEY", Headers: map[string]string{}, @@ -570,7 +556,6 @@ func _() { } } - func _() { var Universe = Scope{ Names: map[string]*Ident{ @@ -614,7 +599,6 @@ func _() { } } - // alignment of map composite entries var _ = map[int]int{ // small key sizes: always align even if size ratios are large @@ -638,21 +622,18 @@ var _ = map[int]int{ abcde: a, // align with previous line } - func _() { var _ = T{ a, // must introduce trailing comma } } - // formatting of function results func _() func() {} func _() func(int) { return nil } func _() func(int) int { return nil } func _() func(int) func(int) func() { return nil } - // formatting of consecutive single-line functions func _() {} func _() {} @@ -680,7 +661,6 @@ func _() int { return x } - // making function declarations safe for new semicolon rules func _() { /* multi-line func because of comment */ } @@ -689,7 +669,6 @@ func _() { /* multi-line func because block is on multiple lines */ } - // ellipsis parameters func _(...int) func _(...*int) @@ -711,7 +690,6 @@ func _(x ...func(...int)) func _(x ...map[string]int) func _(x ...chan int) - // these parameter lists must remain multi-line since they are multi-line in the source func _(bool, int) { diff --git a/src/pkg/go/printer/testdata/expressions.golden b/src/pkg/go/printer/testdata/expressions.golden index a5e2fdc3b9..d0cf24ad6f 100644 --- a/src/pkg/go/printer/testdata/expressions.golden +++ b/src/pkg/go/printer/testdata/expressions.golden @@ -17,7 +17,6 @@ var ( p *int ) - func _() { // no spaces around simple or parenthesized expressions _ = (a + 0) @@ -115,7 +114,6 @@ func _() { x < y || z > 42 } - func _() { _ = a + b _ = a + b + c @@ -187,7 +185,6 @@ func _() { _ = token(matchType + xlength< 42 } - func _() { _ = a + b _ = a + b + c @@ -187,7 +185,6 @@ func _() { _ = token(matchType + xlength<" @@ -65,16 +59,13 @@ func (e *Error) String() string { return e.Msg } - // An ErrorList is a (possibly sorted) list of Errors. type ErrorList []*Error - // ErrorList implements the sort Interface. func (p ErrorList) Len() int { return len(p) } func (p ErrorList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - func (p ErrorList) Less(i, j int) bool { e := &p[i].Pos f := &p[j].Pos @@ -95,7 +86,6 @@ func (p ErrorList) Less(i, j int) bool { return false } - func (p ErrorList) String() string { switch len(p) { case 0: @@ -106,7 +96,6 @@ func (p ErrorList) String() string { return fmt.Sprintf("%s (and %d more errors)", p[0].String(), len(p)-1) } - // These constants control the construction of the ErrorList // returned by GetErrors. // @@ -116,7 +105,6 @@ const ( NoMultiples // sort error list and leave only the first error per line ) - // GetErrorList returns the list of errors collected by an ErrorVector. // The construction of the ErrorList returned is controlled by the mode // parameter. If there are no errors, the result is nil. @@ -151,7 +139,6 @@ func (h *ErrorVector) GetErrorList(mode int) ErrorList { return list } - // GetError is like GetErrorList, but it returns an os.Error instead // so that a nil result can be assigned to an os.Error variable and // remains nil. @@ -164,13 +151,11 @@ func (h *ErrorVector) GetError(mode int) os.Error { return h.GetErrorList(mode) } - // ErrorVector implements the ErrorHandler interface. func (h *ErrorVector) Error(pos token.Position, msg string) { h.errors.Push(&Error{pos, msg}) } - // PrintError is a utility function that prints a list of errors to w, // one error per line, if the err parameter is an ErrorList. Otherwise // it prints the err string. diff --git a/src/pkg/go/scanner/scanner.go b/src/pkg/go/scanner/scanner.go index 795f0ac15b..7f3dd23732 100644 --- a/src/pkg/go/scanner/scanner.go +++ b/src/pkg/go/scanner/scanner.go @@ -30,7 +30,6 @@ import ( "utf8" ) - // A Scanner holds the scanner's internal state while processing // a given text. It can be allocated as part of another data // structure but must be initialized via Init before use. @@ -54,7 +53,6 @@ type Scanner struct { ErrorCount int // number of errors encountered } - // Read the next Unicode char into S.ch. // S.ch < 0 means end-of-file. // @@ -88,7 +86,6 @@ func (S *Scanner) next() { } } - // The mode parameter to the Init function is a set of flags (or 0). // They control scanner behavior. // @@ -134,7 +131,6 @@ func (S *Scanner) Init(file *token.File, src []byte, err ErrorHandler, mode uint S.next() } - func (S *Scanner) error(offs int, msg string) { if S.err != nil { S.err.Error(S.file.Position(S.file.Pos(offs)), msg) @@ -142,7 +138,6 @@ func (S *Scanner) error(offs int, msg string) { S.ErrorCount++ } - var prefix = []byte("//line ") func (S *Scanner) interpretLineComment(text []byte) { @@ -163,7 +158,6 @@ func (S *Scanner) interpretLineComment(text []byte) { } } - func (S *Scanner) scanComment() { // initial '/' already consumed; S.ch == '/' || S.ch == '*' offs := S.offset - 1 // position of initial '/' @@ -195,7 +189,6 @@ func (S *Scanner) scanComment() { S.error(offs, "comment not terminated") } - func (S *Scanner) findLineEnd() bool { // initial '/' already consumed @@ -240,17 +233,14 @@ func (S *Scanner) findLineEnd() bool { return false } - func isLetter(ch int) bool { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch) } - func isDigit(ch int) bool { return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch) } - func (S *Scanner) scanIdentifier() token.Token { offs := S.offset for isLetter(S.ch) || isDigit(S.ch) { @@ -259,7 +249,6 @@ func (S *Scanner) scanIdentifier() token.Token { return token.Lookup(S.src[offs:S.offset]) } - func digitVal(ch int) int { switch { case '0' <= ch && ch <= '9': @@ -272,14 +261,12 @@ func digitVal(ch int) int { return 16 // larger than any legal digit val } - func (S *Scanner) scanMantissa(base int) { for digitVal(S.ch) < base { S.next() } } - func (S *Scanner) scanNumber(seenDecimalPoint bool) token.Token { // digitVal(S.ch) < 10 tok := token.INT @@ -351,7 +338,6 @@ exit: return tok } - func (S *Scanner) scanEscape(quote int) { offs := S.offset @@ -396,7 +382,6 @@ func (S *Scanner) scanEscape(quote int) { } } - func (S *Scanner) scanChar() { // '\'' opening already consumed offs := S.offset - 1 @@ -423,7 +408,6 @@ func (S *Scanner) scanChar() { } } - func (S *Scanner) scanString() { // '"' opening already consumed offs := S.offset - 1 @@ -443,7 +427,6 @@ func (S *Scanner) scanString() { S.next() } - func (S *Scanner) scanRawString() { // '`' opening already consumed offs := S.offset - 1 @@ -460,14 +443,12 @@ func (S *Scanner) scanRawString() { S.next() } - func (S *Scanner) skipWhitespace() { for S.ch == ' ' || S.ch == '\t' || S.ch == '\n' && !S.insertSemi || S.ch == '\r' { S.next() } } - // Helper functions for scanning multi-byte tokens such as >> += >>= . // Different routines recognize different length tok_i based on matches // of ch_i. If a token ends in '=', the result is tok1 or tok3 @@ -482,7 +463,6 @@ func (S *Scanner) switch2(tok0, tok1 token.Token) token.Token { return tok0 } - func (S *Scanner) switch3(tok0, tok1 token.Token, ch2 int, tok2 token.Token) token.Token { if S.ch == '=' { S.next() @@ -495,7 +475,6 @@ func (S *Scanner) switch3(tok0, tok1 token.Token, ch2 int, tok2 token.Token) tok return tok0 } - func (S *Scanner) switch4(tok0, tok1 token.Token, ch2 int, tok2, tok3 token.Token) token.Token { if S.ch == '=' { S.next() @@ -512,7 +491,6 @@ func (S *Scanner) switch4(tok0, tok1 token.Token, ch2 int, tok2, tok3 token.Toke return tok0 } - // Scan scans the next token and returns the token position, // the token, and the literal string corresponding to the // token. The source end is indicated by token.EOF. diff --git a/src/pkg/go/scanner/scanner_test.go b/src/pkg/go/scanner/scanner_test.go index c096e2725e..52d726245f 100644 --- a/src/pkg/go/scanner/scanner_test.go +++ b/src/pkg/go/scanner/scanner_test.go @@ -12,10 +12,8 @@ import ( "testing" ) - var fset = token.NewFileSet() - const /* class */ ( special = iota literal @@ -23,7 +21,6 @@ const /* class */ ( keyword ) - func tokenclass(tok token.Token) int { switch { case tok.IsLiteral(): @@ -36,14 +33,12 @@ func tokenclass(tok token.Token) int { return special } - type elt struct { tok token.Token lit string class int } - var tokens = [...]elt{ // Special tokens {token.COMMENT, "/* a comment */", special}, @@ -178,7 +173,6 @@ var tokens = [...]elt{ {token.VAR, "var", keyword}, } - const whitespace = " \t \n\n\n" // to separate tokens type testErrorHandler struct { @@ -189,7 +183,6 @@ func (h *testErrorHandler) Error(pos token.Position, msg string) { h.t.Errorf("Error() called (msg = %s)", msg) } - func newlineCount(s string) int { n := 0 for i := 0; i < len(s); i++ { @@ -200,7 +193,6 @@ func newlineCount(s string) int { return n } - func checkPos(t *testing.T, lit string, p token.Pos, expected token.Position) { pos := fset.Position(p) if pos.Filename != expected.Filename { @@ -217,7 +209,6 @@ func checkPos(t *testing.T, lit string, p token.Pos, expected token.Position) { } } - // Verify that calling Scan() provides the correct results. func TestScan(t *testing.T) { // make source @@ -271,7 +262,6 @@ func TestScan(t *testing.T) { } } - func checkSemi(t *testing.T, line string, mode uint) { var S Scanner file := fset.AddFile("TestSemis", fset.Base(), len(line)) @@ -305,7 +295,6 @@ func checkSemi(t *testing.T, line string, mode uint) { } } - var lines = []string{ // # indicates a semicolon present in the source // $ indicates an automatically inserted semicolon @@ -429,7 +418,6 @@ var lines = []string{ "package main$", } - func TestSemis(t *testing.T) { for _, line := range lines { checkSemi(t, line, AllowIllegalChars|InsertSemis) @@ -472,7 +460,6 @@ var winsegments = []segment{ {"\n//line c:\\dir\\File1.go:100\n line100", "c:\\dir\\File1.go", 100}, } - // Verify that comments of the form "//line filename:line" are interpreted correctly. func TestLineComments(t *testing.T) { if runtime.GOOS == "windows" { @@ -500,7 +487,6 @@ func TestLineComments(t *testing.T) { } } - // Verify that initializing the same scanner more then once works correctly. func TestInit(t *testing.T) { var s Scanner @@ -536,7 +522,6 @@ func TestInit(t *testing.T) { } } - func TestIllegalChars(t *testing.T) { var s Scanner @@ -558,7 +543,6 @@ func TestIllegalChars(t *testing.T) { } } - func TestStdErrorHander(t *testing.T) { const src = "@\n" + // illegal character, cause an error "@ @\n" + // two errors on the same line @@ -601,21 +585,18 @@ func TestStdErrorHander(t *testing.T) { } } - type errorCollector struct { cnt int // number of errors encountered msg string // last error message encountered pos token.Position // last error position encountered } - func (h *errorCollector) Error(pos token.Position, msg string) { h.cnt++ h.msg = msg h.pos = pos } - func checkError(t *testing.T, src string, tok token.Token, pos int, err string) { var s Scanner var h errorCollector @@ -643,7 +624,6 @@ func checkError(t *testing.T, src string, tok token.Token, pos int, err string) } } - var errors = []struct { src string tok token.Token @@ -678,7 +658,6 @@ var errors = []struct { {"\"abc\x80def\"", token.STRING, 4, "illegal UTF-8 encoding"}, } - func TestScanErrors(t *testing.T) { for _, e := range errors { checkError(t, e.src, e.tok, e.pos, e.err) diff --git a/src/pkg/go/token/position.go b/src/pkg/go/token/position.go index 23a3cc00fb..c559e19f88 100644 --- a/src/pkg/go/token/position.go +++ b/src/pkg/go/token/position.go @@ -12,7 +12,6 @@ import ( "sync" ) - // Position describes an arbitrary source position // including the file, line, and column location. // A Position is valid if the line number is > 0. @@ -24,11 +23,9 @@ type Position struct { Column int // column number, starting at 1 (character count) } - // IsValid returns true if the position is valid. func (pos *Position) IsValid() bool { return pos.Line > 0 } - // String returns a string in one of several forms: // // file:line:column valid position with file name @@ -50,7 +47,6 @@ func (pos Position) String() string { return s } - // Pos is a compact encoding of a source position within a file set. // It can be converted into a Position for a more convenient, but much // larger, representation. @@ -73,7 +69,6 @@ func (pos Position) String() string { // type Pos int - // The zero value for Pos is NoPos; there is no file and line information // associated with it, and NoPos().IsValid() is false. NoPos is always // smaller than any other Pos value. The corresponding Position value @@ -81,18 +76,15 @@ type Pos int // const NoPos Pos = 0 - // IsValid returns true if the position is valid. func (p Pos) IsValid() bool { return p != NoPos } - func searchFiles(a []*File, x int) int { return sort.Search(len(a), func(i int) bool { return a[i].base > x }) - 1 } - func (s *FileSet) file(p Pos) *File { if f := s.last; f != nil && f.base <= int(p) && int(p) <= f.base+f.size { return f @@ -108,7 +100,6 @@ func (s *FileSet) file(p Pos) *File { return nil } - // File returns the file which contains the position p. // If no such file is found (for instance for p == NoPos), // the result is nil. @@ -122,7 +113,6 @@ func (s *FileSet) File(p Pos) (f *File) { return } - func (f *File) position(p Pos) (pos Position) { offset := int(p) - f.base pos.Offset = offset @@ -130,7 +120,6 @@ func (f *File) position(p Pos) (pos Position) { return } - // Position converts a Pos in the fileset into a general Position. func (s *FileSet) Position(p Pos) (pos Position) { if p != NoPos { @@ -147,14 +136,12 @@ func (s *FileSet) Position(p Pos) (pos Position) { return } - type lineInfo struct { offset int filename string line int } - // AddLineInfo adds alternative file and line number information for // a given file offset. The offset must be larger than the offset for // the previously added alternative line info and smaller than the @@ -171,7 +158,6 @@ func (f *File) AddLineInfo(offset int, filename string, line int) { f.set.mutex.Unlock() } - // A File is a handle for a file belonging to a FileSet. // A File has a name, size, and line offset table. // @@ -186,25 +172,21 @@ type File struct { infos []lineInfo } - // Name returns the file name of file f as registered with AddFile. func (f *File) Name() string { return f.name } - // Base returns the base offset of file f as registered with AddFile. func (f *File) Base() int { return f.base } - // Size returns the size of file f as registered with AddFile. func (f *File) Size() int { return f.size } - // LineCount returns the number of lines in file f. func (f *File) LineCount() int { f.set.mutex.RLock() @@ -213,7 +195,6 @@ func (f *File) LineCount() int { return n } - // AddLine adds the line offset for a new line. // The line offset must be larger than the offset for the previous line // and smaller than the file size; otherwise the line offset is ignored. @@ -226,7 +207,6 @@ func (f *File) AddLine(offset int) { f.set.mutex.Unlock() } - // SetLines sets the line offsets for a file and returns true if successful. // The line offsets are the offsets of the first character of each line; // for instance for the content "ab\nc\n" the line offsets are {0, 3}. @@ -251,7 +231,6 @@ func (f *File) SetLines(lines []int) bool { return true } - // SetLinesForContent sets the line offsets for the given file content. func (f *File) SetLinesForContent(content []byte) { var lines []int @@ -272,7 +251,6 @@ func (f *File) SetLinesForContent(content []byte) { f.set.mutex.Unlock() } - // Pos returns the Pos value for the given file offset; // the offset must be <= f.Size(). // f.Pos(f.Offset(p)) == p. @@ -284,7 +262,6 @@ func (f *File) Pos(offset int) Pos { return Pos(f.base + offset) } - // Offset returns the offset for the given file position p; // p must be a valid Pos value in that file. // f.Offset(f.Pos(offset)) == offset. @@ -296,7 +273,6 @@ func (f *File) Offset(p Pos) int { return int(p) - f.base } - // Line returns the line number for the given file position p; // p must be a Pos value in that file or NoPos. // @@ -305,7 +281,6 @@ func (f *File) Line(p Pos) int { return f.Position(p).Line } - // Position returns the Position value for the given file position p; // p must be a Pos value in that file or NoPos. // @@ -319,7 +294,6 @@ func (f *File) Position(p Pos) (pos Position) { return } - func searchInts(a []int, x int) int { // This function body is a manually inlined version of: // @@ -342,12 +316,10 @@ func searchInts(a []int, x int) int { return i - 1 } - func searchLineInfos(a []lineInfo, x int) int { return sort.Search(len(a), func(i int) bool { return a[i].offset > x }) - 1 } - // info returns the file name, line, and column number for a file offset. func (f *File) info(offset int) (filename string, line, column int) { filename = f.name @@ -367,7 +339,6 @@ func (f *File) info(offset int) (filename string, line, column int) { return } - // A FileSet represents a set of source files. // Methods of file sets are synchronized; multiple goroutines // may invoke them concurrently. @@ -379,7 +350,6 @@ type FileSet struct { last *File // cache of last file looked up } - // NewFileSet creates a new file set. func NewFileSet() *FileSet { s := new(FileSet) @@ -387,7 +357,6 @@ func NewFileSet() *FileSet { return s } - // Base returns the minimum base offset that must be provided to // AddFile when adding the next file. // @@ -399,7 +368,6 @@ func (s *FileSet) Base() int { } - // AddFile adds a new file with a given filename, base offset, and file size // to the file set s and returns the file. Multiple files may have the same // name. The base offset must not be smaller than the FileSet's Base(), and @@ -434,7 +402,6 @@ func (s *FileSet) AddFile(filename string, base, size int) *File { return f } - // Files returns the files added to the file set. func (s *FileSet) Files() <-chan *File { ch := make(chan *File) diff --git a/src/pkg/go/token/position_test.go b/src/pkg/go/token/position_test.go index 979c9b1e8e..30bec59913 100644 --- a/src/pkg/go/token/position_test.go +++ b/src/pkg/go/token/position_test.go @@ -9,7 +9,6 @@ import ( "testing" ) - func checkPos(t *testing.T, msg string, p, q Position) { if p.Filename != q.Filename { t.Errorf("%s: expected filename = %q; got %q", msg, q.Filename, p.Filename) @@ -25,7 +24,6 @@ func checkPos(t *testing.T, msg string, p, q Position) { } } - func TestNoPos(t *testing.T) { if NoPos.IsValid() { t.Errorf("NoPos should not be valid") @@ -36,7 +34,6 @@ func TestNoPos(t *testing.T) { checkPos(t, "fset NoPos", fset.Position(NoPos), Position{}) } - var tests = []struct { filename string source []byte // may be nil @@ -53,7 +50,6 @@ var tests = []struct { {"h", []byte("package p\n\nimport \"fmt\"\n "), 25, []int{0, 10, 11, 24}}, } - func linecol(lines []int, offs int) (int, int) { prevLineOffs := 0 for line, lineOffs := range lines { @@ -65,7 +61,6 @@ func linecol(lines []int, offs int) (int, int) { return len(lines), offs - prevLineOffs + 1 } - func verifyPositions(t *testing.T, fset *FileSet, f *File, lines []int) { for offs := 0; offs < f.Size(); offs++ { p := f.Pos(offs) @@ -80,7 +75,6 @@ func verifyPositions(t *testing.T, fset *FileSet, f *File, lines []int) { } } - func makeTestSource(size int, lines []int) []byte { src := make([]byte, size) for _, offs := range lines { @@ -91,7 +85,6 @@ func makeTestSource(size int, lines []int) []byte { return src } - func TestPositions(t *testing.T) { const delta = 7 // a non-zero base offset increment fset := NewFileSet() @@ -150,7 +143,6 @@ func TestPositions(t *testing.T) { } } - func TestLineInfo(t *testing.T) { fset := NewFileSet() f := fset.AddFile("foo", fset.Base(), 500) @@ -170,7 +162,6 @@ func TestLineInfo(t *testing.T) { } } - func TestFiles(t *testing.T) { fset := NewFileSet() for i, test := range tests { diff --git a/src/pkg/go/token/token.go b/src/pkg/go/token/token.go index c2ec80ae14..557374052c 100644 --- a/src/pkg/go/token/token.go +++ b/src/pkg/go/token/token.go @@ -9,7 +9,6 @@ package token import "strconv" - // Token is the set of lexical tokens of the Go programming language. type Token int @@ -124,7 +123,6 @@ const ( keyword_end ) - var tokens = [...]string{ ILLEGAL: "ILLEGAL", @@ -225,7 +223,6 @@ var tokens = [...]string{ VAR: "var", } - // String returns the string corresponding to the token tok. // For operators, delimiters, and keywords the string is the actual // token character sequence (e.g., for the token ADD, the string is @@ -243,7 +240,6 @@ func (tok Token) String() string { return s } - // A set of constants for precedence-based expression parsing. // Non-operators have lowest precedence, followed by operators // starting with precedence 1 up to unary operators. The highest @@ -256,7 +252,6 @@ const ( HighestPrec = 7 ) - // Precedence returns the operator precedence of the binary // operator op. If op is not a binary operator, the result // is LowestPrecedence. @@ -277,7 +272,6 @@ func (op Token) Precedence() int { return LowestPrec } - var keywords map[string]Token func init() { @@ -287,7 +281,6 @@ func init() { } } - // Lookup maps an identifier to its keyword token or IDENT (if not a keyword). // func Lookup(ident []byte) Token { @@ -299,7 +292,6 @@ func Lookup(ident []byte) Token { return IDENT } - // Predicates // IsLiteral returns true for tokens corresponding to identifiers diff --git a/src/pkg/go/typechecker/scope.go b/src/pkg/go/typechecker/scope.go index a4bee6e696..d73d1a4504 100644 --- a/src/pkg/go/typechecker/scope.go +++ b/src/pkg/go/typechecker/scope.go @@ -12,18 +12,15 @@ package typechecker import "go/ast" - func (tc *typechecker) openScope() *ast.Scope { tc.topScope = ast.NewScope(tc.topScope) return tc.topScope } - func (tc *typechecker) closeScope() { tc.topScope = tc.topScope.Outer } - // declInScope declares an object of a given kind and name in scope and sets the object's Decl and N fields. // It returns the newly allocated object. If an object with the same name already exists in scope, an error // is reported and the object is not inserted. @@ -40,13 +37,11 @@ func (tc *typechecker) declInScope(scope *ast.Scope, kind ast.ObjKind, name *ast return obj } - // decl is the same as declInScope(tc.topScope, ...) func (tc *typechecker) decl(kind ast.ObjKind, name *ast.Ident, decl interface{}, n int) *ast.Object { return tc.declInScope(tc.topScope, kind, name, decl, n) } - // find returns the object with the given name if visible in the current scope hierarchy. // If no such object is found, an error is reported and a bad object is returned instead. func (tc *typechecker) find(name *ast.Ident) (obj *ast.Object) { @@ -61,7 +56,6 @@ func (tc *typechecker) find(name *ast.Ident) (obj *ast.Object) { return } - // findField returns the object with the given name if visible in the type's scope. // If no such object is found, an error is reported and a bad object is returned instead. func (tc *typechecker) findField(typ *Type, name *ast.Ident) (obj *ast.Object) { diff --git a/src/pkg/go/typechecker/type.go b/src/pkg/go/typechecker/type.go index 62b4e9d3e4..1b88eb54b8 100644 --- a/src/pkg/go/typechecker/type.go +++ b/src/pkg/go/typechecker/type.go @@ -6,7 +6,6 @@ package typechecker import "go/ast" - // A Type represents a Go type. type Type struct { Form Form @@ -18,13 +17,11 @@ type Type struct { Expr ast.Expr // corresponding AST expression } - // NewType creates a new type of a given form. func NewType(form Form) *Type { return &Type{Form: form, Scope: ast.NewScope(nil)} } - // Form describes the form of a type. type Form int @@ -45,7 +42,6 @@ const ( Tuple ) - var formStrings = [...]string{ BadType: "badType", Unresolved: "unresolved", @@ -62,10 +58,8 @@ var formStrings = [...]string{ Tuple: "tuple", } - func (form Form) String() string { return formStrings[form] } - // The list of basic type id's. const ( Bool = iota @@ -96,7 +90,6 @@ const ( // TODO(gri) ideal types are missing ) - var BasicTypes = map[uint]string{ Bool: "bool", Byte: "byte", diff --git a/src/pkg/go/typechecker/typechecker.go b/src/pkg/go/typechecker/typechecker.go index b151f5834d..24480165bd 100644 --- a/src/pkg/go/typechecker/typechecker.go +++ b/src/pkg/go/typechecker/typechecker.go @@ -17,19 +17,16 @@ import ( "os" ) - // TODO(gri) don't report errors for objects/types that are marked as bad. const debug = true // set for debugging output - // An importer takes an import path and returns the data describing the // respective package's exported interface. The data format is TBD. // type Importer func(path string) ([]byte, os.Error) - // CheckPackage typechecks a package and augments the AST by setting // *ast.Object, *ast.Type, and *ast.Scope fields accordingly. If an // importer is provided, it is used to handle imports, otherwise they @@ -46,7 +43,6 @@ func CheckPackage(fset *token.FileSet, pkg *ast.Package, importer Importer) os.E return tc.GetError(scanner.Sorted) } - // CheckFile typechecks a single file, but otherwise behaves like // CheckPackage. If the complete package consists of more than just // one file, the file may not typecheck without errors. @@ -57,7 +53,6 @@ func CheckFile(fset *token.FileSet, file *ast.File, importer Importer) os.Error return CheckPackage(fset, pkg, importer) } - // ---------------------------------------------------------------------------- // Typechecker state @@ -71,19 +66,16 @@ type typechecker struct { iota int // current value of iota } - func (tc *typechecker) Errorf(pos token.Pos, format string, args ...interface{}) { tc.Error(tc.fset.Position(pos), fmt.Sprintf(format, args...)) } - func assert(pred bool) { if !pred { panic("internal error") } } - /* Typechecking is done in several phases: @@ -158,7 +150,6 @@ func (tc *typechecker) checkPackage(pkg *ast.Package) { pkg.Scope = tc.topScope } - func (tc *typechecker) declGlobal(global ast.Decl) { switch d := global.(type) { case *ast.BadDecl: @@ -218,7 +209,6 @@ func (tc *typechecker) declGlobal(global ast.Decl) { } } - // If x is of the form *T, deref returns T, otherwise it returns x. func deref(x ast.Expr) ast.Expr { if p, isPtr := x.(*ast.StarExpr); isPtr { @@ -227,7 +217,6 @@ func deref(x ast.Expr) ast.Expr { return x } - func (tc *typechecker) bindMethod(method *ast.FuncDecl) { // a method is declared in the receiver base type's scope var scope *ast.Scope @@ -259,7 +248,6 @@ func (tc *typechecker) bindMethod(method *ast.FuncDecl) { tc.declInScope(scope, ast.Fun, method.Name, method, 0) } - func (tc *typechecker) resolve(obj *ast.Object) { // check for declaration cycles if tc.cyclemap[obj] { @@ -318,7 +306,6 @@ func (tc *typechecker) resolve(obj *ast.Object) { } } - func (tc *typechecker) checkBlock(body []ast.Stmt, ftype *Type) { tc.openScope() defer tc.closeScope() @@ -338,7 +325,6 @@ func (tc *typechecker) checkBlock(body []ast.Stmt, ftype *Type) { } } - // ---------------------------------------------------------------------------- // Types @@ -350,7 +336,6 @@ func unparen(x ast.Expr) ast.Expr { return x } - func (tc *typechecker) declFields(scope *ast.Scope, fields *ast.FieldList, ref bool) (n uint) { if fields != nil { for _, f := range fields.List { @@ -365,7 +350,6 @@ func (tc *typechecker) declFields(scope *ast.Scope, fields *ast.FieldList, ref b return n } - func (tc *typechecker) declSignature(typ *Type, recv, params, results *ast.FieldList) { assert((typ.Form == Method) == (recv != nil)) typ.Params = ast.NewScope(nil) @@ -374,7 +358,6 @@ func (tc *typechecker) declSignature(typ *Type, recv, params, results *ast.Field typ.N = tc.declFields(typ.Params, results, true) } - func (tc *typechecker) typeFor(def *Type, x ast.Expr, ref bool) (typ *Type) { x = unparen(x) @@ -472,17 +455,14 @@ func (tc *typechecker) typeFor(def *Type, x ast.Expr, ref bool) (typ *Type) { return } - // ---------------------------------------------------------------------------- // TODO(gri) implement these place holders func (tc *typechecker) declConst(*ast.Object) { } - func (tc *typechecker) declVar(*ast.Object) { } - func (tc *typechecker) checkStmt(ast.Stmt) { } diff --git a/src/pkg/go/typechecker/typechecker_test.go b/src/pkg/go/typechecker/typechecker_test.go index d16e069218..4bad4499a4 100644 --- a/src/pkg/go/typechecker/typechecker_test.go +++ b/src/pkg/go/typechecker/typechecker_test.go @@ -41,7 +41,6 @@ import ( "testing" ) - const testDir = "./testdata" // location of test packages var fset = token.NewFileSet() @@ -51,7 +50,6 @@ var ( trace = flag.Bool("trace", false, "print package names") ) - // ERROR comments must be of the form /* ERROR "rx" */ and rx is // a regular expression that matches the expected error message. var errRx = regexp.MustCompile(`^/\* *ERROR *"([^"]*)" *\*/$`) @@ -91,12 +89,10 @@ func expectedErrors(t *testing.T, pkg *ast.Package) (list scanner.ErrorList) { return } - func testFilter(f *os.FileInfo) bool { return strings.HasSuffix(f.Name, ".src") && f.Name[0] != '.' } - func checkError(t *testing.T, expected, found *scanner.Error) { rx, err := regexp.Compile(expected.Msg) if err != nil { @@ -120,7 +116,6 @@ func checkError(t *testing.T, expected, found *scanner.Error) { } } - func TestTypeCheck(t *testing.T) { flag.Parse() pkgRx, err := regexp.Compile(*pkgPat) diff --git a/src/pkg/go/typechecker/universe.go b/src/pkg/go/typechecker/universe.go index abc8bbbd49..81c14a05e5 100644 --- a/src/pkg/go/typechecker/universe.go +++ b/src/pkg/go/typechecker/universe.go @@ -11,7 +11,6 @@ import "go/ast" // The Universe scope contains all predeclared identifiers. var Universe *ast.Scope - func def(obj *ast.Object) { alt := Universe.Insert(obj) if alt != nil { @@ -19,7 +18,6 @@ func def(obj *ast.Object) { } } - func init() { Universe = ast.NewScope(nil) diff --git a/src/pkg/go/types/check.go b/src/pkg/go/types/check.go index 02d6629264..87e3e93da7 100644 --- a/src/pkg/go/types/check.go +++ b/src/pkg/go/types/check.go @@ -15,24 +15,20 @@ import ( "strconv" ) - const debug = false - type checker struct { fset *token.FileSet scanner.ErrorVector types map[ast.Expr]Type } - func (c *checker) errorf(pos token.Pos, format string, args ...interface{}) string { msg := fmt.Sprintf(format, args...) c.Error(c.fset.Position(pos), msg) return msg } - // collectFields collects struct fields tok = token.STRUCT), interface methods // (tok = token.INTERFACE), and function arguments/results (tok = token.FUNC). func (c *checker) collectFields(tok token.Token, list *ast.FieldList, cycleOk bool) (fields ObjList, tags []string, isVariadic bool) { @@ -87,7 +83,6 @@ func (c *checker) collectFields(tok token.Token, list *ast.FieldList, cycleOk bo return } - // makeType makes a new type for an AST type specification x or returns // the type referred to by a type name x. If cycleOk is set, a type may // refer to itself directly or indirectly; otherwise cycles are errors. @@ -183,7 +178,6 @@ func (c *checker) makeType(x ast.Expr, cycleOk bool) (typ Type) { panic(fmt.Sprintf("unreachable (%T)", x)) } - // checkObj type checks an object. func (c *checker) checkObj(obj *ast.Object, ref bool) { if obj.Type != nil { @@ -214,7 +208,6 @@ func (c *checker) checkObj(obj *ast.Object, ref bool) { } } - // Check typechecks a package. // It augments the AST by assigning types to all ast.Objects and returns a map // of types for all expression nodes in statements, and a scanner.ErrorList if diff --git a/src/pkg/go/types/check_test.go b/src/pkg/go/types/check_test.go index 6ecb12b1ee..8be653fcb6 100644 --- a/src/pkg/go/types/check_test.go +++ b/src/pkg/go/types/check_test.go @@ -34,7 +34,6 @@ import ( "testing" ) - // The test filenames do not end in .go so that they are invisible // to gofmt since they contain comments that must not change their // positions relative to surrounding tokens. @@ -46,10 +45,8 @@ var tests = []struct { {"test0", []string{"testdata/test0.src"}}, } - var fset = token.NewFileSet() - // TODO(gri) This functionality should be in token.Fileset. func getFile(filename string) *token.File { for f := range fset.Files() { @@ -60,7 +57,6 @@ func getFile(filename string) *token.File { return nil } - // TODO(gri) This functionality should be in token.Fileset. func getPos(filename string, offset int) token.Pos { if f := getFile(filename); f != nil { @@ -69,7 +65,6 @@ func getPos(filename string, offset int) token.Pos { return token.NoPos } - // TODO(gri) Need to revisit parser interface. We should be able to use parser.ParseFiles // or a similar function instead. func parseFiles(t *testing.T, testname string, filenames []string) (map[string]*ast.File, os.Error) { @@ -95,7 +90,6 @@ func parseFiles(t *testing.T, testname string, filenames []string) (map[string]* return files, errors } - // ERROR comments must be of the form /* ERROR "rx" */ and rx is // a regular expression that matches the expected error message. // @@ -138,7 +132,6 @@ func expectedErrors(t *testing.T, testname string, files map[string]*ast.File) m return errors } - func eliminate(t *testing.T, expected map[token.Pos]string, errors os.Error) { if errors == nil { return @@ -172,7 +165,6 @@ func eliminate(t *testing.T, expected map[token.Pos]string, errors os.Error) { } } - func check(t *testing.T, testname string, testfiles []string) { // TODO(gri) Eventually all these different phases should be // subsumed into a single function call that takes @@ -206,7 +198,6 @@ func check(t *testing.T, testname string, testfiles []string) { } } - func TestCheck(t *testing.T) { // For easy debugging w/o changing the testing code, // if there is a local test file, only test that file. diff --git a/src/pkg/go/types/const.go b/src/pkg/go/types/const.go index 6fdc22f6b3..1ef95d9f95 100644 --- a/src/pkg/go/types/const.go +++ b/src/pkg/go/types/const.go @@ -12,7 +12,6 @@ import ( "strconv" ) - // TODO(gri) Consider changing the API so Const is an interface // and operations on consts don't have to type switch. @@ -28,20 +27,17 @@ type Const struct { val interface{} } - // Representation of complex values. type cmplx struct { re, im *big.Rat } - func assert(cond bool) { if !cond { panic("go/types internal error: assertion failed") } } - // MakeConst makes an ideal constant from a literal // token and the corresponding literal string. func MakeConst(tok token.Token, lit string) Const { @@ -75,14 +71,12 @@ func MakeConst(tok token.Token, lit string) Const { panic("unreachable") } - // MakeZero returns the zero constant for the given type. func MakeZero(typ *Type) Const { // TODO(gri) fix this return Const{0} } - // Match attempts to match the internal constant representations of x and y. // If the attempt is successful, the result is the values of x and y, // if necessary converted to have the same internal representation; otherwise @@ -132,7 +126,6 @@ func (x Const) Match(y Const) (u, v Const) { return } - // Convert attempts to convert the constant x to a given type. // If the attempt is successful, the result is the new constant; // otherwise the result is invalid. @@ -148,7 +141,6 @@ func (x Const) Convert(typ *Type) Const { return x } - func (x Const) String() string { switch x := x.val.(type) { case bool: @@ -169,12 +161,10 @@ func (x Const) String() string { panic("unreachable") } - func (x Const) UnaryOp(op token.Token) Const { panic("unimplemented") } - func (x Const) BinaryOp(op token.Token, y Const) Const { var z interface{} switch x := x.val.(type) { @@ -194,7 +184,6 @@ func (x Const) BinaryOp(op token.Token, y Const) Const { return Const{z} } - func binaryBoolOp(x bool, op token.Token, y bool) interface{} { switch op { case token.EQL: @@ -205,7 +194,6 @@ func binaryBoolOp(x bool, op token.Token, y bool) interface{} { panic("unreachable") } - func binaryIntOp(x *big.Int, op token.Token, y *big.Int) interface{} { var z big.Int switch op { @@ -247,7 +235,6 @@ func binaryIntOp(x *big.Int, op token.Token, y *big.Int) interface{} { panic("unreachable") } - func binaryFloatOp(x *big.Rat, op token.Token, y *big.Rat) interface{} { var z big.Rat switch op { @@ -275,7 +262,6 @@ func binaryFloatOp(x *big.Rat, op token.Token, y *big.Rat) interface{} { panic("unreachable") } - func binaryCmplxOp(x cmplx, op token.Token, y cmplx) interface{} { a, b := x.re, x.im c, d := y.re, y.im @@ -325,7 +311,6 @@ func binaryCmplxOp(x cmplx, op token.Token, y cmplx) interface{} { panic("unreachable") } - func binaryStringOp(x string, op token.Token, y string) interface{} { switch op { case token.ADD: diff --git a/src/pkg/go/types/exportdata.go b/src/pkg/go/types/exportdata.go index f68133761a..383520320f 100644 --- a/src/pkg/go/types/exportdata.go +++ b/src/pkg/go/types/exportdata.go @@ -15,7 +15,6 @@ import ( "strings" ) - func readGopackHeader(buf *bufio.Reader) (name string, size int, err os.Error) { // See $GOROOT/include/ar.h. hdr := make([]byte, 64+12+6+6+8+10+2) @@ -36,13 +35,11 @@ func readGopackHeader(buf *bufio.Reader) (name string, size int, err os.Error) { return } - type dataReader struct { *bufio.Reader io.Closer } - // ExportData returns a readCloser positioned at the beginning of the // export data section of the given object/archive file, or an error. // It is the caller's responsibility to close the readCloser. diff --git a/src/pkg/go/types/gcimporter.go b/src/pkg/go/types/gcimporter.go index aa0bb91605..6ab1806b64 100644 --- a/src/pkg/go/types/gcimporter.go +++ b/src/pkg/go/types/gcimporter.go @@ -20,7 +20,6 @@ import ( "strconv" ) - const trace = false // set to true for debugging var ( @@ -28,7 +27,6 @@ var ( pkgExts = [...]string{".a", ".5", ".6", ".8"} ) - // findPkg returns the filename and package id for an import path. // If no file was found, an empty filename is returned. func findPkg(path string) (filename, id string) { @@ -69,7 +67,6 @@ func findPkg(path string) (filename, id string) { return } - // gcParser parses the exports inside a gc compiler-produced // object/archive file and populates its scope with the results. type gcParser struct { @@ -80,7 +77,6 @@ type gcParser struct { imports map[string]*ast.Object // package id -> package object } - func (p *gcParser) init(filename, id string, src io.Reader, imports map[string]*ast.Object) { p.scanner.Init(src) p.scanner.Error = func(_ *scanner.Scanner, msg string) { p.error(msg) } @@ -92,7 +88,6 @@ func (p *gcParser) init(filename, id string, src io.Reader, imports map[string]* p.imports = imports } - func (p *gcParser) next() { p.tok = p.scanner.Scan() switch p.tok { @@ -106,7 +101,6 @@ func (p *gcParser) next() { } } - // GcImporter implements the ast.Importer signature. func GcImporter(imports map[string]*ast.Object, path string) (pkg *ast.Object, err os.Error) { if path == "unsafe" { @@ -148,7 +142,6 @@ func GcImporter(imports map[string]*ast.Object, path string) (pkg *ast.Object, e return } - // ---------------------------------------------------------------------------- // Error handling @@ -158,12 +151,10 @@ type importError struct { err os.Error } - func (e importError) String() string { return fmt.Sprintf("import error %s (byte offset = %d): %s", e.pos, e.pos.Offset, e.err) } - func (p *gcParser) error(err interface{}) { if s, ok := err.(string); ok { err = os.NewError(s) @@ -172,12 +163,10 @@ func (p *gcParser) error(err interface{}) { panic(importError{p.scanner.Pos(), err.(os.Error)}) } - func (p *gcParser) errorf(format string, args ...interface{}) { p.error(fmt.Sprintf(format, args...)) } - func (p *gcParser) expect(tok int) string { lit := p.lit if p.tok != tok { @@ -187,7 +176,6 @@ func (p *gcParser) expect(tok int) string { return lit } - func (p *gcParser) expectSpecial(tok string) { sep := 'x' // not white space i := 0 @@ -201,7 +189,6 @@ func (p *gcParser) expectSpecial(tok string) { } } - func (p *gcParser) expectKeyword(keyword string) { lit := p.expect(scanner.Ident) if lit != keyword { @@ -209,7 +196,6 @@ func (p *gcParser) expectKeyword(keyword string) { } } - // ---------------------------------------------------------------------------- // Import declarations @@ -242,7 +228,6 @@ func (p *gcParser) parsePkgId() *ast.Object { return pkg } - // dotIdentifier = ( ident | '·' ) { ident | int | '·' } . func (p *gcParser) parseDotIdent() string { ident := "" @@ -260,7 +245,6 @@ func (p *gcParser) parseDotIdent() string { return ident } - // ExportedName = ImportPath "." dotIdentifier . // func (p *gcParser) parseExportedName(kind ast.ObjKind) *ast.Object { @@ -295,7 +279,6 @@ func (p *gcParser) parseExportedName(kind ast.ObjKind) *ast.Object { return obj } - // ---------------------------------------------------------------------------- // Types @@ -309,7 +292,6 @@ func (p *gcParser) parseBasicType() Type { return obj.Type.(Type) } - // ArrayType = "[" int_lit "]" Type . // func (p *gcParser) parseArrayType() Type { @@ -324,7 +306,6 @@ func (p *gcParser) parseArrayType() Type { return &Array{Len: n, Elt: elt} } - // MapType = "map" "[" Type "]" Type . // func (p *gcParser) parseMapType() Type { @@ -336,7 +317,6 @@ func (p *gcParser) parseMapType() Type { return &Map{Key: key, Elt: elt} } - // Name = identifier | "?" . // func (p *gcParser) parseName() (name string) { @@ -353,7 +333,6 @@ func (p *gcParser) parseName() (name string) { return } - // Field = Name Type [ ":" string_lit ] . // func (p *gcParser) parseField() (fld *ast.Object, tag string) { @@ -374,7 +353,6 @@ func (p *gcParser) parseField() (fld *ast.Object, tag string) { return } - // StructType = "struct" "{" [ FieldList ] "}" . // FieldList = Field { ";" Field } . // @@ -402,7 +380,6 @@ func (p *gcParser) parseStructType() Type { return &Struct{Fields: fields, Tags: tags} } - // Parameter = ( identifier | "?" ) [ "..." ] Type [ ":" string_lit ] . // func (p *gcParser) parseParameter() (par *ast.Object, isVariadic bool) { @@ -425,7 +402,6 @@ func (p *gcParser) parseParameter() (par *ast.Object, isVariadic bool) { return } - // Parameters = "(" [ ParameterList ] ")" . // ParameterList = { Parameter "," } Parameter . // @@ -454,7 +430,6 @@ func (p *gcParser) parseParameters() (list []*ast.Object, isVariadic bool) { return } - // Signature = Parameters [ Result ] . // Result = Type | Parameters . // @@ -481,7 +456,6 @@ func (p *gcParser) parseSignature() *Func { return &Func{Params: params, Results: results, IsVariadic: isVariadic} } - // MethodSpec = identifier Signature . // func (p *gcParser) parseMethodSpec() *ast.Object { @@ -499,7 +473,6 @@ func (p *gcParser) parseMethodSpec() *ast.Object { return ast.NewObj(ast.Fun, "_") } - // InterfaceType = "interface" "{" [ MethodList ] "}" . // MethodList = MethodSpec { ";" MethodSpec } . // @@ -526,7 +499,6 @@ func (p *gcParser) parseInterfaceType() Type { return &Interface{Methods: methods} } - // ChanType = ( "chan" [ "<-" ] | "<-" "chan" ) Type . // func (p *gcParser) parseChanType() Type { @@ -546,7 +518,6 @@ func (p *gcParser) parseChanType() Type { return &Chan{Dir: dir, Elt: elt} } - // Type = // BasicType | TypeName | ArrayType | SliceType | StructType | // PointerType | FuncType | InterfaceType | MapType | ChanType | @@ -604,7 +575,6 @@ func (p *gcParser) parseType() Type { return nil } - // ---------------------------------------------------------------------------- // Declarations @@ -621,7 +591,6 @@ func (p *gcParser) parseImportDecl() { pkg.Name = name } - // int_lit = [ "+" | "-" ] { "0" ... "9" } . // func (p *gcParser) parseInt() (sign, val string) { @@ -636,7 +605,6 @@ func (p *gcParser) parseInt() (sign, val string) { return } - // number = int_lit [ "p" int_lit ] . // func (p *gcParser) parseNumber() Const { @@ -667,7 +635,6 @@ func (p *gcParser) parseNumber() Const { return Const{mant} } - // ConstDecl = "const" ExportedName [ Type ] "=" Literal . // Literal = bool_lit | int_lit | float_lit | complex_lit | string_lit . // bool_lit = "true" | "false" . @@ -722,7 +689,6 @@ func (p *gcParser) parseConstDecl() { obj.Data = x } - // TypeDecl = "type" ExportedName Type . // func (p *gcParser) parseTypeDecl() { @@ -742,7 +708,6 @@ func (p *gcParser) parseTypeDecl() { } } - // VarDecl = "var" ExportedName Type . // func (p *gcParser) parseVarDecl() { @@ -751,7 +716,6 @@ func (p *gcParser) parseVarDecl() { obj.Type = p.parseType() } - // FuncDecl = "func" ExportedName Signature . // func (p *gcParser) parseFuncDecl() { @@ -760,7 +724,6 @@ func (p *gcParser) parseFuncDecl() { obj.Type = p.parseSignature() } - // MethodDecl = "func" Receiver identifier Signature . // Receiver = "(" ( identifier | "?" ) [ "*" ] ExportedName ")" . // @@ -773,7 +736,6 @@ func (p *gcParser) parseMethodDecl() { p.parseSignature() } - // Decl = [ ImportDecl | ConstDecl | TypeDecl | VarDecl | FuncDecl | MethodDecl ] "\n" . // func (p *gcParser) parseDecl() { @@ -797,7 +759,6 @@ func (p *gcParser) parseDecl() { p.expect('\n') } - // ---------------------------------------------------------------------------- // Export diff --git a/src/pkg/go/types/gcimporter_test.go b/src/pkg/go/types/gcimporter_test.go index 10240add53..ec87f5d514 100644 --- a/src/pkg/go/types/gcimporter_test.go +++ b/src/pkg/go/types/gcimporter_test.go @@ -15,7 +15,6 @@ import ( "time" ) - var gcName, gcPath string // compiler name and path func init() { @@ -35,7 +34,6 @@ func init() { gcPath, _ = exec.LookPath(gcName) } - func compile(t *testing.T, dirname, filename string) { cmd := exec.Command(gcPath, filename) cmd.Dir = dirname @@ -47,7 +45,6 @@ func compile(t *testing.T, dirname, filename string) { t.Logf("%s", string(out)) } - // Use the same global imports map for all tests. The effect is // as if all tested packages were imported into a single package. var imports = make(map[string]*ast.Object) @@ -61,7 +58,6 @@ func testPath(t *testing.T, path string) bool { return true } - const maxTime = 3e9 // maximum allotted testing time in ns func testDir(t *testing.T, dir string, endTime int64) (nimports int) { @@ -93,7 +89,6 @@ func testDir(t *testing.T, dir string, endTime int64) (nimports int) { return } - func TestGcImport(t *testing.T) { compile(t, "testdata", "exports.go") diff --git a/src/pkg/go/types/testdata/exports.go b/src/pkg/go/types/testdata/exports.go index 035a13fb70..ed63bf9ade 100644 --- a/src/pkg/go/types/testdata/exports.go +++ b/src/pkg/go/types/testdata/exports.go @@ -11,7 +11,6 @@ import ( "go/ast" ) - const ( C0 int = 0 C1 = 3.14159265 @@ -23,7 +22,6 @@ const ( C7 = `bar\n` ) - type ( T1 int T2 [10]int @@ -72,18 +70,15 @@ type ( T28 func(T28) T28 ) - var ( V0 int V1 = -991.0 ) - func F1() {} func F2(x int) {} func F3() int { return 0 } func F4() float32 { return 0 } func F5(a, b, c int, u, v, w struct{ x, y T1 }, more ...interface{}) (p, q, r chan<- T10) - func (p *T1) M1() diff --git a/src/pkg/go/types/types.go b/src/pkg/go/types/types.go index 10b0145b89..3aa896892e 100644 --- a/src/pkg/go/types/types.go +++ b/src/pkg/go/types/types.go @@ -12,34 +12,29 @@ import ( "sort" ) - // All types implement the Type interface. type Type interface { isType() } - // All concrete types embed ImplementsType which // ensures that all types implement the Type interface. type ImplementsType struct{} func (t *ImplementsType) isType() {} - // A Bad type is a non-nil placeholder type when we don't know a type. type Bad struct { ImplementsType Msg string // for better error reporting/debugging } - // A Basic represents a (unnamed) basic type. type Basic struct { ImplementsType // TODO(gri) need a field specifying the exact basic type } - // An Array represents an array type [Len]Elt. type Array struct { ImplementsType @@ -47,14 +42,12 @@ type Array struct { Elt Type } - // A Slice represents a slice type []Elt. type Slice struct { ImplementsType Elt Type } - // A Struct represents a struct type struct{...}. // Anonymous fields are represented by objects with empty names. type Struct struct { @@ -67,14 +60,12 @@ type Struct struct { // - there is no scope for fast lookup (but the parser creates one) } - // A Pointer represents a pointer type *Base. type Pointer struct { ImplementsType Base Type } - // A Func represents a function type func(...) (...). // Unnamed parameters are represented by objects with empty names. type Func struct { @@ -85,21 +76,18 @@ type Func struct { IsVariadic bool // true if the last parameter's type is of the form ...T } - // An Interface represents an interface type interface{...}. type Interface struct { ImplementsType Methods ObjList // interface methods sorted by name; or nil } - // A Map represents a map type map[Key]Elt. type Map struct { ImplementsType Key, Elt Type } - // A Chan represents a channel type chan Elt, <-chan Elt, or chan<-Elt. type Chan struct { ImplementsType @@ -107,7 +95,6 @@ type Chan struct { Elt Type } - // A Name represents a named type as declared in a type declaration. type Name struct { ImplementsType @@ -116,7 +103,6 @@ type Name struct { // TODO(gri) need to remember fields and methods. } - // If typ is a pointer type, Deref returns the pointer's base type; // otherwise it returns typ. func Deref(typ Type) Type { @@ -126,7 +112,6 @@ func Deref(typ Type) Type { return typ } - // Underlying returns the underlying type of a type. func Underlying(typ Type) Type { if typ, ok := typ.(*Name); ok { @@ -141,7 +126,6 @@ func Underlying(typ Type) Type { return typ } - // An ObjList represents an ordered (in some fashion) list of objects. type ObjList []*ast.Object @@ -153,7 +137,6 @@ func (list ObjList) Swap(i, j int) { list[i], list[j] = list[j], list[i] } // Sort sorts an object list by object name. func (list ObjList) Sort() { sort.Sort(list) } - // identicalTypes returns true if both lists a and b have the // same length and corresponding objects have identical types. func identicalTypes(a, b ObjList) bool { @@ -169,7 +152,6 @@ func identicalTypes(a, b ObjList) bool { return false } - // Identical returns true if two types are identical. func Identical(x, y Type) bool { if x == y { diff --git a/src/pkg/go/types/universe.go b/src/pkg/go/types/universe.go index 96005cff5e..6ae88e5f9c 100644 --- a/src/pkg/go/types/universe.go +++ b/src/pkg/go/types/universe.go @@ -9,14 +9,12 @@ package types import "go/ast" - var ( scope *ast.Scope // current scope to use for initialization Universe *ast.Scope Unsafe *ast.Object // package unsafe ) - func define(kind ast.ObjKind, name string) *ast.Object { obj := ast.NewObj(kind, name) if scope.Insert(obj) != nil { @@ -25,7 +23,6 @@ func define(kind ast.ObjKind, name string) *ast.Object { return obj } - func defType(name string) *Name { obj := define(ast.Typ, name) typ := &Name{Underlying: &Basic{}, Obj: obj} @@ -33,19 +30,16 @@ func defType(name string) *Name { return typ } - func defConst(name string) { obj := define(ast.Con, name) _ = obj // TODO(gri) fill in other properties } - func defFun(name string) { obj := define(ast.Fun, name) _ = obj // TODO(gri) fill in other properties } - var ( Bool, Int, @@ -54,7 +48,6 @@ var ( String *Name ) - func init() { scope = ast.NewScope(nil) Universe = scope diff --git a/src/pkg/gob/codec_test.go b/src/pkg/gob/codec_test.go index da8e59c742..03fec261a1 100644 --- a/src/pkg/gob/codec_test.go +++ b/src/pkg/gob/codec_test.go @@ -782,7 +782,6 @@ func TestOverflow(t *testing.T) { } } - func TestNesting(t *testing.T) { type RT struct { A string @@ -980,7 +979,6 @@ func TestIgnoredFields(t *testing.T) { } } - func TestBadRecursiveType(t *testing.T) { type Rec ***Rec var rec Rec diff --git a/src/pkg/gob/debug.go b/src/pkg/gob/debug.go index 79aee7788b..ce8a6ff5e5 100644 --- a/src/pkg/gob/debug.go +++ b/src/pkg/gob/debug.go @@ -416,7 +416,6 @@ func (deb *debugger) typeDefinition(indent tab, id typeId) { deb.wireType[id] = wire } - // Value: // SingletonValue | StructValue func (deb *debugger) value(indent tab, id typeId) { @@ -463,7 +462,6 @@ func (deb *debugger) nilInterfaceValue(indent tab) int { return 0 } - // NonNilInterfaceValue: // ConcreteTypeName TypeSequence InterfaceContents // ConcreteTypeName: @@ -603,7 +601,6 @@ func (deb *debugger) printBuiltin(indent tab, id typeId) { } } - // ArrayValue: // uint(n) FieldValue*n func (deb *debugger) arrayValue(indent tab, wire *wireType) { diff --git a/src/pkg/http/cgi/host_test.go b/src/pkg/http/cgi/host_test.go index 250324a512..98a7ce5f26 100644 --- a/src/pkg/http/cgi/host_test.go +++ b/src/pkg/http/cgi/host_test.go @@ -85,7 +85,6 @@ func skipTest(t *testing.T) bool { return false } - func TestCGIBasicGet(t *testing.T) { if skipTest(t) { return @@ -375,7 +374,6 @@ func TestCopyError(t *testing.T) { } } - func TestDirUnix(t *testing.T) { if skipTest(t) || runtime.GOOS == "windows" { return diff --git a/src/pkg/http/client.go b/src/pkg/http/client.go index 4f63b44f26..6ea7dee03f 100644 --- a/src/pkg/http/client.go +++ b/src/pkg/http/client.go @@ -85,7 +85,6 @@ func (c *Client) Do(req *Request) (resp *Response, err os.Error) { return send(req, c.Transport) } - // send issues an HTTP request. Caller should close resp.Body when done reading from it. func send(req *Request, t RoundTripper) (resp *Response, err os.Error) { if t == nil { diff --git a/src/pkg/http/triv.go b/src/pkg/http/triv.go index 54b12333f5..a8fd99aa4b 100644 --- a/src/pkg/http/triv.go +++ b/src/pkg/http/triv.go @@ -16,7 +16,6 @@ import ( "strconv" ) - // hello world, the web server var helloRequests = expvar.NewInt("hello-requests") @@ -126,7 +125,6 @@ func Logger(w http.ResponseWriter, req *http.Request) { w.Write([]byte("oops")) } - var webroot = flag.String("root", "/home/rsc", "web root directory") func main() { diff --git a/src/pkg/http/url.go b/src/pkg/http/url.go index e934b27c4d..b38585ac20 100644 --- a/src/pkg/http/url.go +++ b/src/pkg/http/url.go @@ -56,7 +56,6 @@ const ( encodeOpaque ) - type URLEscapeError string func (e URLEscapeError) String() string { @@ -114,7 +113,6 @@ func shouldEscape(c byte, mode encoding) bool { return true } - // URLUnescape unescapes a string in ``URL encoded'' form, // converting %AB into the byte 0xAB and '+' into ' ' (space). // It returns an error if any % is not followed diff --git a/src/pkg/index/suffixarray/qsufsort.go b/src/pkg/index/suffixarray/qsufsort.go index 9751b5c766..30c1104428 100644 --- a/src/pkg/index/suffixarray/qsufsort.go +++ b/src/pkg/index/suffixarray/qsufsort.go @@ -72,7 +72,6 @@ func qsufsort(data []byte) []int { return sa } - func sortedByFirstByte(data []byte) []int { // total byte counts var count [256]int @@ -93,7 +92,6 @@ func sortedByFirstByte(data []byte) []int { return sa } - func initGroups(sa []int, data []byte) []int { // label contiguous same-letter groups with the same group number inv := make([]int, len(data)) @@ -133,7 +131,6 @@ func initGroups(sa []int, data []byte) []int { return inv } - type suffixSortable struct { sa []int inv []int @@ -144,7 +141,6 @@ func (x *suffixSortable) Len() int { return len(x.sa) } func (x *suffixSortable) Less(i, j int) bool { return x.inv[x.sa[i]+x.h] < x.inv[x.sa[j]+x.h] } func (x *suffixSortable) Swap(i, j int) { x.sa[i], x.sa[j] = x.sa[j], x.sa[i] } - func (x *suffixSortable) updateGroups(offset int) { bounds := make([]int, 0, 4) group := x.inv[x.sa[0]+x.h] diff --git a/src/pkg/index/suffixarray/suffixarray.go b/src/pkg/index/suffixarray/suffixarray.go index 9d4e93217b..82e98d2ef5 100644 --- a/src/pkg/index/suffixarray/suffixarray.go +++ b/src/pkg/index/suffixarray/suffixarray.go @@ -22,21 +22,18 @@ import ( "sort" ) - // Index implements a suffix array for fast substring search. type Index struct { data []byte sa []int // suffix array for data } - // New creates a new Index for data. // Index creation time is O(N*log(N)) for N = len(data). func New(data []byte) *Index { return &Index{data, qsufsort(data)} } - // Bytes returns the data over which the index was created. // It must not be modified. // @@ -44,12 +41,10 @@ func (x *Index) Bytes() []byte { return x.data } - func (x *Index) at(i int) []byte { return x.data[x.sa[i]:] } - // lookupAll returns a slice into the matching region of the index. // The runtime is O(log(N)*len(s)). func (x *Index) lookupAll(s []byte) []int { @@ -61,7 +56,6 @@ func (x *Index) lookupAll(s []byte) []int { return x.sa[i:j] } - // Lookup returns an unsorted list of at most n indices where the byte string s // occurs in the indexed data. If n < 0, all occurrences are returned. // The result is nil if s is empty, s is not found, or n == 0. @@ -82,7 +76,6 @@ func (x *Index) Lookup(s []byte, n int) (result []int) { return } - // FindAllIndex returns a sorted list of non-overlapping matches of the // regular expression r, where a match is a pair of indices specifying // the matched slice of x.Bytes(). If n < 0, all matches are returned diff --git a/src/pkg/index/suffixarray/suffixarray_test.go b/src/pkg/index/suffixarray/suffixarray_test.go index 385ff0e56a..bd37ba4007 100644 --- a/src/pkg/index/suffixarray/suffixarray_test.go +++ b/src/pkg/index/suffixarray/suffixarray_test.go @@ -13,14 +13,12 @@ import ( "testing" ) - type testCase struct { name string // name of test case source string // source to index patterns []string // patterns to lookup } - var testCases = []testCase{ { "empty string", @@ -107,7 +105,6 @@ var testCases = []testCase{ }, } - // find all occurrences of s in source; report at most n occurrences func find(src, s string, n int) []int { var res vector.IntVector @@ -125,7 +122,6 @@ func find(src, s string, n int) []int { return res } - func testLookup(t *testing.T, tc *testCase, x *Index, s string, n int) { res := x.Lookup([]byte(s), n) exp := find(tc.source, s, n) @@ -164,7 +160,6 @@ func testLookup(t *testing.T, tc *testCase, x *Index, s string, n int) { } } - func testFindAllIndex(t *testing.T, tc *testCase, x *Index, rx *regexp.Regexp, n int) { res := x.FindAllIndex(rx, n) exp := rx.FindAllStringIndex(tc.source, n) @@ -200,7 +195,6 @@ func testFindAllIndex(t *testing.T, tc *testCase, x *Index, rx *regexp.Regexp, n } } - func testLookups(t *testing.T, tc *testCase, x *Index, n int) { for _, pat := range tc.patterns { testLookup(t, tc, x, pat, n) @@ -210,7 +204,6 @@ func testLookups(t *testing.T, tc *testCase, x *Index, n int) { } } - // index is used to hide the sort.Interface type index Index @@ -219,14 +212,12 @@ func (x *index) Less(i, j int) bool { return bytes.Compare(x.at(i), x.at(j)) < 0 func (x *index) Swap(i, j int) { x.sa[i], x.sa[j] = x.sa[j], x.sa[i] } func (a *index) at(i int) []byte { return a.data[a.sa[i]:] } - func testConstruction(t *testing.T, tc *testCase, x *Index) { if !sort.IsSorted((*index)(x)) { t.Errorf("testConstruction failed %s", tc.name) } } - func TestIndex(t *testing.T) { for _, tc := range testCases { x := New([]byte(tc.source)) diff --git a/src/pkg/io/ioutil/ioutil_test.go b/src/pkg/io/ioutil/ioutil_test.go index 150ee6d632..55e4b2c2bc 100644 --- a/src/pkg/io/ioutil/ioutil_test.go +++ b/src/pkg/io/ioutil/ioutil_test.go @@ -59,7 +59,6 @@ func TestWriteFile(t *testing.T) { os.Remove(filename) // ignore error } - func TestReadDir(t *testing.T) { dirname := "rumpelstilzchen" _, err := ReadDir(dirname) diff --git a/src/pkg/json/decode.go b/src/pkg/json/decode.go index 35a06b0f96..2edbbdafee 100644 --- a/src/pkg/json/decode.go +++ b/src/pkg/json/decode.go @@ -71,7 +71,6 @@ type Unmarshaler interface { UnmarshalJSON([]byte) os.Error } - // An UnmarshalTypeError describes a JSON value that was // not appropriate for a value of a specific Go type. type UnmarshalTypeError struct { @@ -742,7 +741,6 @@ func (d *decodeState) objectInterface() map[string]interface{} { return m } - // literalInterface is like literal but returns an interface value. func (d *decodeState) literalInterface() interface{} { // All bytes inside literal return scanContinue op code. diff --git a/src/pkg/math/acosh.go b/src/pkg/math/acosh.go index d8067c0658..7e8740b89b 100644 --- a/src/pkg/math/acosh.go +++ b/src/pkg/math/acosh.go @@ -4,7 +4,6 @@ package math - // The original C code, the long comment, and the constants // below are from FreeBSD's /usr/src/lib/msun/src/e_acosh.c // and came with this notice. The go code is a simplified diff --git a/src/pkg/math/asin.go b/src/pkg/math/asin.go index 3bace8ff1c..0a0b0a11cb 100644 --- a/src/pkg/math/asin.go +++ b/src/pkg/math/asin.go @@ -4,7 +4,6 @@ package math - /* Floating-point arcsine and arccosine. diff --git a/src/pkg/math/asinh.go b/src/pkg/math/asinh.go index 90dcd27ab9..c1cad563c7 100644 --- a/src/pkg/math/asinh.go +++ b/src/pkg/math/asinh.go @@ -4,7 +4,6 @@ package math - // The original C code, the long comment, and the constants // below are from FreeBSD's /usr/src/lib/msun/src/s_asinh.c // and came with this notice. The go code is a simplified diff --git a/src/pkg/math/atanh.go b/src/pkg/math/atanh.go index 6aecb7b3bb..ed38fcac66 100644 --- a/src/pkg/math/atanh.go +++ b/src/pkg/math/atanh.go @@ -4,7 +4,6 @@ package math - // The original C code, the long comment, and the constants // below are from FreeBSD's /usr/src/lib/msun/src/e_atanh.c // and came with this notice. The go code is a simplified diff --git a/src/pkg/math/erf.go b/src/pkg/math/erf.go index b608999337..6d3d9b7c53 100644 --- a/src/pkg/math/erf.go +++ b/src/pkg/math/erf.go @@ -4,7 +4,6 @@ package math - /* Floating-point error function and complementary error function. */ diff --git a/src/pkg/math/exp_port.go b/src/pkg/math/exp_port.go index 071420c24c..618c31a5d1 100644 --- a/src/pkg/math/exp_port.go +++ b/src/pkg/math/exp_port.go @@ -4,7 +4,6 @@ package math - // The original C code, the long comment, and the constants // below are from FreeBSD's /usr/src/lib/msun/src/e_exp.c // and came with this notice. The go code is a simplified diff --git a/src/pkg/math/expm1.go b/src/pkg/math/expm1.go index 35100caa40..e9f833140b 100644 --- a/src/pkg/math/expm1.go +++ b/src/pkg/math/expm1.go @@ -4,7 +4,6 @@ package math - // The original C code, the long comment, and the constants // below are from FreeBSD's /usr/src/lib/msun/src/s_expm1.c // and came with this notice. The go code is a simplified diff --git a/src/pkg/math/floor.go b/src/pkg/math/floor.go index b22b94ad63..babbf645f5 100644 --- a/src/pkg/math/floor.go +++ b/src/pkg/math/floor.go @@ -4,7 +4,6 @@ package math - // Floor returns the greatest integer value less than or equal to x. // // Special cases are: diff --git a/src/pkg/math/fmod.go b/src/pkg/math/fmod.go index fc57f7483f..75c614629d 100644 --- a/src/pkg/math/fmod.go +++ b/src/pkg/math/fmod.go @@ -4,7 +4,6 @@ package math - /* Floating-point mod function. */ diff --git a/src/pkg/math/log1p.go b/src/pkg/math/log1p.go index e1fc275d0c..c25d73b664 100644 --- a/src/pkg/math/log1p.go +++ b/src/pkg/math/log1p.go @@ -4,7 +4,6 @@ package math - // The original C code, the long comment, and the constants // below are from FreeBSD's /usr/src/lib/msun/src/s_log1p.c // and came with this notice. The go code is a simplified diff --git a/src/pkg/math/sin.go b/src/pkg/math/sin.go index 35220cb3e5..8a2edd7e56 100644 --- a/src/pkg/math/sin.go +++ b/src/pkg/math/sin.go @@ -4,7 +4,6 @@ package math - /* Floating-point sine and cosine. diff --git a/src/pkg/math/sinh.go b/src/pkg/math/sinh.go index 23a8719f2c..eaf28a51cd 100644 --- a/src/pkg/math/sinh.go +++ b/src/pkg/math/sinh.go @@ -4,7 +4,6 @@ package math - /* Floating-point hyperbolic sine and cosine. diff --git a/src/pkg/math/tan.go b/src/pkg/math/tan.go index a36ebbf449..6d7a60ba6b 100644 --- a/src/pkg/math/tan.go +++ b/src/pkg/math/tan.go @@ -4,7 +4,6 @@ package math - /* Floating point tangent. */ diff --git a/src/pkg/math/tanh.go b/src/pkg/math/tanh.go index 8bcf2ddac2..f4a8a5a4d6 100644 --- a/src/pkg/math/tanh.go +++ b/src/pkg/math/tanh.go @@ -4,7 +4,6 @@ package math - /* Floating-point hyperbolic tangent. diff --git a/src/pkg/mime/multipart/multipart.go b/src/pkg/mime/multipart/multipart.go index 630aaf5ed2..2533bd337d 100644 --- a/src/pkg/mime/multipart/multipart.go +++ b/src/pkg/mime/multipart/multipart.go @@ -58,7 +58,6 @@ func (p *Part) FormName() string { return p.dispositionParams["name"] } - // FileName returns the filename parameter of the Part's // Content-Disposition header. func (p *Part) FileName() string { diff --git a/src/pkg/net/dnsclient_unix.go b/src/pkg/net/dnsclient_unix.go index 7f3ef28786..f407b17783 100644 --- a/src/pkg/net/dnsclient_unix.go +++ b/src/pkg/net/dnsclient_unix.go @@ -68,7 +68,6 @@ func exchange(cfg *dnsConfig, c Conn, name string, qtype uint16) (*dnsMsg, os.Er return nil, &DNSError{Error: "no answer from server", Name: name, Server: server, IsTimeout: true} } - // Do a lookup for a single name, which must be rooted // (otherwise answer will not find the answers). func tryOneName(cfg *dnsConfig, name string, qtype uint16) (cname string, addrs []dnsRR, err os.Error) { diff --git a/src/pkg/net/dnsmsg.go b/src/pkg/net/dnsmsg.go index 640973b13a..7595aa2ab5 100644 --- a/src/pkg/net/dnsmsg.go +++ b/src/pkg/net/dnsmsg.go @@ -635,7 +635,6 @@ type dnsMsg struct { extra []dnsRR } - func (dns *dnsMsg) Pack() (msg []byte, ok bool) { var dh dnsHeader diff --git a/src/pkg/net/fd_windows.go b/src/pkg/net/fd_windows.go index 6ab9053348..f5249e64c9 100644 --- a/src/pkg/net/fd_windows.go +++ b/src/pkg/net/fd_windows.go @@ -113,7 +113,6 @@ func (s *resultSrv) Run() { } } - // ioSrv executes net io requests. type ioSrv struct { submchan chan anOpIface // submit io requests diff --git a/src/pkg/net/interface_windows.go b/src/pkg/net/interface_windows.go index 198e4096f6..571f74cdc8 100644 --- a/src/pkg/net/interface_windows.go +++ b/src/pkg/net/interface_windows.go @@ -55,7 +55,6 @@ func getInterfaceList() ([]syscall.InterfaceInfo, os.Error) { return ii[:c-1], nil } - // If the ifindex is zero, interfaceTable returns mappings of all // network interfaces. Otheriwse it returns a mapping of a specific // interface. diff --git a/src/pkg/net/ipraw_test.go b/src/pkg/net/ipraw_test.go index 7cc9604b54..6894ce656d 100644 --- a/src/pkg/net/ipraw_test.go +++ b/src/pkg/net/ipraw_test.go @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. - // TODO(cw): ListenPacket test, Read() test, ipv6 test & // Dial()/Listen() level tests diff --git a/src/pkg/os/env_unix.go b/src/pkg/os/env_unix.go index 8aa71e83a0..9cc0b03d87 100644 --- a/src/pkg/os/env_unix.go +++ b/src/pkg/os/env_unix.go @@ -16,7 +16,6 @@ var ENOENV = NewError("no such environment variable") var env map[string]string var once sync.Once - func copyenv() { env = make(map[string]string) for _, s := range Envs { diff --git a/src/pkg/os/file_plan9.go b/src/pkg/os/file_plan9.go index f196ea9a65..1e94fb715b 100644 --- a/src/pkg/os/file_plan9.go +++ b/src/pkg/os/file_plan9.go @@ -44,7 +44,6 @@ type dirInfo struct { func epipecheck(file *File, e syscall.Error) { } - // DevNull is the name of the operating system's ``null device.'' // On Unix-like systems, it is "/dev/null"; on Windows, "NUL". const DevNull = "/dev/null" @@ -304,7 +303,6 @@ func Pipe() (r *File, w *File, err Error) { return NewFile(p[0], "|0"), NewFile(p[1], "|1"), nil } - // not supported on Plan 9 // Link creates a hard link. diff --git a/src/pkg/os/inotify/inotify_linux.go b/src/pkg/os/inotify/inotify_linux.go index 7c7b7698fe..99fa516222 100644 --- a/src/pkg/os/inotify/inotify_linux.go +++ b/src/pkg/os/inotify/inotify_linux.go @@ -34,7 +34,6 @@ import ( "unsafe" ) - type Event struct { Mask uint32 // Mask of events Cookie uint32 // Unique cookie associating related events (for rename(2)) @@ -56,7 +55,6 @@ type Watcher struct { isClosed bool // Set to true when Close() is first called } - // NewWatcher creates and returns a new inotify instance using inotify_init(2) func NewWatcher() (*Watcher, os.Error) { fd, errno := syscall.InotifyInit() @@ -76,7 +74,6 @@ func NewWatcher() (*Watcher, os.Error) { return w, nil } - // Close closes an inotify watcher instance // It sends a message to the reader goroutine to quit and removes all watches // associated with the inotify instance @@ -119,13 +116,11 @@ func (w *Watcher) AddWatch(path string, flags uint32) os.Error { return nil } - // Watch adds path to the watched file set, watching all events. func (w *Watcher) Watch(path string) os.Error { return w.AddWatch(path, IN_ALL_EVENTS) } - // RemoveWatch removes path from the watched file set. func (w *Watcher) RemoveWatch(path string) os.Error { watch, ok := w.watches[path] @@ -140,7 +135,6 @@ func (w *Watcher) RemoveWatch(path string) os.Error { return nil } - // readEvents reads from the inotify file descriptor, converts the // received events into Event objects and sends them via the Event channel func (w *Watcher) readEvents() { @@ -208,7 +202,6 @@ func (w *Watcher) readEvents() { } } - // String formats the event e in the form // "filename: 0xEventMask = IN_ACCESS|IN_ATTRIB_|..." func (e *Event) String() string { diff --git a/src/pkg/os/inotify/inotify_linux_test.go b/src/pkg/os/inotify/inotify_linux_test.go index e29a46d6c2..aa72604eb9 100644 --- a/src/pkg/os/inotify/inotify_linux_test.go +++ b/src/pkg/os/inotify/inotify_linux_test.go @@ -74,7 +74,6 @@ func TestInotifyEvents(t *testing.T) { } } - func TestInotifyClose(t *testing.T) { watcher, _ := NewWatcher() watcher.Close() diff --git a/src/pkg/os/os_test.go b/src/pkg/os/os_test.go index dadae03e8c..4d60333df7 100644 --- a/src/pkg/os/os_test.go +++ b/src/pkg/os/os_test.go @@ -914,7 +914,6 @@ func run(t *testing.T, cmd []string) string { return output } - func TestHostname(t *testing.T) { // There is no other way to fetch hostname on windows, but via winapi. // On Plan 9 it is can be taken from #c/sysname as Hostname() does. diff --git a/src/pkg/os/path.go b/src/pkg/os/path.go index 7b93036aab..a8dfce3075 100644 --- a/src/pkg/os/path.go +++ b/src/pkg/os/path.go @@ -4,7 +4,6 @@ package os - // MkdirAll creates a directory named path, // along with any necessary parents, and returns nil, // or else returns an error. diff --git a/src/pkg/os/proc.go b/src/pkg/os/proc.go index 481ef60337..dfe388f250 100644 --- a/src/pkg/os/proc.go +++ b/src/pkg/os/proc.go @@ -11,7 +11,6 @@ import "syscall" var Args []string // provided by runtime var Envs []string // provided by runtime - // Getuid returns the numeric user id of the caller. func Getuid() int { return syscall.Getuid() } diff --git a/src/pkg/os/stat_plan9.go b/src/pkg/os/stat_plan9.go index d2300d5984..173a23f8bd 100644 --- a/src/pkg/os/stat_plan9.go +++ b/src/pkg/os/stat_plan9.go @@ -69,7 +69,6 @@ func dirstat(arg interface{}) (d *Dir, err Error) { return nil, &PathError{"stat", name, Ebadstat} } - // Stat returns a FileInfo structure describing the named file and an error, if any. func Stat(name string) (fi *FileInfo, err Error) { d, err := dirstat(name) diff --git a/src/pkg/os/sys_linux.go b/src/pkg/os/sys_linux.go index 408d667c7c..2accd6c1f0 100644 --- a/src/pkg/os/sys_linux.go +++ b/src/pkg/os/sys_linux.go @@ -6,7 +6,6 @@ package os - // Hostname returns the host name reported by the kernel. func Hostname() (name string, err Error) { f, err := Open("/proc/sys/kernel/hostname") diff --git a/src/pkg/os/sys_plan9.go b/src/pkg/os/sys_plan9.go index f6af28b611..c24cde05ec 100644 --- a/src/pkg/os/sys_plan9.go +++ b/src/pkg/os/sys_plan9.go @@ -6,7 +6,6 @@ package os - func Hostname() (name string, err Error) { f, err := Open("#c/sysname") if err != nil { diff --git a/src/pkg/os/time.go b/src/pkg/os/time.go index 8e87a49e16..949574d19a 100644 --- a/src/pkg/os/time.go +++ b/src/pkg/os/time.go @@ -6,7 +6,6 @@ package os import "syscall" - // Time returns the current time, in whole seconds and // fractional nanoseconds, plus an Error if any. The current // time is thus 1e9*sec+nsec, in nanoseconds. The zero of diff --git a/src/pkg/reflect/all_test.go b/src/pkg/reflect/all_test.go index 34d74b37a4..ac43b50bb1 100644 --- a/src/pkg/reflect/all_test.go +++ b/src/pkg/reflect/all_test.go @@ -380,7 +380,6 @@ func TestMapSetNil(t *testing.T) { } } - func TestAll(t *testing.T) { testType(t, 1, TypeOf((int8)(0)), "int8") testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8") @@ -744,7 +743,6 @@ func TestDeepEqualUnexportedMap(t *testing.T) { } } - func check2ndField(x interface{}, offs uintptr, t *testing.T) { s := ValueOf(x) f := s.Type().Field(1) diff --git a/src/pkg/reflect/type.go b/src/pkg/reflect/type.go index a120da732a..76a65effcd 100644 --- a/src/pkg/reflect/type.go +++ b/src/pkg/reflect/type.go @@ -271,7 +271,6 @@ const ( BothDir = RecvDir | SendDir ) - // arrayType represents a fixed array type. type arrayType struct { commonType `reflect:"array"` @@ -342,7 +341,6 @@ type structType struct { fields []structField } - /* * The compiler knows the exact layout of all the data structures above. * The compiler does not know about the data structures and methods below. diff --git a/src/pkg/rpc/client.go b/src/pkg/rpc/client.go index b1828614fc..4acfdf6d96 100644 --- a/src/pkg/rpc/client.go +++ b/src/pkg/rpc/client.go @@ -197,7 +197,6 @@ func (c *gobClientCodec) Close() os.Error { return c.rwc.Close() } - // DialHTTP connects to an HTTP RPC server at the specified network address // listening on the default HTTP RPC path. func DialHTTP(network, address string) (*Client, os.Error) { diff --git a/src/pkg/rpc/server.go b/src/pkg/rpc/server.go index 07845d128b..b079c9bb9a 100644 --- a/src/pkg/rpc/server.go +++ b/src/pkg/rpc/server.go @@ -376,7 +376,6 @@ func (c *gobServerCodec) Close() os.Error { return c.rwc.Close() } - // ServeConn runs the server on a single connection. // ServeConn blocks, serving the connection until the client hangs up. // The caller typically invokes ServeConn in a go statement. diff --git a/src/pkg/scanner/scanner.go b/src/pkg/scanner/scanner.go index e79d392f70..d0c32e70a7 100644 --- a/src/pkg/scanner/scanner.go +++ b/src/pkg/scanner/scanner.go @@ -34,7 +34,6 @@ import ( "utf8" ) - // TODO(gri): Consider changing this to use the new (token) Position package. // A source position is represented by a Position value. @@ -46,11 +45,9 @@ type Position struct { Column int // column number, starting at 1 (character count per line) } - // IsValid returns true if the position is valid. func (pos *Position) IsValid() bool { return pos.Line > 0 } - func (pos Position) String() string { s := pos.Filename if pos.IsValid() { @@ -65,7 +62,6 @@ func (pos Position) String() string { return s } - // Predefined mode bits to control recognition of tokens. For instance, // to configure a Scanner such that it only recognizes (Go) identifiers, // integers, and skips comments, set the Scanner's Mode field to: @@ -84,7 +80,6 @@ const ( GoTokens = ScanIdents | ScanFloats | ScanChars | ScanStrings | ScanRawStrings | ScanComments | SkipComments ) - // The result of Scan is one of the following tokens or a Unicode character. const ( EOF = -(iota + 1) @@ -98,7 +93,6 @@ const ( skipComment ) - var tokenString = map[int]string{ EOF: "EOF", Ident: "Ident", @@ -110,7 +104,6 @@ var tokenString = map[int]string{ Comment: "Comment", } - // TokenString returns a (visible) string for a token or Unicode character. func TokenString(tok int) string { if s, found := tokenString[tok]; found { @@ -119,12 +112,10 @@ func TokenString(tok int) string { return fmt.Sprintf("%q", string(tok)) } - // GoWhitespace is the default value for the Scanner's Whitespace field. // Its value selects Go's white space characters. const GoWhitespace = 1<<'\t' | 1<<'\n' | 1<<'\r' | 1<<' ' - const bufLen = 1024 // at least utf8.UTFMax // A Scanner implements reading of Unicode characters and tokens from an io.Reader. @@ -179,7 +170,6 @@ type Scanner struct { Position } - // Init initializes a Scanner with a new source and returns s. // Error is set to nil, ErrorCount is set to 0, Mode is set to GoTokens, // and Whitespace is set to GoWhitespace. @@ -215,7 +205,6 @@ func (s *Scanner) Init(src io.Reader) *Scanner { return s } - // TODO(gri): The code for next() and the internal scanner state could benefit // from a rethink. While next() is optimized for the common ASCII // case, the "corrections" needed for proper position tracking undo @@ -300,7 +289,6 @@ func (s *Scanner) next() int { return ch } - // Next reads and returns the next Unicode character. // It returns EOF at the end of the source. It reports // a read error by calling s.Error, if not nil; otherwise @@ -314,7 +302,6 @@ func (s *Scanner) Next() int { return ch } - // Peek returns the next Unicode character in the source without advancing // the scanner. It returns EOF if the scanner's position is at the last // character of the source. @@ -325,7 +312,6 @@ func (s *Scanner) Peek() int { return s.ch } - func (s *Scanner) error(msg string) { s.ErrorCount++ if s.Error != nil { @@ -335,7 +321,6 @@ func (s *Scanner) error(msg string) { fmt.Fprintf(os.Stderr, "%s: %s\n", s.Position, msg) } - func (s *Scanner) scanIdentifier() int { ch := s.next() // read character after first '_' or letter for ch == '_' || unicode.IsLetter(ch) || unicode.IsDigit(ch) { @@ -344,7 +329,6 @@ func (s *Scanner) scanIdentifier() int { return ch } - func digitVal(ch int) int { switch { case '0' <= ch && ch <= '9': @@ -357,10 +341,8 @@ func digitVal(ch int) int { return 16 // larger than any legal digit val } - func isDecimal(ch int) bool { return '0' <= ch && ch <= '9' } - func (s *Scanner) scanMantissa(ch int) int { for isDecimal(ch) { ch = s.next() @@ -368,7 +350,6 @@ func (s *Scanner) scanMantissa(ch int) int { return ch } - func (s *Scanner) scanFraction(ch int) int { if ch == '.' { ch = s.scanMantissa(s.next()) @@ -376,7 +357,6 @@ func (s *Scanner) scanFraction(ch int) int { return ch } - func (s *Scanner) scanExponent(ch int) int { if ch == 'e' || ch == 'E' { ch = s.next() @@ -388,7 +368,6 @@ func (s *Scanner) scanExponent(ch int) int { return ch } - func (s *Scanner) scanNumber(ch int) (int, int) { // isDecimal(ch) if ch == '0' { @@ -433,7 +412,6 @@ func (s *Scanner) scanNumber(ch int) (int, int) { return Int, ch } - func (s *Scanner) scanDigits(ch, base, n int) int { for n > 0 && digitVal(ch) < base { ch = s.next() @@ -445,7 +423,6 @@ func (s *Scanner) scanDigits(ch, base, n int) int { return ch } - func (s *Scanner) scanEscape(quote int) int { ch := s.next() // read character after '/' switch ch { @@ -466,7 +443,6 @@ func (s *Scanner) scanEscape(quote int) int { return ch } - func (s *Scanner) scanString(quote int) (n int) { ch := s.next() // read character after quote for ch != quote { @@ -484,7 +460,6 @@ func (s *Scanner) scanString(quote int) (n int) { return } - func (s *Scanner) scanRawString() { ch := s.next() // read character after '`' for ch != '`' { @@ -496,14 +471,12 @@ func (s *Scanner) scanRawString() { } } - func (s *Scanner) scanChar() { if s.scanString('\'') != 1 { s.error("illegal char literal") } } - func (s *Scanner) scanComment(ch int) int { // ch == '/' || ch == '*' if ch == '/' { @@ -532,7 +505,6 @@ func (s *Scanner) scanComment(ch int) int { return ch } - // Scan reads the next token or Unicode character from source and returns it. // It only recognizes tokens t for which the respective Mode bit (1<<-t) is set. // It returns EOF at the end of the source. It reports scanner errors (read and @@ -635,7 +607,6 @@ redo: return tok } - // Pos returns the position of the character immediately after // the character or token returned by the last call to Next or Scan. func (s *Scanner) Pos() (pos Position) { @@ -658,7 +629,6 @@ func (s *Scanner) Pos() (pos Position) { return } - // TokenText returns the string corresponding to the most recently scanned token. // Valid after calling Scan(). func (s *Scanner) TokenText() string { diff --git a/src/pkg/scanner/scanner_test.go b/src/pkg/scanner/scanner_test.go index cf9ad01111..4ba1587e8a 100644 --- a/src/pkg/scanner/scanner_test.go +++ b/src/pkg/scanner/scanner_test.go @@ -13,14 +13,12 @@ import ( "utf8" ) - // A StringReader delivers its data one string segment at a time via Read. type StringReader struct { data []string step int } - func (r *StringReader) Read(p []byte) (n int, err os.Error) { if r.step < len(r.data) { s := r.data[r.step] @@ -32,7 +30,6 @@ func (r *StringReader) Read(p []byte) (n int, err os.Error) { return } - func readRuneSegments(t *testing.T, segments []string) { got := "" want := strings.Join(segments, "") @@ -49,7 +46,6 @@ func readRuneSegments(t *testing.T, segments []string) { } } - var segmentList = [][]string{ {}, {""}, @@ -61,14 +57,12 @@ var segmentList = [][]string{ {"Hello", ", ", "", "World", "!"}, } - func TestNext(t *testing.T) { for _, s := range segmentList { readRuneSegments(t, s) } } - type token struct { tok int text string @@ -234,7 +228,6 @@ var tokenList = []token{ {'(', "("}, } - func makeSource(pattern string) *bytes.Buffer { var buf bytes.Buffer for _, k := range tokenList { @@ -243,7 +236,6 @@ func makeSource(pattern string) *bytes.Buffer { return &buf } - func checkTok(t *testing.T, s *Scanner, line, got, want int, text string) { if got != want { t.Fatalf("tok = %s, want %s for %q", TokenString(got), TokenString(want), text) @@ -263,7 +255,6 @@ func checkTok(t *testing.T, s *Scanner, line, got, want int, text string) { } } - func countNewlines(s string) int { n := 0 for _, ch := range s { @@ -274,7 +265,6 @@ func countNewlines(s string) int { return n } - func testScan(t *testing.T, mode uint) { s := new(Scanner).Init(makeSource(" \t%s\n")) s.Mode = mode @@ -290,13 +280,11 @@ func testScan(t *testing.T, mode uint) { checkTok(t, s, line, tok, EOF, "") } - func TestScan(t *testing.T) { testScan(t, GoTokens) testScan(t, GoTokens&^SkipComments) } - func TestPosition(t *testing.T) { src := makeSource("\t\t\t\t%s\n") s := new(Scanner).Init(src) @@ -323,7 +311,6 @@ func TestPosition(t *testing.T) { } } - func TestScanZeroMode(t *testing.T) { src := makeSource("%s\n") str := src.String() @@ -345,7 +332,6 @@ func TestScanZeroMode(t *testing.T) { } } - func testScanSelectedMode(t *testing.T, mode uint, class int) { src := makeSource("%s\n") s := new(Scanner).Init(src) @@ -362,7 +348,6 @@ func testScanSelectedMode(t *testing.T, mode uint, class int) { } } - func TestScanSelectedMask(t *testing.T) { testScanSelectedMode(t, 0, 0) testScanSelectedMode(t, ScanIdents, Ident) @@ -375,7 +360,6 @@ func TestScanSelectedMask(t *testing.T) { testScanSelectedMode(t, ScanComments, Comment) } - func TestScanNext(t *testing.T) { s := new(Scanner).Init(bytes.NewBufferString("if a == bcd /* comment */ {\n\ta += c\n} // line comment ending in eof")) checkTok(t, s, 1, s.Scan(), Ident, "if") @@ -397,7 +381,6 @@ func TestScanNext(t *testing.T) { } } - func TestScanWhitespace(t *testing.T) { var buf bytes.Buffer var ws uint64 @@ -418,7 +401,6 @@ func TestScanWhitespace(t *testing.T) { } } - func testError(t *testing.T, src, msg string, tok int) { s := new(Scanner).Init(bytes.NewBufferString(src)) errorCalled := false @@ -443,7 +425,6 @@ func testError(t *testing.T, src, msg string, tok int) { } } - func TestError(t *testing.T) { testError(t, "\x00", "illegal character NUL", 0) testError(t, "\xff", "illegal UTF-8 encoding", utf8.RuneError) @@ -459,7 +440,6 @@ func TestError(t *testing.T) { testError(t, `"abc`+"\xff"+`def"`, "illegal UTF-8 encoding", String) } - func checkPos(t *testing.T, got, want Position) { if got.Offset != want.Offset || got.Line != want.Line || got.Column != want.Column { t.Errorf("got offset, line, column = %d, %d, %d; want %d, %d, %d", @@ -467,7 +447,6 @@ func checkPos(t *testing.T, got, want Position) { } } - func checkNextPos(t *testing.T, s *Scanner, offset, line, column, char int) { if ch := s.Next(); ch != char { t.Errorf("ch = %s, want %s", TokenString(ch), TokenString(char)) @@ -476,7 +455,6 @@ func checkNextPos(t *testing.T, s *Scanner, offset, line, column, char int) { checkPos(t, s.Pos(), want) } - func checkScanPos(t *testing.T, s *Scanner, offset, line, column, char int) { want := Position{Offset: offset, Line: line, Column: column} checkPos(t, s.Pos(), want) @@ -489,7 +467,6 @@ func checkScanPos(t *testing.T, s *Scanner, offset, line, column, char int) { checkPos(t, s.Position, want) } - func TestPos(t *testing.T) { // corner case: empty source s := new(Scanner).Init(bytes.NewBufferString("")) diff --git a/src/pkg/sort/search.go b/src/pkg/sort/search.go index 7d468da8a0..4f0ce55c3c 100644 --- a/src/pkg/sort/search.go +++ b/src/pkg/sort/search.go @@ -71,7 +71,6 @@ func Search(n int, f func(int) bool) int { return i } - // Convenience wrappers for common cases. // SearchInts searches for x in a sorted slice of ints and returns the index @@ -81,7 +80,6 @@ func SearchInts(a []int, x int) int { return Search(len(a), func(i int) bool { return a[i] >= x }) } - // SearchFloat64s searches for x in a sorted slice of float64s and returns the index // as specified by Search. The slice must be sorted in ascending order. // @@ -89,7 +87,6 @@ func SearchFloat64s(a []float64, x float64) int { return Search(len(a), func(i int) bool { return a[i] >= x }) } - // SearchStrings searches for x slice a sorted slice of strings and returns the index // as specified by Search. The slice must be sorted in ascending order. // @@ -97,14 +94,11 @@ func SearchStrings(a []string, x string) int { return Search(len(a), func(i int) bool { return a[i] >= x }) } - // Search returns the result of applying SearchInts to the receiver and x. func (p IntSlice) Search(x int) int { return SearchInts(p, x) } - // Search returns the result of applying SearchFloat64s to the receiver and x. func (p Float64Slice) Search(x float64) int { return SearchFloat64s(p, x) } - // Search returns the result of applying SearchStrings to the receiver and x. func (p StringSlice) Search(x string) int { return SearchStrings(p, x) } diff --git a/src/pkg/sort/search_test.go b/src/pkg/sort/search_test.go index 2a9a858545..0005cd2ced 100644 --- a/src/pkg/sort/search_test.go +++ b/src/pkg/sort/search_test.go @@ -6,14 +6,12 @@ package sort import "testing" - func f(a []int, x int) func(int) bool { return func(i int) bool { return a[i] >= x } } - var data = []int{0: -10, 1: -5, 2: 0, 3: 1, 4: 2, 5: 3, 6: 5, 7: 7, 8: 11, 9: 100, 10: 100, 11: 100, 12: 1000, 13: 10000} var tests = []struct { @@ -46,7 +44,6 @@ var tests = []struct { {"overflow", 2e9, func(i int) bool { return false }, 2e9}, } - func TestSearch(t *testing.T) { for _, e := range tests { i := Search(e.n, e.f) @@ -56,7 +53,6 @@ func TestSearch(t *testing.T) { } } - // log2 computes the binary logarithm of x, rounded up to the next integer. // (log2(0) == 0, log2(1) == 0, log2(2) == 1, log2(3) == 2, etc.) // @@ -70,7 +66,6 @@ func log2(x int) int { return n } - func TestSearchEfficiency(t *testing.T) { n := 100 step := 1 @@ -93,7 +88,6 @@ func TestSearchEfficiency(t *testing.T) { } } - // Smoke tests for convenience wrappers - not comprehensive. var fdata = []float64{0: -3.14, 1: 0, 2: 1, 3: 2, 4: 1000.7} @@ -112,7 +106,6 @@ var wrappertests = []struct { {"StringSlice.Search", StringSlice(sdata).Search("x"), 3}, } - func TestSearchWrappers(t *testing.T) { for _, e := range wrappertests { if e.result != e.i { @@ -121,7 +114,6 @@ func TestSearchWrappers(t *testing.T) { } } - // Abstract exhaustive test: all sizes up to 100, // all possible return values. If there are any small // corner cases, this test exercises them. diff --git a/src/pkg/sort/sort.go b/src/pkg/sort/sort.go index daed61ea8d..067d27901e 100644 --- a/src/pkg/sort/sort.go +++ b/src/pkg/sort/sort.go @@ -141,7 +141,6 @@ func quickSort(data Interface, a, b int) { func Sort(data Interface) { quickSort(data, 0, data.Len()) } - func IsSorted(data Interface) bool { n := data.Len() for i := n - 1; i > 0; i-- { @@ -152,7 +151,6 @@ func IsSorted(data Interface) bool { return true } - // Convenience types for common cases // IntSlice attaches the methods of Interface to []int, sorting in increasing order. @@ -165,7 +163,6 @@ func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // Sort is a convenience method. func (p IntSlice) Sort() { Sort(p) } - // Float64Slice attaches the methods of Interface to []float64, sorting in increasing order. type Float64Slice []float64 @@ -176,7 +173,6 @@ func (p Float64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // Sort is a convenience method. func (p Float64Slice) Sort() { Sort(p) } - // StringSlice attaches the methods of Interface to []string, sorting in increasing order. type StringSlice []string @@ -187,7 +183,6 @@ func (p StringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // Sort is a convenience method. func (p StringSlice) Sort() { Sort(p) } - // Convenience wrappers for common cases // Ints sorts a slice of ints in increasing order. @@ -197,7 +192,6 @@ func Float64s(a []float64) { Sort(Float64Slice(a)) } // Strings sorts a slice of strings in increasing order. func Strings(a []string) { Sort(StringSlice(a)) } - // IntsAreSorted tests whether a slice of ints is sorted in increasing order. func IntsAreSorted(a []int) bool { return IsSorted(IntSlice(a)) } // Float64sAreSorted tests whether a slice of float64s is sorted in increasing order. diff --git a/src/pkg/sort/sort_test.go b/src/pkg/sort/sort_test.go index 4da2626377..20e7287da9 100644 --- a/src/pkg/sort/sort_test.go +++ b/src/pkg/sort/sort_test.go @@ -11,7 +11,6 @@ import ( "testing" ) - var ints = [...]int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586} var float64s = [...]float64{74.3, 59.0, 238.2, -784.0, 2.3, 9845.768, -959.7485, 905, 7.8, 7.8} var strings = [...]string{"", "Hello", "foo", "bar", "foo", "f00", "%*&^*&^&", "***"} diff --git a/src/pkg/strconv/atoi.go b/src/pkg/strconv/atoi.go index e1154782b5..5845942162 100644 --- a/src/pkg/strconv/atoi.go +++ b/src/pkg/strconv/atoi.go @@ -13,7 +13,6 @@ type NumError struct { func (e *NumError) String() string { return `parsing "` + e.Num + `": ` + e.Error.String() } - func computeIntsize() uint { siz := uint(8) for 1< len(src) { b.write0(src) @@ -247,13 +236,11 @@ func (b *Writer) writeN(src []byte, n int) { b.write0(src[0:n]) } - var ( newline = []byte{'\n'} tabs = []byte("\t\t\t\t\t\t\t\t") ) - func (b *Writer) writePadding(textw, cellw int, useTabs bool) { if b.padbytes[0] == '\t' || useTabs { // padding is done with tabs @@ -274,7 +261,6 @@ func (b *Writer) writePadding(textw, cellw int, useTabs bool) { b.writeN(b.padbytes[0:], cellw-textw) } - var vbar = []byte{'|'} func (b *Writer) writeLines(pos0 int, line0, line1 int) (pos int) { @@ -328,7 +314,6 @@ func (b *Writer) writeLines(pos0 int, line0, line1 int) (pos int) { return } - // Format the text between line0 and line1 (excluding line1); pos // is the buffer position corresponding to the beginning of line0. // Returns the buffer position corresponding to the beginning of @@ -392,21 +377,18 @@ func (b *Writer) format(pos0 int, line0, line1 int) (pos int) { return b.writeLines(pos, line0, line1) } - // Append text to current cell. func (b *Writer) append(text []byte) { b.buf.Write(text) b.cell.size += len(text) } - // Update the cell width. func (b *Writer) updateWidth() { b.cell.width += utf8.RuneCount(b.buf.Bytes()[b.pos:b.buf.Len()]) b.pos = b.buf.Len() } - // To escape a text segment, bracket it with Escape characters. // For instance, the tab in this string "Ignore this tab: \xff\t\xff" // does not terminate a cell and constitutes a single character of @@ -416,7 +398,6 @@ func (b *Writer) updateWidth() { // const Escape = '\xff' - // Start escaped mode. func (b *Writer) startEscape(ch byte) { switch ch { @@ -429,7 +410,6 @@ func (b *Writer) startEscape(ch byte) { } } - // Terminate escaped mode. If the escaped text was an HTML tag, its width // is assumed to be zero for formatting purposes; if it was an HTML entity, // its width is assumed to be one. In all other cases, the width is the @@ -450,7 +430,6 @@ func (b *Writer) endEscape() { b.endChar = 0 } - // Terminate the current cell by adding it to the list of cells of the // current line. Returns the number of cells in that line. // @@ -462,14 +441,12 @@ func (b *Writer) terminateCell(htab bool) int { return len(*line) } - func handlePanic(err *os.Error) { if e := recover(); e != nil { *err = e.(osError).err // re-panics if it's not a local osError } } - // Flush should be called after the last call to Write to ensure // that any data buffered in the Writer is written to output. Any // incomplete escape sequence at the end is simply considered @@ -494,7 +471,6 @@ func (b *Writer) Flush() (err os.Error) { return } - var hbar = []byte("---\n") // Write writes buf to the writer b. @@ -577,7 +553,6 @@ func (b *Writer) Write(buf []byte) (n int, err os.Error) { return } - // NewWriter allocates and initializes a new tabwriter.Writer. // The parameters are the same as for the the Init function. // diff --git a/src/pkg/tabwriter/tabwriter_test.go b/src/pkg/tabwriter/tabwriter_test.go index 043d9154e1..6ef7e808ef 100644 --- a/src/pkg/tabwriter/tabwriter_test.go +++ b/src/pkg/tabwriter/tabwriter_test.go @@ -10,18 +10,14 @@ import ( "testing" ) - type buffer struct { a []byte } - func (b *buffer) init(n int) { b.a = make([]byte, n)[0:0] } - 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) @@ -36,10 +32,8 @@ func (b *buffer) Write(buf []byte) (written int, err os.Error) { return len(buf), nil } - 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) if err != nil { @@ -50,7 +44,6 @@ 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() if err != nil { @@ -63,7 +56,6 @@ 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) @@ -98,7 +90,6 @@ func check(t *testing.T, testname string, minwidth, tabwidth, padding int, padch verify(t, title, &w, &b, src, expected) } - var tests = []struct { testname string minwidth, tabwidth, padding int @@ -617,7 +608,6 @@ var tests = []struct { }, } - func Test(t *testing.T) { for _, e := range tests { check(t, e.testname, e.minwidth, e.tabwidth, e.padding, e.padchar, e.flags, e.src, e.expected) diff --git a/src/pkg/template/template_test.go b/src/pkg/template/template_test.go index 99b23c2883..eae8011eb3 100644 --- a/src/pkg/template/template_test.go +++ b/src/pkg/template/template_test.go @@ -259,7 +259,6 @@ var tests = []*Test{ out: "77", }, - // Repeated &Test{ in: "{.section Pdata }\n" + @@ -438,7 +437,6 @@ var tests = []*Test{ "pointedToString\n", }, - // Interface values &Test{ diff --git a/src/pkg/testing/iotest/reader.go b/src/pkg/testing/iotest/reader.go index daa6ede08e..dcf5565e07 100644 --- a/src/pkg/testing/iotest/reader.go +++ b/src/pkg/testing/iotest/reader.go @@ -37,7 +37,6 @@ func (r *halfReader) Read(p []byte) (int, os.Error) { return r.r.Read(p[0 : (len(p)+1)/2]) } - // DataErrReader returns a Reader that returns the final // error with the last data read, instead of by itself with // zero bytes of data. diff --git a/src/pkg/testing/testing.go b/src/pkg/testing/testing.go index ba721523e1..ec4a453717 100644 --- a/src/pkg/testing/testing.go +++ b/src/pkg/testing/testing.go @@ -74,7 +74,6 @@ func Short() bool { return *short } - // Insert final newline if needed and tabs after internal newlines. func tabify(s string) string { n := len(s) diff --git a/src/pkg/time/zoneinfo_unix.go b/src/pkg/time/zoneinfo_unix.go index 2a83e0c16c..f3ea7b6fda 100644 --- a/src/pkg/time/zoneinfo_unix.go +++ b/src/pkg/time/zoneinfo_unix.go @@ -24,7 +24,6 @@ type data struct { error bool } - func (d *data) read(n int) []byte { if len(d.p) < n { d.p = nil @@ -54,7 +53,6 @@ func (d *data) byte() (n byte, ok bool) { return p[0], true } - // Make a string by stopping at the first NUL func byteString(p []byte) string { for i := 0; i < len(p); i++ { diff --git a/src/pkg/unicode/casetables.go b/src/pkg/unicode/casetables.go index 66440705bf..86336b1b90 100644 --- a/src/pkg/unicode/casetables.go +++ b/src/pkg/unicode/casetables.go @@ -9,7 +9,6 @@ package unicode - var TurkishCase = _TurkishCase var _TurkishCase = SpecialCase{ CaseRange{0x0049, 0x0049, d{0, 0x131 - 0x49, 0}}, diff --git a/src/pkg/unicode/maketables.go b/src/pkg/unicode/maketables.go index 07b931d7ee..0020dc427c 100644 --- a/src/pkg/unicode/maketables.go +++ b/src/pkg/unicode/maketables.go @@ -366,7 +366,6 @@ package unicode ` - func printCategories() { if *tablelist == "" { return diff --git a/src/pkg/unicode/tables.go b/src/pkg/unicode/tables.go index a75011adb9..9fe43017e5 100644 --- a/src/pkg/unicode/tables.go +++ b/src/pkg/unicode/tables.go @@ -6099,7 +6099,6 @@ var foldLt = &RangeTable{ // If there is no entry for a script name, there are no such points. var FoldScript = map[string]*RangeTable{} - // Range entries: 3391 16-bit, 659 32-bit, 4050 total. // Range bytes: 20346 16-bit, 7908 32-bit, 28254 total. diff --git a/src/pkg/websocket/server.go b/src/pkg/websocket/server.go index 165cbffee0..e0e7c872db 100644 --- a/src/pkg/websocket/server.go +++ b/src/pkg/websocket/server.go @@ -154,7 +154,6 @@ func (f Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { f(ws) } - /* Draft75Handler is an interface to a WebSocket based on the (soon obsolete) draft-hixie-thewebsocketprotocol-75. diff --git a/src/pkg/xml/xml.go b/src/pkg/xml/xml.go index e5d73dd020..e7ba44e4a2 100644 --- a/src/pkg/xml/xml.go +++ b/src/pkg/xml/xml.go @@ -416,7 +416,6 @@ func (p *Parser) autoClose(t Token) (Token, bool) { return nil, false } - // RawToken is like Token but does not verify that // start and end elements match and does not translate // name space prefixes to their corresponding URLs. diff --git a/src/pkg/xml/xml_test.go b/src/pkg/xml/xml_test.go index aba21a2b44..6407624055 100644 --- a/src/pkg/xml/xml_test.go +++ b/src/pkg/xml/xml_test.go @@ -546,7 +546,6 @@ func TestEntityInsideCDATA(t *testing.T) { } } - // The last three tests (respectively one for characters in attribute // names and two for character entities) pass not because of code // changed for issue 1259, but instead pass with the given messages @@ -567,7 +566,6 @@ var characterTests = []struct { {"&\xef\xbf\xbe;", "invalid character entity &;"}, } - func TestDisallowedCharacters(t *testing.T) { for i, tt := range characterTests { -- 2.50.0