diff options
Diffstat (limited to 'src/cmd')
-rw-r--r-- | src/cmd/cgo/ast.go | 230 | ||||
-rw-r--r-- | src/cmd/cgo/gcc.go | 412 | ||||
-rw-r--r-- | src/cmd/cgo/main.go | 60 | ||||
-rw-r--r-- | src/cmd/cgo/out.go | 170 | ||||
-rw-r--r-- | src/cmd/cgo/util.go | 74 | ||||
-rw-r--r-- | src/cmd/ebnflint/ebnflint.go | 54 | ||||
-rw-r--r-- | src/cmd/gc/runtime.go | 2 | ||||
-rw-r--r-- | src/cmd/godoc/godoc.go | 600 | ||||
-rw-r--r-- | src/cmd/godoc/index.go | 418 | ||||
-rw-r--r-- | src/cmd/godoc/main.go | 142 | ||||
-rwxr-xr-x | src/cmd/godoc/snippet.go | 48 | ||||
-rw-r--r-- | src/cmd/godoc/spec.go | 122 | ||||
-rw-r--r-- | src/cmd/gofmt/gofmt.go | 118 | ||||
-rw-r--r-- | src/cmd/gofmt/rewrite.go | 130 | ||||
-rw-r--r-- | src/cmd/goyacc/goyacc.go | 1814 | ||||
-rw-r--r-- | src/cmd/hgpatch/main.go | 268 |
16 files changed, 2331 insertions, 2331 deletions
diff --git a/src/cmd/cgo/ast.go b/src/cmd/cgo/ast.go index ccaef69d1..b309c33d4 100644 --- a/src/cmd/cgo/ast.go +++ b/src/cmd/cgo/ast.go @@ -7,57 +7,57 @@ package main import ( - "fmt"; - "go/ast"; - "go/doc"; - "go/parser"; - "go/scanner"; - "os"; + "fmt" + "go/ast" + "go/doc" + "go/parser" + "go/scanner" + "os" ) // A Cref refers to an expression of the form C.xxx in the AST. type Cref struct { - Name string; - Expr *ast.Expr; - Context string; // "type", "expr", or "call" - TypeName bool; // whether xxx is a C type name - Type *Type; // the type of xxx - FuncType *FuncType; + Name string + Expr *ast.Expr + Context string // "type", "expr", or "call" + TypeName bool // whether xxx is a C type name + Type *Type // the type of xxx + FuncType *FuncType } // A Prog collects information about a cgo program. type Prog struct { - AST *ast.File; // parsed AST - Preamble string; // C preamble (doc comment on import "C") - PackagePath string; - Package string; - Crefs []*Cref; - Typedef map[string]ast.Expr; - Vardef map[string]*Type; - Funcdef map[string]*FuncType; - PtrSize int64; - GccOptions []string; + AST *ast.File // parsed AST + Preamble string // C preamble (doc comment on import "C") + PackagePath string + Package string + Crefs []*Cref + Typedef map[string]ast.Expr + Vardef map[string]*Type + Funcdef map[string]*FuncType + PtrSize int64 + GccOptions []string } // A Type collects information about a type in both the C and Go worlds. type Type struct { - Size int64; - Align int64; - C string; - Go ast.Expr; + Size int64 + Align int64 + C string + Go ast.Expr } // A FuncType collects information about a function type in both the C and Go worlds. type FuncType struct { - Params []*Type; - Result *Type; - Go *ast.FuncType; + Params []*Type + Result *Type + Go *ast.FuncType } func openProg(name string) *Prog { - p := new(Prog); - var err os.Error; - p.AST, err = parser.ParsePkgFile("", name, parser.ParseComments); + p := new(Prog) + var err os.Error + p.AST, err = parser.ParsePkgFile("", name, parser.ParseComments) if err != nil { if list, ok := err.(scanner.ErrorList); ok { // If err is a scanner.ErrorList, its String will print just @@ -67,32 +67,32 @@ func openProg(name string) *Prog { for _, e := range list { fmt.Fprintln(os.Stderr, e) } - os.Exit(2); + os.Exit(2) } - fatal("parsing %s: %s", name, err); + fatal("parsing %s: %s", name, err) } - p.Package = p.AST.Name.Value; + p.Package = p.AST.Name.Value // Find the import "C" line and get any extra C preamble. // Delete the import "C" line along the way. - sawC := false; - w := 0; + sawC := false + w := 0 for _, decl := range p.AST.Decls { - d, ok := decl.(*ast.GenDecl); + d, ok := decl.(*ast.GenDecl) if !ok { - p.AST.Decls[w] = decl; - w++; - continue; + p.AST.Decls[w] = decl + w++ + continue } - ws := 0; + ws := 0 for _, spec := range d.Specs { - s, ok := spec.(*ast.ImportSpec); + s, ok := spec.(*ast.ImportSpec) if !ok || len(s.Path) != 1 || string(s.Path[0].Value) != `"C"` { - d.Specs[ws] = spec; - ws++; - continue; + d.Specs[ws] = spec + ws++ + continue } - sawC = true; + sawC = true if s.Name != nil { error(s.Path[0].Pos(), `cannot rename import "C"`) } @@ -105,20 +105,20 @@ func openProg(name string) *Prog { if ws == 0 { continue } - d.Specs = d.Specs[0:ws]; - p.AST.Decls[w] = d; - w++; + d.Specs = d.Specs[0:ws] + p.AST.Decls[w] = d + w++ } - p.AST.Decls = p.AST.Decls[0:w]; + p.AST.Decls = p.AST.Decls[0:w] if !sawC { error(noPos, `cannot find import "C"`) } // Accumulate pointers to uses of C.x. - p.Crefs = make([]*Cref, 0, 8); - walk(p.AST, p, "prog"); - return p; + p.Crefs = make([]*Cref, 0, 8) + walk(p.AST, p, "prog") + return p } func walk(x interface{}, p *Prog, context string) { @@ -131,29 +131,29 @@ func walk(x interface{}, p *Prog, context string) { // so that we will be able to distinguish a "top-level C" // from a local C. if l, ok := sel.X.(*ast.Ident); ok && l.Value == "C" { - i := len(p.Crefs); + i := len(p.Crefs) if i >= cap(p.Crefs) { - new := make([]*Cref, 2*i); + new := make([]*Cref, 2*i) for j, v := range p.Crefs { new[j] = v } - p.Crefs = new; + p.Crefs = new } - p.Crefs = p.Crefs[0 : i+1]; + p.Crefs = p.Crefs[0 : i+1] p.Crefs[i] = &Cref{ Name: sel.Sel.Value, Expr: n, Context: context, - }; - break; + } + break } } - walk(*n, p, context); + walk(*n, p, context) // everything else just recurs default: - error(noPos, "unexpected type %T in walk", x); - panic(); + error(noPos, "unexpected type %T in walk", x) + panic() case nil: @@ -166,54 +166,54 @@ func walk(x interface{}, p *Prog, context string) { case *ast.BasicLit: case *ast.StringList: case *ast.FuncLit: - walk(n.Type, p, "type"); - walk(n.Body, p, "stmt"); + walk(n.Type, p, "type") + walk(n.Body, p, "stmt") case *ast.CompositeLit: - walk(&n.Type, p, "type"); - walk(n.Elts, p, "expr"); + walk(&n.Type, p, "type") + walk(n.Elts, p, "expr") case *ast.ParenExpr: walk(&n.X, p, context) case *ast.SelectorExpr: walk(&n.X, p, "selector") case *ast.IndexExpr: - walk(&n.X, p, "expr"); - walk(&n.Index, p, "expr"); + walk(&n.X, p, "expr") + walk(&n.Index, p, "expr") case *ast.SliceExpr: - walk(&n.X, p, "expr"); - walk(&n.Index, p, "expr"); + walk(&n.X, p, "expr") + walk(&n.Index, p, "expr") if n.End != nil { walk(&n.End, p, "expr") } case *ast.TypeAssertExpr: - walk(&n.X, p, "expr"); - walk(&n.Type, p, "type"); + walk(&n.X, p, "expr") + walk(&n.Type, p, "type") case *ast.CallExpr: - walk(&n.Fun, p, "call"); - walk(n.Args, p, "expr"); + walk(&n.Fun, p, "call") + walk(n.Args, p, "expr") case *ast.StarExpr: walk(&n.X, p, context) case *ast.UnaryExpr: walk(&n.X, p, "expr") case *ast.BinaryExpr: - walk(&n.X, p, "expr"); - walk(&n.Y, p, "expr"); + walk(&n.X, p, "expr") + walk(&n.Y, p, "expr") case *ast.KeyValueExpr: - walk(&n.Key, p, "expr"); - walk(&n.Value, p, "expr"); + walk(&n.Key, p, "expr") + walk(&n.Value, p, "expr") case *ast.ArrayType: - walk(&n.Len, p, "expr"); - walk(&n.Elt, p, "type"); + walk(&n.Len, p, "expr") + walk(&n.Elt, p, "type") case *ast.StructType: walk(n.Fields, p, "field") case *ast.FuncType: - walk(n.Params, p, "field"); - walk(n.Results, p, "field"); + walk(n.Params, p, "field") + walk(n.Results, p, "field") case *ast.InterfaceType: walk(n.Methods, p, "field") case *ast.MapType: - walk(&n.Key, p, "type"); - walk(&n.Value, p, "type"); + walk(&n.Key, p, "type") + walk(&n.Value, p, "type") case *ast.ChanType: walk(&n.Value, p, "type") @@ -228,8 +228,8 @@ func walk(x interface{}, p *Prog, context string) { case *ast.IncDecStmt: walk(&n.X, p, "expr") case *ast.AssignStmt: - walk(n.Lhs, p, "expr"); - walk(n.Rhs, p, "expr"); + walk(n.Lhs, p, "expr") + walk(n.Rhs, p, "expr") case *ast.GoStmt: walk(n.Call, p, "expr") case *ast.DeferStmt: @@ -240,45 +240,45 @@ func walk(x interface{}, p *Prog, context string) { case *ast.BlockStmt: walk(n.List, p, "stmt") case *ast.IfStmt: - walk(n.Init, p, "stmt"); - walk(&n.Cond, p, "expr"); - walk(n.Body, p, "stmt"); - walk(n.Else, p, "stmt"); + walk(n.Init, p, "stmt") + walk(&n.Cond, p, "expr") + walk(n.Body, p, "stmt") + walk(n.Else, p, "stmt") case *ast.CaseClause: - walk(n.Values, p, "expr"); - walk(n.Body, p, "stmt"); + walk(n.Values, p, "expr") + walk(n.Body, p, "stmt") case *ast.SwitchStmt: - walk(n.Init, p, "stmt"); - walk(&n.Tag, p, "expr"); - walk(n.Body, p, "stmt"); + walk(n.Init, p, "stmt") + walk(&n.Tag, p, "expr") + walk(n.Body, p, "stmt") case *ast.TypeCaseClause: - walk(n.Types, p, "type"); - walk(n.Body, p, "stmt"); + walk(n.Types, p, "type") + walk(n.Body, p, "stmt") case *ast.TypeSwitchStmt: - walk(n.Init, p, "stmt"); - walk(n.Assign, p, "stmt"); - walk(n.Body, p, "stmt"); + walk(n.Init, p, "stmt") + walk(n.Assign, p, "stmt") + walk(n.Body, p, "stmt") case *ast.CommClause: - walk(n.Lhs, p, "expr"); - walk(n.Rhs, p, "expr"); - walk(n.Body, p, "stmt"); + walk(n.Lhs, p, "expr") + walk(n.Rhs, p, "expr") + walk(n.Body, p, "stmt") case *ast.SelectStmt: walk(n.Body, p, "stmt") case *ast.ForStmt: - walk(n.Init, p, "stmt"); - walk(&n.Cond, p, "expr"); - walk(n.Post, p, "stmt"); - walk(n.Body, p, "stmt"); + walk(n.Init, p, "stmt") + walk(&n.Cond, p, "expr") + walk(n.Post, p, "stmt") + walk(n.Body, p, "stmt") case *ast.RangeStmt: - walk(&n.Key, p, "expr"); - walk(&n.Value, p, "expr"); - walk(&n.X, p, "expr"); - walk(n.Body, p, "stmt"); + walk(&n.Key, p, "expr") + walk(&n.Value, p, "expr") + walk(&n.X, p, "expr") + walk(n.Body, p, "stmt") case *ast.ImportSpec: case *ast.ValueSpec: - walk(&n.Type, p, "type"); - walk(n.Values, p, "expr"); + walk(&n.Type, p, "type") + walk(n.Values, p, "expr") case *ast.TypeSpec: walk(&n.Type, p, "type") @@ -289,7 +289,7 @@ func walk(x interface{}, p *Prog, context string) { if n.Recv != nil { walk(n.Recv, p, "field") } - walk(n.Type, p, "type"); + walk(n.Type, p, "type") if n.Body != nil { walk(n.Body, p, "stmt") } diff --git a/src/cmd/cgo/gcc.go b/src/cmd/cgo/gcc.go index 7d377db54..c42cb7300 100644 --- a/src/cmd/cgo/gcc.go +++ b/src/cmd/cgo/gcc.go @@ -8,30 +8,30 @@ package main import ( - "bytes"; - "debug/dwarf"; - "debug/elf"; - "debug/macho"; - "fmt"; - "go/ast"; - "go/token"; - "os"; - "strconv"; - "strings"; + "bytes" + "debug/dwarf" + "debug/elf" + "debug/macho" + "fmt" + "go/ast" + "go/token" + "os" + "strconv" + "strings" ) func (p *Prog) loadDebugInfo() { // Construct a slice of unique names from p.Crefs. - m := make(map[string]int); + m := make(map[string]int) for _, c := range p.Crefs { m[c.Name] = -1 } - names := make([]string, 0, len(m)); + names := make([]string, 0, len(m)) for name, _ := range m { - i := len(names); - names = names[0 : i+1]; - names[i] = name; - m[name] = i; + i := len(names) + names = names[0 : i+1] + names[i] = name + m[name] = i } // Coerce gcc into telling us whether each name is @@ -46,18 +46,18 @@ func (p *Prog) loadDebugInfo() { // x.c:2: error: 'name' undeclared (first use in this function) // A line number directive causes the line number to // correspond to the index in the names array. - var b bytes.Buffer; - b.WriteString(p.Preamble); - b.WriteString("void f(void) {\n"); - b.WriteString("#line 0 \"cgo-test\"\n"); + var b bytes.Buffer + b.WriteString(p.Preamble) + b.WriteString("void f(void) {\n") + b.WriteString("#line 0 \"cgo-test\"\n") for _, n := range names { - b.WriteString(n); - b.WriteString(";\n"); + b.WriteString(n) + b.WriteString(";\n") } - b.WriteString("}\n"); + b.WriteString("}\n") - kind := make(map[string]string); - _, stderr := p.gccDebug(b.Bytes()); + kind := make(map[string]string) + _, stderr := p.gccDebug(b.Bytes()) if stderr == "" { fatal("gcc produced no output") } @@ -65,16 +65,16 @@ func (p *Prog) loadDebugInfo() { if len(line) < 9 || line[0:9] != "cgo-test:" { continue } - line = line[9:]; - colon := strings.Index(line, ":"); + line = line[9:] + colon := strings.Index(line, ":") if colon < 0 { continue } - i, err := strconv.Atoi(line[0:colon]); + i, err := strconv.Atoi(line[0:colon]) if err != nil { continue } - what := ""; + what := "" switch { default: continue @@ -88,7 +88,7 @@ func (p *Prog) loadDebugInfo() { if old, ok := kind[names[i]]; ok && old != what { error(noPos, "inconsistent gcc output about C.%s", names[i]) } - kind[names[i]] = what; + kind[names[i]] = what } for _, n := range names { if _, ok := kind[n]; !ok { @@ -108,21 +108,21 @@ func (p *Prog) loadDebugInfo() { // typeof(names[i]) *__cgo__i; // for each entry in names and then dereference the type we // learn for __cgo__i. - b.Reset(); - b.WriteString(p.Preamble); + b.Reset() + b.WriteString(p.Preamble) for i, n := range names { fmt.Fprintf(&b, "typeof(%s) *__cgo__%d;\n", n, i) } - d, stderr := p.gccDebug(b.Bytes()); + d, stderr := p.gccDebug(b.Bytes()) if d == nil { fatal("gcc failed:\n%s\non input:\n%s", stderr, b.Bytes()) } // Scan DWARF info for top-level TagVariable entries with AttrName __cgo__i. - types := make([]dwarf.Type, len(names)); - r := d.Reader(); + types := make([]dwarf.Type, len(names)) + r := d.Reader() for { - e, err := r.Next(); + e, err := r.Next() if err != nil { fatal("reading DWARF entry: %s", err) } @@ -132,27 +132,27 @@ func (p *Prog) loadDebugInfo() { if e.Tag != dwarf.TagVariable { goto Continue } - name, _ := e.Val(dwarf.AttrName).(string); - typOff, _ := e.Val(dwarf.AttrType).(dwarf.Offset); + name, _ := e.Val(dwarf.AttrName).(string) + typOff, _ := e.Val(dwarf.AttrType).(dwarf.Offset) if name == "" || typOff == 0 { fatal("malformed DWARF TagVariable entry") } if !strings.HasPrefix(name, "__cgo__") { goto Continue } - typ, err := d.Type(typOff); + typ, err := d.Type(typOff) if err != nil { fatal("loading DWARF type: %s", err) } - t, ok := typ.(*dwarf.PtrType); + t, ok := typ.(*dwarf.PtrType) if !ok || t == nil { fatal("internal error: %s has non-pointer type", name) } - i, err := strconv.Atoi(name[7:]); + i, err := strconv.Atoi(name[7:]) if err != nil { fatal("malformed __cgo__ name: %s", name) } - types[i] = t.Type; + types[i] = t.Type Continue: if e.Tag != dwarf.TagCompileUnit { @@ -161,132 +161,132 @@ func (p *Prog) loadDebugInfo() { } // Record types and typedef information in Crefs. - var conv typeConv; - conv.Init(p.PtrSize); + var conv typeConv + conv.Init(p.PtrSize) for _, c := range p.Crefs { - i := m[c.Name]; - c.TypeName = kind[c.Name] == "type"; - f, fok := types[i].(*dwarf.FuncType); + i := m[c.Name] + c.TypeName = kind[c.Name] == "type" + f, fok := types[i].(*dwarf.FuncType) if c.Context == "call" && !c.TypeName && fok { c.FuncType = conv.FuncType(f) } else { c.Type = conv.Type(types[i]) } } - p.Typedef = conv.typedef; + p.Typedef = conv.typedef } func concat(a, b []string) []string { - c := make([]string, len(a)+len(b)); + c := make([]string, len(a)+len(b)) for i, s := range a { c[i] = s } for i, s := range b { c[i+len(a)] = s } - return c; + return c } // gccDebug runs gcc -gdwarf-2 over the C program stdin and // returns the corresponding DWARF data and any messages // printed to standard error. func (p *Prog) gccDebug(stdin []byte) (*dwarf.Data, string) { - machine := "-m32"; + machine := "-m32" if p.PtrSize == 8 { machine = "-m64" } - tmp := "_cgo_.o"; + tmp := "_cgo_.o" base := []string{ "gcc", machine, - "-Wall", // many warnings - "-Werror", // warnings are errors - "-o" + tmp, // write object to tmp - "-gdwarf-2", // generate DWARF v2 debugging symbols - "-c", // do not link - "-xc", // input language is C - "-", // read input from standard input - }; - _, stderr, ok := run(stdin, concat(base, p.GccOptions)); + "-Wall", // many warnings + "-Werror", // warnings are errors + "-o" + tmp, // write object to tmp + "-gdwarf-2", // generate DWARF v2 debugging symbols + "-c", // do not link + "-xc", // input language is C + "-", // read input from standard input + } + _, stderr, ok := run(stdin, concat(base, p.GccOptions)) if !ok { return nil, string(stderr) } // Try to parse f as ELF and Mach-O and hope one works. var f interface { - DWARF() (*dwarf.Data, os.Error); + DWARF() (*dwarf.Data, os.Error) } - var err os.Error; + var err os.Error if f, err = elf.Open(tmp); err != nil { if f, err = macho.Open(tmp); err != nil { fatal("cannot parse gcc output %s as ELF or Mach-O object", tmp) } } - d, err := f.DWARF(); + d, err := f.DWARF() if err != nil { fatal("cannot load DWARF debug information from %s: %s", tmp, err) } - return d, ""; + return d, "" } // A typeConv is a translator from dwarf types to Go types // with equivalent memory layout. type typeConv struct { // Cache of already-translated or in-progress types. - m map[dwarf.Type]*Type; - typedef map[string]ast.Expr; + m map[dwarf.Type]*Type + typedef map[string]ast.Expr // Predeclared types. - byte ast.Expr; // denotes padding - int8, int16, int32, int64 ast.Expr; - uint8, uint16, uint32, uint64, uintptr ast.Expr; - float32, float64 ast.Expr; - void ast.Expr; - unsafePointer ast.Expr; - string ast.Expr; + byte ast.Expr // denotes padding + int8, int16, int32, int64 ast.Expr + uint8, uint16, uint32, uint64, uintptr ast.Expr + float32, float64 ast.Expr + void ast.Expr + unsafePointer ast.Expr + string ast.Expr - ptrSize int64; + ptrSize int64 - tagGen int; + tagGen int } func (c *typeConv) Init(ptrSize int64) { - c.ptrSize = ptrSize; - c.m = make(map[dwarf.Type]*Type); - c.typedef = make(map[string]ast.Expr); - c.byte = c.Ident("byte"); - c.int8 = c.Ident("int8"); - c.int16 = c.Ident("int16"); - c.int32 = c.Ident("int32"); - c.int64 = c.Ident("int64"); - c.uint8 = c.Ident("uint8"); - c.uint16 = c.Ident("uint16"); - c.uint32 = c.Ident("uint32"); - c.uint64 = c.Ident("uint64"); - c.uintptr = c.Ident("uintptr"); - c.float32 = c.Ident("float32"); - c.float64 = c.Ident("float64"); - c.unsafePointer = c.Ident("unsafe.Pointer"); - c.void = c.Ident("void"); - c.string = c.Ident("string"); + c.ptrSize = ptrSize + c.m = make(map[dwarf.Type]*Type) + c.typedef = make(map[string]ast.Expr) + c.byte = c.Ident("byte") + c.int8 = c.Ident("int8") + c.int16 = c.Ident("int16") + c.int32 = c.Ident("int32") + c.int64 = c.Ident("int64") + c.uint8 = c.Ident("uint8") + c.uint16 = c.Ident("uint16") + c.uint32 = c.Ident("uint32") + c.uint64 = c.Ident("uint64") + c.uintptr = c.Ident("uintptr") + c.float32 = c.Ident("float32") + c.float64 = c.Ident("float64") + c.unsafePointer = c.Ident("unsafe.Pointer") + c.void = c.Ident("void") + c.string = c.Ident("string") } // base strips away qualifiers and typedefs to get the underlying type func base(dt dwarf.Type) dwarf.Type { for { if d, ok := dt.(*dwarf.QualType); ok { - dt = d.Type; - continue; + dt = d.Type + continue } if d, ok := dt.(*dwarf.TypedefType); ok { - dt = d.Type; - continue; + dt = d.Type + continue } - break; + break } - return dt; + return dt } // Map from dwarf text names to aliases we use in package "C". @@ -308,22 +308,22 @@ func (c *typeConv) Type(dtype dwarf.Type) *Type { if t.Go == nil { fatal("type conversion loop at %s", dtype) } - return t; + return t } - t := new(Type); - t.Size = dtype.Size(); - t.Align = -1; - t.C = dtype.Common().Name; - c.m[dtype] = t; + t := new(Type) + t.Size = dtype.Size() + t.Align = -1 + t.C = dtype.Common().Name + c.m[dtype] = t if t.Size < 0 { // Unsized types are [0]byte - t.Size = 0; - t.Go = c.Opaque(0); + t.Size = 0 + t.Go = c.Opaque(0) if t.C == "" { t.C = "void" } - return t; + return t } switch dt := dtype.(type) { @@ -334,30 +334,30 @@ func (c *typeConv) Type(dtype dwarf.Type) *Type { if t.Size != c.ptrSize { fatal("unexpected: %d-byte address type - %s", t.Size, dtype) } - t.Go = c.uintptr; - t.Align = t.Size; + t.Go = c.uintptr + t.Align = t.Size case *dwarf.ArrayType: if dt.StrideBitSize > 0 { // Cannot represent bit-sized elements in Go. - t.Go = c.Opaque(t.Size); - break; + t.Go = c.Opaque(t.Size) + break } gt := &ast.ArrayType{ Len: c.intExpr(dt.Count), - }; - t.Go = gt; // publish before recursive call - sub := c.Type(dt.Type); - t.Align = sub.Align; - gt.Elt = sub.Go; - t.C = fmt.Sprintf("typeof(%s[%d])", sub.C, dt.Count); + } + t.Go = gt // publish before recursive call + sub := c.Type(dt.Type) + t.Align = sub.Align + gt.Elt = sub.Go + t.C = fmt.Sprintf("typeof(%s[%d])", sub.C, dt.Count) case *dwarf.CharType: if t.Size != 1 { fatal("unexpected: %d-byte char type - %s", t.Size, dtype) } - t.Go = c.int8; - t.Align = 1; + t.Go = c.int8 + t.Align = 1 case *dwarf.EnumType: switch t.Size { @@ -375,7 +375,7 @@ func (c *typeConv) Type(dtype dwarf.Type) *Type { if t.Align = t.Size; t.Align >= c.ptrSize { t.Align = c.ptrSize } - t.C = "enum " + dt.EnumName; + t.C = "enum " + dt.EnumName case *dwarf.FloatType: switch t.Size { @@ -393,8 +393,8 @@ func (c *typeConv) Type(dtype dwarf.Type) *Type { case *dwarf.FuncType: // No attempt at translation: would enable calls // directly between worlds, but we need to moderate those. - t.Go = c.uintptr; - t.Align = c.ptrSize; + t.Go = c.uintptr + t.Align = c.ptrSize case *dwarf.IntType: if dt.BitSize > 0 { @@ -417,52 +417,52 @@ func (c *typeConv) Type(dtype dwarf.Type) *Type { } case *dwarf.PtrType: - t.Align = c.ptrSize; + t.Align = c.ptrSize // Translate void* as unsafe.Pointer if _, ok := base(dt.Type).(*dwarf.VoidType); ok { - t.Go = c.unsafePointer; - t.C = "void*"; - break; + t.Go = c.unsafePointer + t.C = "void*" + break } - gt := &ast.StarExpr{}; - t.Go = gt; // publish before recursive call - sub := c.Type(dt.Type); - gt.X = sub.Go; - t.C = sub.C + "*"; + gt := &ast.StarExpr{} + t.Go = gt // publish before recursive call + sub := c.Type(dt.Type) + gt.X = sub.Go + t.C = sub.C + "*" case *dwarf.QualType: // Ignore qualifier. - t = c.Type(dt.Type); - c.m[dtype] = t; - return t; + t = c.Type(dt.Type) + c.m[dtype] = t + return t case *dwarf.StructType: // Convert to Go struct, being careful about alignment. // Have to give it a name to simulate C "struct foo" references. - tag := dt.StructName; + tag := dt.StructName if tag == "" { - tag = "__" + strconv.Itoa(c.tagGen); - c.tagGen++; + tag = "__" + strconv.Itoa(c.tagGen) + c.tagGen++ } else if t.C == "" { t.C = dt.Kind + " " + tag } - name := c.Ident("_C" + dt.Kind + "_" + tag); - t.Go = name; // publish before recursive calls + name := c.Ident("_C" + dt.Kind + "_" + tag) + t.Go = name // publish before recursive calls switch dt.Kind { case "union", "class": - c.typedef[name.Value] = c.Opaque(t.Size); + c.typedef[name.Value] = c.Opaque(t.Size) if t.C == "" { t.C = fmt.Sprintf("typeof(unsigned char[%d])", t.Size) } case "struct": - g, csyntax, align := c.Struct(dt); + g, csyntax, align := c.Struct(dt) if t.C == "" { t.C = csyntax } - t.Align = align; - c.typedef[name.Value] = g; + t.Align = align + c.typedef[name.Value] = g } case *dwarf.TypedefType: @@ -471,16 +471,16 @@ func (c *typeConv) Type(dtype dwarf.Type) *Type { // Special C name for Go string type. // Knows string layout used by compilers: pointer plus length, // which rounds up to 2 pointers after alignment. - t.Go = c.string; - t.Size = c.ptrSize * 2; - t.Align = c.ptrSize; - break; - } - name := c.Ident("_C_" + dt.Name); - t.Go = name; // publish before recursive call - sub := c.Type(dt.Type); - t.Size = sub.Size; - t.Align = sub.Align; + t.Go = c.string + t.Size = c.ptrSize * 2 + t.Align = c.ptrSize + break + } + name := c.Ident("_C_" + dt.Name) + t.Go = name // publish before recursive call + sub := c.Type(dt.Type) + t.Size = sub.Size + t.Align = sub.Align if _, ok := c.typedef[name.Value]; !ok { c.typedef[name.Value] = sub.Go } @@ -489,8 +489,8 @@ func (c *typeConv) Type(dtype dwarf.Type) *Type { if t.Size != 1 { fatal("unexpected: %d-byte uchar type - %s", t.Size, dtype) } - t.Go = c.uint8; - t.Align = 1; + t.Go = c.uint8 + t.Align = 1 case *dwarf.UintType: if dt.BitSize > 0 { @@ -513,21 +513,21 @@ func (c *typeConv) Type(dtype dwarf.Type) *Type { } case *dwarf.VoidType: - t.Go = c.void; - t.C = "void"; + t.Go = c.void + t.C = "void" } switch dtype.(type) { case *dwarf.AddrType, *dwarf.CharType, *dwarf.IntType, *dwarf.FloatType, *dwarf.UcharType, *dwarf.UintType: - s := dtype.Common().Name; + s := dtype.Common().Name if s != "" { if ss, ok := cnameMap[s]; ok { s = ss } - s = strings.Join(strings.Split(s, " ", 0), ""); // strip spaces - name := c.Ident("_C_" + s); - c.typedef[name.Value] = t.Go; - t.Go = name; + s = strings.Join(strings.Split(s, " ", 0), "") // strip spaces + name := c.Ident("_C_" + s) + c.typedef[name.Value] = t.Go + t.Go = name } } @@ -535,13 +535,13 @@ func (c *typeConv) Type(dtype dwarf.Type) *Type { fatal("internal error: did not create C name for %s", dtype) } - return t; + return t } // FuncArg returns a Go type with the same memory layout as // dtype when used as the type of a C function argument. func (c *typeConv) FuncArg(dtype dwarf.Type) *Type { - t := c.Type(dtype); + t := c.Type(dtype) switch dt := dtype.(type) { case *dwarf.ArrayType: // Arrays are passed implicitly as pointers in C. @@ -565,14 +565,14 @@ func (c *typeConv) FuncArg(dtype dwarf.Type) *Type { } } } - return t; + return t } // FuncType returns the Go type analogous to dtype. // There is no guarantee about matching memory layout. func (c *typeConv) FuncType(dtype *dwarf.FuncType) *FuncType { - p := make([]*Type, len(dtype.ParamType)); - gp := make([]*ast.Field, len(dtype.ParamType)); + p := make([]*Type, len(dtype.ParamType)) + gp := make([]*ast.Field, len(dtype.ParamType)) for i, f := range dtype.ParamType { // gcc's DWARF generator outputs a single DotDotDotType parameter for // function pointers that specify no parameters (e.g. void @@ -580,17 +580,17 @@ func (c *typeConv) FuncType(dtype *dwarf.FuncType) *FuncType { // invalid according to ISO C anyway (i.e. void (*__cgo_1)(...) is not // legal). if _, ok := f.(*dwarf.DotDotDotType); ok && i == 0 { - p, gp = nil, nil; - break; + p, gp = nil, nil + break } - p[i] = c.FuncArg(f); - gp[i] = &ast.Field{Type: p[i].Go}; + p[i] = c.FuncArg(f) + gp[i] = &ast.Field{Type: p[i].Go} } - var r *Type; - var gr []*ast.Field; + var r *Type + var gr []*ast.Field if _, ok := dtype.ReturnType.(*dwarf.VoidType); !ok && dtype.ReturnType != nil { - r = c.Type(dtype.ReturnType); - gr = []*ast.Field{&ast.Field{Type: r.Go}}; + r = c.Type(dtype.ReturnType) + gr = []*ast.Field{&ast.Field{Type: r.Go}} } return &FuncType{ Params: p, @@ -599,11 +599,11 @@ func (c *typeConv) FuncType(dtype *dwarf.FuncType) *FuncType { Params: gp, Results: gr, }, - }; + } } // Identifier -func (c *typeConv) Ident(s string) *ast.Ident { return &ast.Ident{Value: s} } +func (c *typeConv) Ident(s string) *ast.Ident { return &ast.Ident{Value: s} } // Opaque type of n bytes. func (c *typeConv) Opaque(n int64) ast.Expr { @@ -623,17 +623,17 @@ func (c *typeConv) intExpr(n int64) ast.Expr { // Add padding of given size to fld. func (c *typeConv) pad(fld []*ast.Field, size int64) []*ast.Field { - n := len(fld); - fld = fld[0 : n+1]; - fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident("_")}, Type: c.Opaque(size)}; - return fld; + n := len(fld) + fld = fld[0 : n+1] + fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident("_")}, Type: c.Opaque(size)} + return fld } // Struct conversion func (c *typeConv) Struct(dt *dwarf.StructType) (expr *ast.StructType, csyntax string, align int64) { - csyntax = "struct { "; - fld := make([]*ast.Field, 0, 2*len(dt.Field)+1); // enough for padding around every field - off := int64(0); + csyntax = "struct { " + fld := make([]*ast.Field, 0, 2*len(dt.Field)+1) // enough for padding around every field + off := int64(0) // Mangle struct fields that happen to be named Go keywords into // _{keyword}. Create a map from C ident -> Go ident. The Go ident will @@ -641,51 +641,51 @@ func (c *typeConv) Struct(dt *dwarf.StructType) (expr *ast.StructType, csyntax s // the C-side will cause the Go-mangled version to be prefixed with _. // (e.g. in a struct with fields '_type' and 'type', the latter would be // rendered as '__type' in Go). - ident := make(map[string]string); - used := make(map[string]bool); + ident := make(map[string]string) + used := make(map[string]bool) for _, f := range dt.Field { - ident[f.Name] = f.Name; - used[f.Name] = true; + ident[f.Name] = f.Name + used[f.Name] = true } for cid, goid := range ident { if token.Lookup(strings.Bytes(goid)).IsKeyword() { // Avoid keyword - goid = "_" + goid; + goid = "_" + goid // Also avoid existing fields for _, exist := used[goid]; exist; _, exist = used[goid] { goid = "_" + goid } - used[goid] = true; - ident[cid] = goid; + used[goid] = true + ident[cid] = goid } } for _, f := range dt.Field { if f.ByteOffset > off { - fld = c.pad(fld, f.ByteOffset-off); - off = f.ByteOffset; + fld = c.pad(fld, f.ByteOffset-off) + off = f.ByteOffset } - t := c.Type(f.Type); - n := len(fld); - fld = fld[0 : n+1]; + t := c.Type(f.Type) + n := len(fld) + fld = fld[0 : n+1] - fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident(ident[f.Name])}, Type: t.Go}; - off += t.Size; - csyntax += t.C + " " + f.Name + "; "; + fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident(ident[f.Name])}, Type: t.Go} + off += t.Size + csyntax += t.C + " " + f.Name + "; " if t.Align > align { align = t.Align } } if off < dt.ByteSize { - fld = c.pad(fld, dt.ByteSize-off); - off = dt.ByteSize; + fld = c.pad(fld, dt.ByteSize-off) + off = dt.ByteSize } if off != dt.ByteSize { fatal("struct size calculation error") } - csyntax += "}"; - expr = &ast.StructType{Fields: fld}; - return; + csyntax += "}" + expr = &ast.StructType{Fields: fld} + return } diff --git a/src/cmd/cgo/main.go b/src/cmd/cgo/main.go index 8202b8e2b..373df3ba2 100644 --- a/src/cmd/cgo/main.go +++ b/src/cmd/cgo/main.go @@ -11,12 +11,12 @@ package main import ( - "fmt"; - "go/ast"; - "os"; + "fmt" + "go/ast" + "os" ) -func usage() { fmt.Fprint(os.Stderr, "usage: cgo [compiler options] file.go\n") } +func usage() { fmt.Fprint(os.Stderr, "usage: cgo [compiler options] file.go\n") } var ptrSizeMap = map[string]int64{ "386": 4, @@ -35,29 +35,29 @@ var expandName = map[string]string{ } func main() { - args := os.Args; + args := os.Args if len(args) < 2 { - usage(); - os.Exit(2); + usage() + os.Exit(2) } - gccOptions := args[1 : len(args)-1]; - input := args[len(args)-1]; + gccOptions := args[1 : len(args)-1] + input := args[len(args)-1] - arch := os.Getenv("GOARCH"); + arch := os.Getenv("GOARCH") if arch == "" { fatal("$GOARCH is not set") } - ptrSize, ok := ptrSizeMap[arch]; + ptrSize, ok := ptrSizeMap[arch] if !ok { fatal("unknown architecture %s", arch) } // Clear locale variables so gcc emits English errors [sic]. - os.Setenv("LANG", "en_US.UTF-8"); - os.Setenv("LC_ALL", "C"); - os.Setenv("LC_CTYPE", "C"); + os.Setenv("LANG", "en_US.UTF-8") + os.Setenv("LC_ALL", "C") + os.Setenv("LC_CTYPE", "C") - p := openProg(input); + p := openProg(input) for _, cref := range p.Crefs { // Convert C.ulong to C.unsigned long, etc. if expand, ok := expandName[cref.Name]; ok { @@ -65,42 +65,42 @@ func main() { } } - p.PtrSize = ptrSize; - p.Preamble = p.Preamble + "\n" + builtinProlog; - p.GccOptions = gccOptions; - p.loadDebugInfo(); - p.Vardef = make(map[string]*Type); - p.Funcdef = make(map[string]*FuncType); + p.PtrSize = ptrSize + p.Preamble = p.Preamble + "\n" + builtinProlog + p.GccOptions = gccOptions + p.loadDebugInfo() + p.Vardef = make(map[string]*Type) + p.Funcdef = make(map[string]*FuncType) for _, cref := range p.Crefs { switch cref.Context { case "call": if !cref.TypeName { // Is an actual function call. - *cref.Expr = &ast.Ident{Value: "_C_" + cref.Name}; - p.Funcdef[cref.Name] = cref.FuncType; - break; + *cref.Expr = &ast.Ident{Value: "_C_" + cref.Name} + p.Funcdef[cref.Name] = cref.FuncType + break } - *cref.Expr = cref.Type.Go; + *cref.Expr = cref.Type.Go case "expr": if cref.TypeName { error((*cref.Expr).Pos(), "type C.%s used as expression", cref.Name) } // Reference to C variable. // We declare a pointer and arrange to have it filled in. - *cref.Expr = &ast.StarExpr{X: &ast.Ident{Value: "_C_" + cref.Name}}; - p.Vardef[cref.Name] = cref.Type; + *cref.Expr = &ast.StarExpr{X: &ast.Ident{Value: "_C_" + cref.Name}} + p.Vardef[cref.Name] = cref.Type case "type": if !cref.TypeName { error((*cref.Expr).Pos(), "expression C.%s used as type", cref.Name) } - *cref.Expr = cref.Type.Go; + *cref.Expr = cref.Type.Go } } if nerrors > 0 { os.Exit(2) } - p.PackagePath = os.Getenv("CGOPKGPATH") + "/" + p.Package; - p.writeOutput(input); + p.PackagePath = os.Getenv("CGOPKGPATH") + "/" + p.Package + p.writeOutput(input) } diff --git a/src/cmd/cgo/out.go b/src/cmd/cgo/out.go index 297ffe40a..9c85bc598 100644 --- a/src/cmd/cgo/out.go +++ b/src/cmd/cgo/out.go @@ -5,78 +5,78 @@ package main import ( - "fmt"; - "go/ast"; - "go/printer"; - "os"; - "strings"; + "fmt" + "go/ast" + "go/printer" + "os" + "strings" ) func creat(name string) *os.File { - f, err := os.Open(name, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, 0666); + f, err := os.Open(name, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, 0666) if err != nil { fatal("%s", err) } - return f; + return f } // writeOutput creates output files to be compiled by 6g, 6c, and gcc. // (The comments here say 6g and 6c but the code applies to the 8 and 5 tools too.) func (p *Prog) writeOutput(srcfile string) { - pkgroot := os.Getenv("GOROOT") + "/pkg/" + os.Getenv("GOOS") + "_" + os.Getenv("GOARCH"); + pkgroot := os.Getenv("GOROOT") + "/pkg/" + os.Getenv("GOOS") + "_" + os.Getenv("GOARCH") - base := srcfile; + base := srcfile if strings.HasSuffix(base, ".go") { base = base[0 : len(base)-3] } - fgo1 := creat(base + ".cgo1.go"); - fgo2 := creat(base + ".cgo2.go"); - fc := creat(base + ".cgo3.c"); - fgcc := creat(base + ".cgo4.c"); + fgo1 := creat(base + ".cgo1.go") + fgo2 := creat(base + ".cgo2.go") + fc := creat(base + ".cgo3.c") + fgcc := creat(base + ".cgo4.c") // Write Go output: Go input with rewrites of C.xxx to _C_xxx. - fmt.Fprintf(fgo1, "// Created by cgo - DO NOT EDIT\n"); - fmt.Fprintf(fgo1, "//line %s:1\n", srcfile); - printer.Fprint(fgo1, p.AST); + fmt.Fprintf(fgo1, "// Created by cgo - DO NOT EDIT\n") + fmt.Fprintf(fgo1, "//line %s:1\n", srcfile) + printer.Fprint(fgo1, p.AST) // Write second Go output: definitions of _C_xxx. // In a separate file so that the import of "unsafe" does not // pollute the original file. - fmt.Fprintf(fgo2, "// Created by cgo - DO NOT EDIT\n"); - fmt.Fprintf(fgo2, "package %s\n\n", p.Package); - fmt.Fprintf(fgo2, "import \"unsafe\"\n\n"); - fmt.Fprintf(fgo2, "type _ unsafe.Pointer\n\n"); + fmt.Fprintf(fgo2, "// Created by cgo - DO NOT EDIT\n") + fmt.Fprintf(fgo2, "package %s\n\n", p.Package) + fmt.Fprintf(fgo2, "import \"unsafe\"\n\n") + fmt.Fprintf(fgo2, "type _ unsafe.Pointer\n\n") for name, def := range p.Typedef { - fmt.Fprintf(fgo2, "type %s ", name); - printer.Fprint(fgo2, def); - fmt.Fprintf(fgo2, "\n"); + fmt.Fprintf(fgo2, "type %s ", name) + printer.Fprint(fgo2, def) + fmt.Fprintf(fgo2, "\n") } - fmt.Fprintf(fgo2, "type _C_void [0]byte\n"); + fmt.Fprintf(fgo2, "type _C_void [0]byte\n") // While we process the vars and funcs, also write 6c and gcc output. // Gcc output starts with the preamble. - fmt.Fprintf(fgcc, "%s\n", p.Preamble); - fmt.Fprintf(fgcc, "%s\n", gccProlog); + fmt.Fprintf(fgcc, "%s\n", p.Preamble) + fmt.Fprintf(fgcc, "%s\n", gccProlog) - fmt.Fprintf(fc, cProlog, pkgroot, pkgroot, pkgroot, pkgroot, p.Package, p.Package); + fmt.Fprintf(fc, cProlog, pkgroot, pkgroot, pkgroot, pkgroot, p.Package, p.Package) for name, def := range p.Vardef { - fmt.Fprintf(fc, "#pragma dynld %s·_C_%s %s \"%s/%s_%s.so\"\n", p.Package, name, name, pkgroot, p.PackagePath, base); - fmt.Fprintf(fgo2, "var _C_%s ", name); - printer.Fprint(fgo2, &ast.StarExpr{X: def.Go}); - fmt.Fprintf(fgo2, "\n"); + fmt.Fprintf(fc, "#pragma dynld %s·_C_%s %s \"%s/%s_%s.so\"\n", p.Package, name, name, pkgroot, p.PackagePath, base) + fmt.Fprintf(fgo2, "var _C_%s ", name) + printer.Fprint(fgo2, &ast.StarExpr{X: def.Go}) + fmt.Fprintf(fgo2, "\n") } - fmt.Fprintf(fc, "\n"); + fmt.Fprintf(fc, "\n") for name, def := range p.Funcdef { // Go func declaration. d := &ast.FuncDecl{ Name: &ast.Ident{Value: "_C_" + name}, Type: def.Go, - }; - printer.Fprint(fgo2, d); - fmt.Fprintf(fgo2, "\n"); + } + printer.Fprint(fgo2, d) + fmt.Fprintf(fgo2, "\n") if name == "CString" || name == "GoString" { // The builtins are already defined in the C prolog. @@ -88,86 +88,86 @@ func (p *Prog) writeOutput(srcfile string) { // These assumptions are checked by the gccProlog. // Also assumes that 6c convention is to word-align the // input and output parameters. - structType := "struct {\n"; - off := int64(0); - npad := 0; + structType := "struct {\n" + off := int64(0) + npad := 0 for i, t := range def.Params { if off%t.Align != 0 { - pad := t.Align - off%t.Align; - structType += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad); - off += pad; - npad++; + pad := t.Align - off%t.Align + structType += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad) + off += pad + npad++ } - structType += fmt.Sprintf("\t\t%s p%d;\n", t.C, i); - off += t.Size; + structType += fmt.Sprintf("\t\t%s p%d;\n", t.C, i) + off += t.Size } if off%p.PtrSize != 0 { - pad := p.PtrSize - off%p.PtrSize; - structType += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad); - off += pad; - npad++; + pad := p.PtrSize - off%p.PtrSize + structType += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad) + off += pad + npad++ } if t := def.Result; t != nil { if off%t.Align != 0 { - pad := t.Align - off%t.Align; - structType += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad); - off += pad; - npad++; + pad := t.Align - off%t.Align + structType += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad) + off += pad + npad++ } - structType += fmt.Sprintf("\t\t%s r;\n", t.C); - off += t.Size; + structType += fmt.Sprintf("\t\t%s r;\n", t.C) + off += t.Size } if off%p.PtrSize != 0 { - pad := p.PtrSize - off%p.PtrSize; - structType += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad); - off += pad; - npad++; + pad := p.PtrSize - off%p.PtrSize + structType += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad) + off += pad + npad++ } if len(def.Params) == 0 && def.Result == nil { - structType += "\t\tchar unused;\n"; // avoid empty struct - off++; + structType += "\t\tchar unused;\n" // avoid empty struct + off++ } - structType += "\t}"; - argSize := off; + structType += "\t}" + argSize := off // C wrapper calls into gcc, passing a pointer to the argument frame. // Also emit #pragma to get a pointer to the gcc wrapper. - fmt.Fprintf(fc, "#pragma dynld _cgo_%s _cgo_%s \"%s/%s_%s.so\"\n", name, name, pkgroot, p.PackagePath, base); - fmt.Fprintf(fc, "void (*_cgo_%s)(void*);\n", name); - fmt.Fprintf(fc, "\n"); - fmt.Fprintf(fc, "void\n"); - fmt.Fprintf(fc, "%s·_C_%s(struct{uint8 x[%d];}p)\n", p.Package, name, argSize); - fmt.Fprintf(fc, "{\n"); - fmt.Fprintf(fc, "\tcgocall(_cgo_%s, &p);\n", name); - fmt.Fprintf(fc, "}\n"); - fmt.Fprintf(fc, "\n"); + fmt.Fprintf(fc, "#pragma dynld _cgo_%s _cgo_%s \"%s/%s_%s.so\"\n", name, name, pkgroot, p.PackagePath, base) + fmt.Fprintf(fc, "void (*_cgo_%s)(void*);\n", name) + fmt.Fprintf(fc, "\n") + fmt.Fprintf(fc, "void\n") + fmt.Fprintf(fc, "%s·_C_%s(struct{uint8 x[%d];}p)\n", p.Package, name, argSize) + fmt.Fprintf(fc, "{\n") + fmt.Fprintf(fc, "\tcgocall(_cgo_%s, &p);\n", name) + fmt.Fprintf(fc, "}\n") + fmt.Fprintf(fc, "\n") // Gcc wrapper unpacks the C argument struct // and calls the actual C function. - fmt.Fprintf(fgcc, "void\n"); - fmt.Fprintf(fgcc, "_cgo_%s(void *v)\n", name); - fmt.Fprintf(fgcc, "{\n"); - fmt.Fprintf(fgcc, "\t%s *a = v;\n", structType); - fmt.Fprintf(fgcc, "\t"); + fmt.Fprintf(fgcc, "void\n") + fmt.Fprintf(fgcc, "_cgo_%s(void *v)\n", name) + fmt.Fprintf(fgcc, "{\n") + fmt.Fprintf(fgcc, "\t%s *a = v;\n", structType) + fmt.Fprintf(fgcc, "\t") if def.Result != nil { fmt.Fprintf(fgcc, "a->r = ") } - fmt.Fprintf(fgcc, "%s(", name); + fmt.Fprintf(fgcc, "%s(", name) for i := range def.Params { if i > 0 { fmt.Fprintf(fgcc, ", ") } - fmt.Fprintf(fgcc, "a->p%d", i); + fmt.Fprintf(fgcc, "a->p%d", i) } - fmt.Fprintf(fgcc, ");\n"); - fmt.Fprintf(fgcc, "}\n"); - fmt.Fprintf(fgcc, "\n"); + fmt.Fprintf(fgcc, ");\n") + fmt.Fprintf(fgcc, "}\n") + fmt.Fprintf(fgcc, "\n") } - fgo1.Close(); - fgo2.Close(); - fc.Close(); - fgcc.Close(); + fgo1.Close() + fgo2.Close() + fc.Close() + fgcc.Close() } const gccProlog = ` diff --git a/src/cmd/cgo/util.go b/src/cmd/cgo/util.go index 176e9528e..782efddf4 100644 --- a/src/cmd/cgo/util.go +++ b/src/cmd/cgo/util.go @@ -5,11 +5,11 @@ package main import ( - "exec"; - "fmt"; - "go/token"; - "io/ioutil"; - "os"; + "exec" + "fmt" + "go/token" + "io/ioutil" + "os" ) // A ByteReaderAt implements io.ReadAt using a slice of bytes. @@ -19,76 +19,76 @@ func (r ByteReaderAt) ReadAt(p []byte, off int64) (n int, err os.Error) { if off >= int64(len(r)) || off < 0 { return 0, os.EOF } - return copy(p, r[off:]), nil; + return copy(p, r[off:]), nil } // run runs the command argv, feeding in stdin on standard input. // It returns the output to standard output and standard error. // ok indicates whether the command exited successfully. func run(stdin []byte, argv []string) (stdout, stderr []byte, ok bool) { - cmd, err := exec.LookPath(argv[0]); + cmd, err := exec.LookPath(argv[0]) if err != nil { fatal("exec %s: %s", argv[0], err) } - r0, w0, err := os.Pipe(); + r0, w0, err := os.Pipe() if err != nil { fatal("%s", err) } - r1, w1, err := os.Pipe(); + r1, w1, err := os.Pipe() if err != nil { fatal("%s", err) } - r2, w2, err := os.Pipe(); + r2, w2, err := os.Pipe() if err != nil { fatal("%s", err) } - pid, err := os.ForkExec(cmd, argv, os.Environ(), "", []*os.File{r0, w1, w2}); + pid, err := os.ForkExec(cmd, argv, os.Environ(), "", []*os.File{r0, w1, w2}) if err != nil { fatal("%s", err) } - r0.Close(); - w1.Close(); - w2.Close(); - c := make(chan bool); + r0.Close() + w1.Close() + w2.Close() + c := make(chan bool) go func() { - w0.Write(stdin); - w0.Close(); - c <- true; - }(); - var xstdout []byte; // TODO(rsc): delete after 6g can take address of out parameter + w0.Write(stdin) + w0.Close() + c <- true + }() + var xstdout []byte // TODO(rsc): delete after 6g can take address of out parameter go func() { - xstdout, _ = ioutil.ReadAll(r1); - r1.Close(); - c <- true; - }(); - stderr, _ = ioutil.ReadAll(r2); - r2.Close(); - <-c; - <-c; - stdout = xstdout; + xstdout, _ = ioutil.ReadAll(r1) + r1.Close() + c <- true + }() + stderr, _ = ioutil.ReadAll(r2) + r2.Close() + <-c + <-c + stdout = xstdout - w, err := os.Wait(pid, 0); + w, err := os.Wait(pid, 0) if err != nil { fatal("%s", err) } - ok = w.Exited() && w.ExitStatus() == 0; - return; + ok = w.Exited() && w.ExitStatus() == 0 + return } // Die with an error message. func fatal(msg string, args ...) { - fmt.Fprintf(os.Stderr, msg+"\n", args); - os.Exit(2); + fmt.Fprintf(os.Stderr, msg+"\n", args) + os.Exit(2) } var nerrors int var noPos token.Position func error(pos token.Position, msg string, args ...) { - nerrors++; + nerrors++ if pos.IsValid() { fmt.Fprintf(os.Stderr, "%s: ", pos) } - fmt.Fprintf(os.Stderr, msg, args); - fmt.Fprintf(os.Stderr, "\n"); + fmt.Fprintf(os.Stderr, msg, args) + fmt.Fprintf(os.Stderr, "\n") } diff --git a/src/cmd/ebnflint/ebnflint.go b/src/cmd/ebnflint/ebnflint.go index 4904780a3..9d391249d 100644 --- a/src/cmd/ebnflint/ebnflint.go +++ b/src/cmd/ebnflint/ebnflint.go @@ -5,15 +5,15 @@ package main import ( - "bytes"; - "ebnf"; - "flag"; - "fmt"; - "go/scanner"; - "io/ioutil"; - "os"; - "path"; - "strings"; + "bytes" + "ebnf" + "flag" + "fmt" + "go/scanner" + "io/ioutil" + "os" + "path" + "strings" ) @@ -21,29 +21,29 @@ 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); + fmt.Fprintf(os.Stderr, "usage: ebnflint [flags] [filename]\n") + flag.PrintDefaults() + os.Exit(1) } // Markers around EBNF sections in .html files var ( - open = strings.Bytes(`<pre class="ebnf">`); - close = strings.Bytes(`</pre>`); + open = strings.Bytes(`<pre class="ebnf">`) + close = strings.Bytes(`</pre>`) ) func extractEBNF(src []byte) []byte { - var buf bytes.Buffer; + var buf bytes.Buffer for { // i = beginning of EBNF text - i := bytes.Index(src, open); + i := bytes.Index(src, open) if i < 0 { - break // no EBNF found - we are done + break // no EBNF found - we are done } - i += len(open); + i += len(open) // write as many newlines as found in the excluded text // to maintain correct line numbers in error messages @@ -54,27 +54,27 @@ func extractEBNF(src []byte) []byte { } // j = end of EBNF text (or end of source) - j := bytes.Index(src[i:], close); // close marker + j := bytes.Index(src[i:], close) // close marker if j < 0 { j = len(src) - i } - j += i; + j += i // copy EBNF text - buf.Write(src[i:j]); + buf.Write(src[i:j]) // advance - src = src[j:]; + src = src[j:] } - return buf.Bytes(); + return buf.Bytes() } func main() { - flag.Parse(); + flag.Parse() - var filename string; + var filename string switch flag.NArg() { case 0: filename = "/dev/stdin" @@ -84,7 +84,7 @@ func main() { usage() } - src, err := ioutil.ReadFile(filename); + src, err := ioutil.ReadFile(filename) if err != nil { scanner.PrintError(os.Stderr, err) } @@ -93,7 +93,7 @@ func main() { src = extractEBNF(src) } - grammar, err := ebnf.Parse(filename, src); + grammar, err := ebnf.Parse(filename, src) if err != nil { scanner.PrintError(os.Stderr, err) } diff --git a/src/cmd/gc/runtime.go b/src/cmd/gc/runtime.go index baca93c8c..2e21d2511 100644 --- a/src/cmd/gc/runtime.go +++ b/src/cmd/gc/runtime.go @@ -84,7 +84,7 @@ func sliceslice1(old []any, lb int, width int) (ary []any) func sliceslice(old []any, lb int, hb int, width int) (ary []any) func slicearray(old *any, nel int, lb int, hb int, width int) (ary []any) -func closure() // has args, but compiler fills in +func closure() // has args, but compiler fills in // only used on 32-bit func int64div(int64, int64) int64 diff --git a/src/cmd/godoc/godoc.go b/src/cmd/godoc/godoc.go index 62258ba65..1e4eb1625 100644 --- a/src/cmd/godoc/godoc.go +++ b/src/cmd/godoc/godoc.go @@ -5,26 +5,26 @@ package main import ( - "bytes"; - "flag"; - "fmt"; - "go/ast"; - "go/doc"; - "go/parser"; - "go/printer"; - "go/token"; - "http"; - "io"; - "io/ioutil"; - "log"; - "os"; - pathutil "path"; - "strings"; - "sync"; - "template"; - "time"; - "unicode"; - "utf8"; + "bytes" + "flag" + "fmt" + "go/ast" + "go/doc" + "go/parser" + "go/printer" + "go/token" + "http" + "io" + "io/ioutil" + "log" + "os" + pathutil "path" + "strings" + "sync" + "template" + "time" + "unicode" + "utf8" ) @@ -34,24 +34,24 @@ import ( // An RWValue wraps a value and permits mutually exclusive // access to it and records the time the value was last set. type RWValue struct { - mutex sync.RWMutex; - value interface{}; - timestamp int64; // time of last set(), in seconds since epoch + mutex sync.RWMutex + value interface{} + timestamp int64 // time of last set(), in seconds since epoch } func (v *RWValue) set(value interface{}) { - v.mutex.Lock(); - v.value = value; - v.timestamp = time.Seconds(); - v.mutex.Unlock(); + v.mutex.Lock() + v.value = value + v.timestamp = time.Seconds() + v.mutex.Unlock() } func (v *RWValue) get() (interface{}, int64) { - v.mutex.RLock(); - defer v.mutex.RUnlock(); - return v.value, v.timestamp; + v.mutex.RLock() + defer v.mutex.RUnlock() + return v.value, v.timestamp } @@ -59,44 +59,44 @@ func (v *RWValue) get() (interface{}, int64) { // Globals type delayTime struct { - RWValue; + RWValue } func (dt *delayTime) backoff(max int) { - dt.mutex.Lock(); - v := dt.value.(int) * 2; + dt.mutex.Lock() + v := dt.value.(int) * 2 if v > max { v = max } - dt.value = v; - dt.mutex.Unlock(); + dt.value = v + dt.mutex.Unlock() } var ( - verbose = flag.Bool("v", false, "verbose mode"); + verbose = flag.Bool("v", false, "verbose mode") // file system roots - goroot string; - cmdroot = flag.String("cmdroot", "src/cmd", "root command source directory (if unrooted, relative to goroot)"); - pkgroot = flag.String("pkgroot", "src/pkg", "root package source directory (if unrooted, relative to goroot)"); - tmplroot = flag.String("tmplroot", "lib/godoc", "root template directory (if unrooted, relative to goroot)"); + goroot string + cmdroot = flag.String("cmdroot", "src/cmd", "root command source directory (if unrooted, relative to goroot)") + pkgroot = flag.String("pkgroot", "src/pkg", "root package source directory (if unrooted, relative to goroot)") + tmplroot = flag.String("tmplroot", "lib/godoc", "root template directory (if unrooted, relative to goroot)") // layout control - tabwidth = flag.Int("tabwidth", 4, "tab width"); + tabwidth = flag.Int("tabwidth", 4, "tab width") ) -var fsTree RWValue // *Directory tree of packages, updated with each sync +var fsTree RWValue // *Directory tree of packages, updated with each sync func init() { - goroot = os.Getenv("GOROOT"); + goroot = os.Getenv("GOROOT") if goroot == "" { goroot = pathutil.Join(os.Getenv("HOME"), "go") } - flag.StringVar(&goroot, "goroot", goroot, "Go root directory"); + flag.StringVar(&goroot, "goroot", goroot, "Go root directory") } @@ -105,14 +105,14 @@ func init() { func isGoFile(dir *os.Dir) bool { return dir.IsRegular() && - !strings.HasPrefix(dir.Name, ".") && // ignore .files + !strings.HasPrefix(dir.Name, ".") && // ignore .files pathutil.Ext(dir.Name) == ".go" } func isPkgFile(dir *os.Dir) bool { return isGoFile(dir) && - !strings.HasSuffix(dir.Name, "_test.go") // ignore test files + !strings.HasSuffix(dir.Name, "_test.go") // ignore test files } @@ -122,54 +122,54 @@ func isPkgDir(dir *os.Dir) bool { func pkgName(filename string) string { - file, err := parser.ParseFile(filename, nil, parser.PackageClauseOnly); + file, err := parser.ParseFile(filename, nil, parser.PackageClauseOnly) if err != nil || file == nil { return "" } - return file.Name.Value; + return file.Name.Value } func htmlEscape(s string) string { - var buf bytes.Buffer; - template.HTMLEscape(&buf, strings.Bytes(s)); - return buf.String(); + var buf bytes.Buffer + template.HTMLEscape(&buf, strings.Bytes(s)) + return buf.String() } func firstSentence(s string) string { - i := -1; // index+1 of first period - j := -1; // index+1 of first period that is followed by white space - prev := 'A'; + i := -1 // index+1 of first period + j := -1 // index+1 of first period that is followed by white space + prev := 'A' for k, ch := range s { - k1 := k + 1; + k1 := k + 1 if ch == '.' { if i < 0 { - i = k1 // first period + i = k1 // first period } if k1 < len(s) && s[k1] <= ' ' { if j < 0 { - j = k1 // first period followed by white space + j = k1 // first period followed by white space } if !unicode.IsUpper(prev) { - j = k1; - break; + j = k1 + break } } } - prev = ch; + prev = ch } if j < 0 { // use the next best period - j = i; + j = i if j < 0 { // no period at all, use the entire string j = len(s) } } - return s[0:j]; + return s[0:j] } @@ -177,11 +177,11 @@ func firstSentence(s string) string { // Package directories type Directory struct { - Depth int; - Path string; // includes Name - Name string; - Text string; // package documentation, if any - Dirs []*Directory; // subdirectories + Depth int + Path string // includes Name + Name string + Text string // package documentation, if any + Dirs []*Directory // subdirectories } @@ -193,22 +193,22 @@ func newDirTree(path, name string, depth, maxDepth int) *Directory { return &Directory{depth, path, name, "", nil} } - list, _ := ioutil.ReadDir(path); // ignore errors + list, _ := ioutil.ReadDir(path) // ignore errors // determine number of subdirectories and package files - ndirs := 0; - nfiles := 0; - text := ""; + ndirs := 0 + nfiles := 0 + text := "" for _, d := range list { switch { case isPkgDir(d): ndirs++ case isPkgFile(d): - nfiles++; + nfiles++ if text == "" { // no package documentation yet; take the first found file, err := parser.ParseFile(pathutil.Join(path, d.Name), nil, - parser.ParseComments|parser.PackageClauseOnly); + parser.ParseComments|parser.PackageClauseOnly) if err == nil && // Also accept fakePkgName, so we get synopses for commmands. // Note: This may lead to incorrect results if there is a @@ -225,20 +225,20 @@ func newDirTree(path, name string, depth, maxDepth int) *Directory { } // create subdirectory tree - var dirs []*Directory; + var dirs []*Directory if ndirs > 0 { - dirs = make([]*Directory, ndirs); - i := 0; + dirs = make([]*Directory, ndirs) + i := 0 for _, d := range list { if isPkgDir(d) { - dd := newDirTree(pathutil.Join(path, d.Name), d.Name, depth+1, maxDepth); + dd := newDirTree(pathutil.Join(path, d.Name), d.Name, depth+1, maxDepth) if dd != nil { - dirs[i] = dd; - i++; + dirs[i] = dd + i++ } } } - dirs = dirs[0:i]; + dirs = dirs[0:i] } // if there are no package files and no subdirectories @@ -247,7 +247,7 @@ func newDirTree(path, name string, depth, maxDepth int) *Directory { return nil } - return &Directory{depth, path, name, text, dirs}; + return &Directory{depth, path, name, text, dirs} } @@ -257,11 +257,11 @@ func newDirTree(path, name string, depth, maxDepth int) *Directory { // subdirectories containing package files (transitively). // func newDirectory(root string, maxDepth int) *Directory { - d, err := os.Lstat(root); + d, err := os.Lstat(root) if err != nil || !isPkgDir(d) { return nil } - return newDirTree(root, d.Name, 0, maxDepth); + return newDirTree(root, d.Name, 0, maxDepth) } @@ -278,24 +278,24 @@ func (dir *Directory) walk(c chan<- *Directory, skipRoot bool) { func (dir *Directory) iter(skipRoot bool) <-chan *Directory { - c := make(chan *Directory); + c := make(chan *Directory) go func() { - dir.walk(c, skipRoot); - close(c); - }(); - return c; + dir.walk(c, skipRoot) + close(c) + }() + return c } // lookup looks for the *Directory for a given path, relative to dir. func (dir *Directory) lookup(path string) *Directory { - path = pathutil.Clean(path); // no trailing '/' + path = pathutil.Clean(path) // no trailing '/' if dir == nil || path == "" || path == "." { return dir } - dpath, dname := pathutil.Split(path); + dpath, dname := pathutil.Split(path) if dpath == "" { // directory-local name for _, d := range dir.Dirs { @@ -303,10 +303,10 @@ func (dir *Directory) lookup(path string) *Directory { return d } } - return nil; + return nil } - return dir.lookup(dpath).lookup(dname); + return dir.lookup(dpath).lookup(dname) } @@ -314,17 +314,17 @@ func (dir *Directory) lookup(path string) *Directory { // are useful for presenting an entry in an indented fashion. // type DirEntry struct { - Depth int; // >= 0 - Height int; // = DirList.MaxHeight - Depth, > 0 - Path string; // includes Name, relative to DirList root - Name string; - Synopsis string; + Depth int // >= 0 + Height int // = DirList.MaxHeight - Depth, > 0 + Path string // includes Name, relative to DirList root + Name string + Synopsis string } type DirList struct { - MaxHeight int; // directory tree height, > 0 - List []DirEntry; + MaxHeight int // directory tree height, > 0 + List []DirEntry } @@ -337,11 +337,11 @@ func (root *Directory) listing(skipRoot bool) *DirList { } // determine number of entries n and maximum height - n := 0; - minDepth := 1 << 30; // infinity - maxDepth := 0; + n := 0 + minDepth := 1 << 30 // infinity + maxDepth := 0 for d := range root.iter(skipRoot) { - n++; + n++ if minDepth > d.Depth { minDepth = d.Depth } @@ -349,23 +349,23 @@ func (root *Directory) listing(skipRoot bool) *DirList { maxDepth = d.Depth } } - maxHeight := maxDepth - minDepth + 1; + maxHeight := maxDepth - minDepth + 1 if n == 0 { return nil } // create list - list := make([]DirEntry, n); - i := 0; + list := make([]DirEntry, n) + i := 0 for d := range root.iter(skipRoot) { - p := &list[i]; - p.Depth = d.Depth - minDepth; - p.Height = maxHeight - p.Depth; + p := &list[i] + p.Depth = d.Depth - minDepth + p.Height = maxHeight - p.Depth // the path is relative to root.Path - remove the root.Path // prefix (the prefix should always be present but avoid // crashes and check) - path := d.Path; + path := d.Path if strings.HasPrefix(d.Path, root.Path) { path = d.Path[len(root.Path):] } @@ -373,27 +373,27 @@ func (root *Directory) listing(skipRoot bool) *DirList { if len(path) > 0 && path[0] == '/' { path = path[1:] } - p.Path = path; - p.Name = d.Name; - p.Synopsis = d.Text; - i++; + p.Path = path + p.Name = d.Name + p.Synopsis = d.Text + i++ } - return &DirList{maxHeight, list}; + return &DirList{maxHeight, list} } func listing(dirs []*os.Dir) *DirList { - list := make([]DirEntry, len(dirs)+1); - list[0] = DirEntry{0, 1, "..", "..", ""}; + list := make([]DirEntry, len(dirs)+1) + list[0] = DirEntry{0, 1, "..", "..", ""} for i, d := range dirs { - p := &list[i+1]; - p.Depth = 0; - p.Height = 1; - p.Path = d.Name; - p.Name = d.Name; + p := &list[i+1] + p.Depth = 0 + p.Height = 1 + p.Path = d.Name + p.Name = d.Name } - return &DirList{1, list}; + return &DirList{1, list} } @@ -402,8 +402,8 @@ func listing(dirs []*os.Dir) *DirList { // Styler implements a printer.Styler. type Styler struct { - linetags bool; - highlight string; + linetags bool + highlight string } @@ -419,37 +419,37 @@ func (s *Styler) LineTag(line int) (text []byte, tag printer.HTMLTag) { if s.linetags { tag = printer.HTMLTag{fmt.Sprintf(`<a id="L%d">`, line), "</a>"} } - return; + return } func (s *Styler) Comment(c *ast.Comment, line []byte) (text []byte, tag printer.HTMLTag) { - text = line; + text = line // minimal syntax-coloring of comments for now - people will want more // (don't do anything more until there's a button to turn it on/off) - tag = printer.HTMLTag{`<span class="comment">`, "</span>"}; - return; + tag = printer.HTMLTag{`<span class="comment">`, "</span>"} + return } func (s *Styler) BasicLit(x *ast.BasicLit) (text []byte, tag printer.HTMLTag) { - text = x.Value; - return; + text = x.Value + return } func (s *Styler) Ident(id *ast.Ident) (text []byte, tag printer.HTMLTag) { - text = strings.Bytes(id.Value); + text = strings.Bytes(id.Value) if s.highlight == id.Value { tag = printer.HTMLTag{"<span class=highlight>", "</span>"} } - return; + return } func (s *Styler) Token(tok token.Token) (text []byte, tag printer.HTMLTag) { - text = strings.Bytes(tok.String()); - return; + text = strings.Bytes(tok.String()) + return } @@ -458,27 +458,27 @@ func (s *Styler) Token(tok token.Token) (text []byte, tag printer.HTMLTag) { // Write an AST-node to w; optionally html-escaped. func writeNode(w io.Writer, node interface{}, html bool, styler printer.Styler) { - mode := printer.UseSpaces | printer.NoSemis; + mode := printer.UseSpaces | printer.NoSemis if html { mode |= printer.GenHTML } - (&printer.Config{mode, *tabwidth, styler}).Fprint(w, node); + (&printer.Config{mode, *tabwidth, styler}).Fprint(w, node) } // Write text to w; optionally html-escaped. func writeText(w io.Writer, text []byte, html bool) { if html { - template.HTMLEscape(w, text); - return; + template.HTMLEscape(w, text) + return } - w.Write(text); + w.Write(text) } type StyledNode struct { - node interface{}; - styler printer.Styler; + node interface{} + styler printer.Styler } @@ -495,9 +495,9 @@ func writeAny(w io.Writer, x interface{}, html bool) { writeNode(w, v.node, html, v.styler) default: if html { - var buf bytes.Buffer; - fmt.Fprint(&buf, x); - writeText(w, buf.Bytes(), true); + var buf bytes.Buffer + fmt.Fprint(&buf, x) + writeText(w, buf.Bytes(), true) } else { fmt.Fprint(w, x) } @@ -513,9 +513,9 @@ func htmlFmt(w io.Writer, x interface{}, format string) { // Template formatter for "html-comment" format. func htmlCommentFmt(w io.Writer, x interface{}, format string) { - var buf bytes.Buffer; - writeAny(&buf, x, false); - doc.ToHTML(w, buf.Bytes()); // does html-escaping + var buf bytes.Buffer + writeAny(&buf, x, false) + doc.ToHTML(w, buf.Bytes()) // does html-escaping } @@ -529,7 +529,7 @@ func removePrefix(s, prefix string) string { if strings.HasPrefix(s, prefix) { return s[len(prefix):] } - return s; + return s } @@ -545,10 +545,10 @@ func pathFmt(w io.Writer, x interface{}, format string) { // Template formatter for "link" format. func linkFmt(w io.Writer, x interface{}, format string) { type Positioner interface { - Pos() token.Position; + Pos() token.Position } if node, ok := x.(Positioner); ok { - pos := node.Pos(); + pos := node.Pos() if pos.IsValid() { // line id's in html-printed source are of the // form "L%d" where %d stands for the line number @@ -573,33 +573,33 @@ var infoKinds = [nKinds]string{ // Template formatter for "infoKind" format. func infoKindFmt(w io.Writer, x interface{}, format string) { - fmt.Fprintf(w, infoKinds[x.(SpotKind)]) // infoKind entries are html-escaped + fmt.Fprintf(w, infoKinds[x.(SpotKind)]) // infoKind entries are html-escaped } // Template formatter for "infoLine" format. func infoLineFmt(w io.Writer, x interface{}, format string) { - info := x.(SpotInfo); - line := info.Lori(); + info := x.(SpotInfo) + line := info.Lori() if info.IsIndex() { - index, _ := searchIndex.get(); - line = index.(*Index).Snippet(line).Line; + index, _ := searchIndex.get() + line = index.(*Index).Snippet(line).Line } - fmt.Fprintf(w, "%d", line); + fmt.Fprintf(w, "%d", line) } // Template formatter for "infoSnippet" format. func infoSnippetFmt(w io.Writer, x interface{}, format string) { - info := x.(SpotInfo); - text := `<span class="alert">no snippet text available</span>`; + info := x.(SpotInfo) + text := `<span class="alert">no snippet text available</span>` if info.IsIndex() { - index, _ := searchIndex.get(); + index, _ := searchIndex.get() // no escaping of snippet text needed; // snippet text is escaped when generated - text = index.(*Index).Snippet(info.Lori()).Text; + text = index.(*Index).Snippet(info.Lori()).Text } - fmt.Fprint(w, text); + fmt.Fprint(w, text) } @@ -633,16 +633,16 @@ var fmap = template.FormatterMap{ func readTemplate(name string) *template.Template { - path := pathutil.Join(*tmplroot, name); - data, err := ioutil.ReadFile(path); + path := pathutil.Join(*tmplroot, name) + data, err := ioutil.ReadFile(path) if err != nil { log.Exitf("ReadFile %s: %v", path, err) } - t, err := template.Parse(string(data), fmap); + t, err := template.Parse(string(data), fmap) if err != nil { log.Exitf("%s: %v", name, err) } - return t; + return t } @@ -652,18 +652,18 @@ var ( packageHTML, packageText, searchHTML, - sourceHTML *template.Template; + sourceHTML *template.Template ) func readTemplates() { // have to delay until after flags processing, // so that main has chdir'ed to goroot. - dirlistHTML = readTemplate("dirlist.html"); - godocHTML = readTemplate("godoc.html"); - packageHTML = readTemplate("package.html"); - packageText = readTemplate("package.txt"); - searchHTML = readTemplate("search.html"); - sourceHTML = readTemplate("source.html"); + dirlistHTML = readTemplate("dirlist.html") + godocHTML = readTemplate("godoc.html") + packageHTML = readTemplate("package.html") + packageText = readTemplate("package.txt") + searchHTML = readTemplate("search.html") + sourceHTML = readTemplate("source.html") } @@ -672,19 +672,19 @@ func readTemplates() { func servePage(c *http.Conn, title, query string, content []byte) { type Data struct { - Title string; - Timestamp uint64; // int64 to be compatible with os.Dir.Mtime_ns - Query string; - Content []byte; + Title string + Timestamp uint64 // int64 to be compatible with os.Dir.Mtime_ns + Query string + Content []byte } - _, ts := fsTree.get(); + _, ts := fsTree.get() d := Data{ Title: title, - Timestamp: uint64(ts) * 1e9, // timestamp in ns + Timestamp: uint64(ts) * 1e9, // timestamp in ns Query: query, Content: content, - }; + } if err := godocHTML.Execute(&d, c); err != nil { log.Stderrf("godocHTML.Execute: %s", err) @@ -693,8 +693,8 @@ func servePage(c *http.Conn, title, query string, content []byte) { func serveText(c *http.Conn, text []byte) { - c.SetHeader("content-type", "text/plain; charset=utf-8"); - c.Write(text); + c.SetHeader("content-type", "text/plain; charset=utf-8") + c.Write(text) } @@ -702,69 +702,69 @@ func serveText(c *http.Conn, text []byte) { // Files var ( - tagBegin = strings.Bytes("<!--"); - tagEnd = strings.Bytes("-->"); + tagBegin = strings.Bytes("<!--") + tagEnd = strings.Bytes("-->") ) // commentText returns the text of the first HTML comment in src. func commentText(src []byte) (text string) { - i := bytes.Index(src, tagBegin); - j := bytes.Index(src, tagEnd); + i := bytes.Index(src, tagBegin) + j := bytes.Index(src, tagEnd) if i >= 0 && j >= i+len(tagBegin) { text = string(bytes.TrimSpace(src[i+len(tagBegin) : j])) } - return; + return } func serveHTMLDoc(c *http.Conn, r *http.Request, path string) { // get HTML body contents - src, err := ioutil.ReadFile(path); + src, err := ioutil.ReadFile(path) if err != nil { - log.Stderrf("%v", err); - http.NotFound(c, r); - return; + log.Stderrf("%v", err) + http.NotFound(c, r) + return } // if it's the language spec, add tags to EBNF productions if strings.HasSuffix(path, "go_spec.html") { - var buf bytes.Buffer; - linkify(&buf, src); - src = buf.Bytes(); + var buf bytes.Buffer + linkify(&buf, src) + src = buf.Bytes() } - title := commentText(src); - servePage(c, title, "", src); + title := commentText(src) + servePage(c, title, "", src) } func serveGoSource(c *http.Conn, r *http.Request, path string) { var info struct { - Source StyledNode; - Error string; + Source StyledNode + Error string } - file, err := parser.ParseFile(path, nil, parser.ParseComments); - info.Source = StyledNode{file, &Styler{linetags: true, highlight: r.FormValue("h")}}; + file, err := parser.ParseFile(path, nil, parser.ParseComments) + info.Source = StyledNode{file, &Styler{linetags: true, highlight: r.FormValue("h")}} if err != nil { info.Error = err.String() } - var buf bytes.Buffer; + var buf bytes.Buffer if err := sourceHTML.Execute(info, &buf); err != nil { log.Stderrf("sourceHTML.Execute: %s", err) } - servePage(c, "Source file "+path, "", buf.Bytes()); + servePage(c, "Source file "+path, "", buf.Bytes()) } func redirect(c *http.Conn, r *http.Request) (redirected bool) { if canonical := pathutil.Clean(r.URL.Path) + "/"; r.URL.Path != canonical { - http.Redirect(c, canonical, http.StatusMovedPermanently); - redirected = true; + http.Redirect(c, canonical, http.StatusMovedPermanently) + redirected = true } - return; + return } @@ -772,8 +772,8 @@ func redirect(c *http.Conn, r *http.Request) (redirected bool) { // textExt[x] is true if the extension x indicates a text file, and false otherwise. var textExt = map[string]bool{ - ".css": false, // must be served raw - ".js": false, // must be served raw + ".css": false, // must be served raw + ".js": false, // must be served raw } @@ -786,20 +786,20 @@ func isTextFile(path string) bool { // the extension is not known; read an initial chunk of // file and check if it looks like correct UTF-8; if it // does, it's probably a text file - f, err := os.Open(path, os.O_RDONLY, 0); + f, err := os.Open(path, os.O_RDONLY, 0) if err != nil { return false } - defer f.Close(); + defer f.Close() - var buf [1024]byte; - n, err := f.Read(&buf); + var buf [1024]byte + n, err := f.Read(&buf) if err != nil { return false } - s := string(buf[0:n]); - n -= utf8.UTFMax; // make sure there's enough bytes for a complete unicode char + s := string(buf[0:n]) + n -= utf8.UTFMax // make sure there's enough bytes for a complete unicode char for i, c := range s { if i > n { break @@ -811,22 +811,22 @@ func isTextFile(path string) bool { } // likely a text file - return true; + return true } func serveTextFile(c *http.Conn, r *http.Request, path string) { - src, err := ioutil.ReadFile(path); + src, err := ioutil.ReadFile(path) if err != nil { log.Stderrf("serveTextFile: %s", err) } - var buf bytes.Buffer; - fmt.Fprintln(&buf, "<pre>"); - template.HTMLEscape(&buf, src); - fmt.Fprintln(&buf, "</pre>"); + var buf bytes.Buffer + fmt.Fprintln(&buf, "<pre>") + template.HTMLEscape(&buf, src) + fmt.Fprintln(&buf, "</pre>") - servePage(c, "Text file "+path, "", buf.Bytes()); + servePage(c, "Text file "+path, "", buf.Bytes()) } @@ -835,63 +835,63 @@ func serveDirectory(c *http.Conn, r *http.Request, path string) { return } - list, err := ioutil.ReadDir(path); + list, err := ioutil.ReadDir(path) if err != nil { - http.NotFound(c, r); - return; + http.NotFound(c, r) + return } - var buf bytes.Buffer; + var buf bytes.Buffer if err := dirlistHTML.Execute(list, &buf); err != nil { log.Stderrf("dirlistHTML.Execute: %s", err) } - servePage(c, "Directory "+path, "", buf.Bytes()); + servePage(c, "Directory "+path, "", buf.Bytes()) } var fileServer = http.FileServer(".", "") func serveFile(c *http.Conn, r *http.Request) { - path := pathutil.Join(".", r.URL.Path); + path := pathutil.Join(".", r.URL.Path) // pick off special cases and hand the rest to the standard file server switch ext := pathutil.Ext(path); { case r.URL.Path == "/": - serveHTMLDoc(c, r, "doc/root.html"); - return; + serveHTMLDoc(c, r, "doc/root.html") + return case r.URL.Path == "/doc/root.html": // hide landing page from its real name - http.NotFound(c, r); - return; + http.NotFound(c, r) + return case ext == ".html": - serveHTMLDoc(c, r, path); - return; + serveHTMLDoc(c, r, path) + return case ext == ".go": - serveGoSource(c, r, path); - return; + serveGoSource(c, r, path) + return } - dir, err := os.Lstat(path); + dir, err := os.Lstat(path) if err != nil { - http.NotFound(c, r); - return; + http.NotFound(c, r) + return } if dir != nil && dir.IsDirectory() { - serveDirectory(c, r, path); - return; + serveDirectory(c, r, path) + return } if isTextFile(path) { - serveTextFile(c, r, path); - return; + serveTextFile(c, r, path) + return } - fileServer.ServeHTTP(c, r); + fileServer.ServeHTTP(c, r) } @@ -903,16 +903,16 @@ const fakePkgName = "documentation" type PageInfo struct { - PDoc *doc.PackageDoc; // nil if no package found - Dirs *DirList; // nil if no directory information found - IsPkg bool; // false if this is not documenting a real package + PDoc *doc.PackageDoc // nil if no package found + Dirs *DirList // nil if no directory information found + IsPkg bool // false if this is not documenting a real package } 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) + 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) } @@ -923,11 +923,11 @@ type httpHandler struct { // func (h *httpHandler) getPageInfo(path string) PageInfo { // the path is relative to h.fsroot - dirname := pathutil.Join(h.fsRoot, path); + dirname := pathutil.Join(h.fsRoot, path) // the package name is the directory name within its parent // (use dirname instead of path because dirname is clean; i.e. has no trailing '/') - _, pkgname := pathutil.Split(dirname); + _, pkgname := pathutil.Split(dirname) // filter function to select the desired .go files filter := func(d *os.Dir) bool { @@ -938,28 +938,28 @@ func (h *httpHandler) getPageInfo(path string) PageInfo { // found" errors. // Additionally, accept the special package name // fakePkgName if we are looking at cmd documentation. - name := pkgName(dirname + "/" + d.Name); - return name == pkgname || h.fsRoot == *cmdroot && name == fakePkgName; + name := pkgName(dirname + "/" + d.Name) + return name == pkgname || h.fsRoot == *cmdroot && name == fakePkgName } - return false; - }; + return false + } // get package AST - pkg, err := parser.ParsePackage(dirname, filter, parser.ParseComments); + pkg, err := parser.ParsePackage(dirname, filter, parser.ParseComments) if err != nil { // TODO: parse errors should be shown instead of an empty directory log.Stderrf("parser.parsePackage: %s", err) } // compute package documentation - var pdoc *doc.PackageDoc; + var pdoc *doc.PackageDoc if pkg != nil { - ast.PackageExports(pkg); - pdoc = doc.NewPackageDoc(pkg, pathutil.Clean(path)); // no trailing '/' in importpath + ast.PackageExports(pkg) + pdoc = doc.NewPackageDoc(pkg, pathutil.Clean(path)) // no trailing '/' in importpath } // get directory information - var dir *Directory; + var dir *Directory if tree, _ := fsTree.get(); tree != nil { // directory tree is present; lookup respective directory // (may still fail if the file system was updated and the @@ -971,7 +971,7 @@ func (h *httpHandler) getPageInfo(path string) PageInfo { dir = newDirectory(dirname, 1) } - return PageInfo{pdoc, dir.listing(true), h.isPkg}; + return PageInfo{pdoc, dir.listing(true), h.isPkg} } @@ -980,17 +980,17 @@ func (h *httpHandler) ServeHTTP(c *http.Conn, r *http.Request) { return } - path := r.URL.Path; - path = path[len(h.pattern):]; - info := h.getPageInfo(path); + path := r.URL.Path + path = path[len(h.pattern):] + info := h.getPageInfo(path) - var buf bytes.Buffer; + var buf bytes.Buffer if r.FormValue("f") == "text" { if err := packageText.Execute(info, &buf); err != nil { log.Stderrf("packageText.Execute: %s", err) } - serveText(c, buf.Bytes()); - return; + serveText(c, buf.Bytes()) + return } if err := packageHTML.Execute(info, &buf); err != nil { @@ -998,23 +998,23 @@ func (h *httpHandler) ServeHTTP(c *http.Conn, r *http.Request) { } if path == "" { - path = "." // don't display an empty path + path = "." // don't display an empty path } - title := "Directory " + path; + title := "Directory " + path if info.PDoc != nil { switch { case h.isPkg: title = "Package " + info.PDoc.PackageName case info.PDoc.PackageName == fakePkgName: // assume that the directory name is the command name - _, pkgname := pathutil.Split(pathutil.Clean(path)); - title = "Command " + pkgname; + _, pkgname := pathutil.Split(pathutil.Clean(path)) + title = "Command " + pkgname default: title = "Command " + info.PDoc.PackageName } } - servePage(c, title, "", buf.Bytes()); + servePage(c, title, "", buf.Bytes()) } @@ -1024,37 +1024,37 @@ func (h *httpHandler) ServeHTTP(c *http.Conn, r *http.Request) { var searchIndex RWValue type SearchResult struct { - Query string; - Hit *LookupResult; - Alt *AltWords; - Illegal bool; - Accurate bool; + Query string + Hit *LookupResult + Alt *AltWords + Illegal bool + Accurate bool } func search(c *http.Conn, r *http.Request) { - query := r.FormValue("q"); - var result SearchResult; + query := r.FormValue("q") + var result SearchResult if index, timestamp := searchIndex.get(); index != nil { - result.Query = query; - result.Hit, result.Alt, result.Illegal = index.(*Index).Lookup(query); - _, ts := fsTree.get(); - result.Accurate = timestamp >= ts; + result.Query = query + result.Hit, result.Alt, result.Illegal = index.(*Index).Lookup(query) + _, ts := fsTree.get() + result.Accurate = timestamp >= ts } - var buf bytes.Buffer; + var buf bytes.Buffer if err := searchHTML.Execute(result, &buf); err != nil { log.Stderrf("searchHTML.Execute: %s", err) } - var title string; + var title string if result.Hit != nil { title = fmt.Sprintf(`Results for query %q`, query) } else { title = fmt.Sprintf(`No results found for query %q`, query) } - servePage(c, title, query, buf.Bytes()); + servePage(c, title, query, buf.Bytes()) } @@ -1062,38 +1062,38 @@ func search(c *http.Conn, r *http.Request) { // Server var ( - cmdHandler = httpHandler{"/cmd/", *cmdroot, false}; - pkgHandler = httpHandler{"/pkg/", *pkgroot, true}; + cmdHandler = httpHandler{"/cmd/", *cmdroot, false} + pkgHandler = httpHandler{"/pkg/", *pkgroot, true} ) func registerPublicHandlers(mux *http.ServeMux) { - mux.Handle(cmdHandler.pattern, &cmdHandler); - mux.Handle(pkgHandler.pattern, &pkgHandler); - mux.Handle("/search", http.HandlerFunc(search)); - mux.Handle("/", http.HandlerFunc(serveFile)); + mux.Handle(cmdHandler.pattern, &cmdHandler) + mux.Handle(pkgHandler.pattern, &pkgHandler) + mux.Handle("/search", http.HandlerFunc(search)) + mux.Handle("/", http.HandlerFunc(serveFile)) } // Indexing goroutine. func indexer() { for { - _, ts := fsTree.get(); + _, ts := fsTree.get() if _, timestamp := searchIndex.get(); timestamp < ts { // index possibly out of date - make a new one // (could use a channel to send an explicit signal // from the sync goroutine, but this solution is // more decoupled, trivial, and works well enough) - start := time.Nanoseconds(); - index := NewIndex("."); - stop := time.Nanoseconds(); - searchIndex.set(index); + start := time.Nanoseconds() + index := NewIndex(".") + stop := time.Nanoseconds() + searchIndex.set(index) if *verbose { - secs := float64((stop-start)/1e6) / 1e3; - nwords, nspots := index.Size(); - log.Stderrf("index updated (%gs, %d unique words, %d spots)", secs, nwords, nspots); + secs := float64((stop-start)/1e6) / 1e3 + nwords, nspots := index.Size() + log.Stderrf("index updated (%gs, %d unique words, %d spots)", secs, nwords, nspots) } } - time.Sleep(1 * 60e9); // try once a minute + time.Sleep(1 * 60e9) // try once a minute } } diff --git a/src/cmd/godoc/index.go b/src/cmd/godoc/index.go index b0c331746..218633b2b 100644 --- a/src/cmd/godoc/index.go +++ b/src/cmd/godoc/index.go @@ -25,15 +25,15 @@ package main import ( - "container/vector"; - "go/ast"; - "go/parser"; - "go/token"; - "go/scanner"; - "os"; - pathutil "path"; - "sort"; - "strings"; + "container/vector" + "go/ast" + "go/parser" + "go/token" + "go/scanner" + "os" + pathutil "path" + "sort" + "strings" ) @@ -47,16 +47,16 @@ import ( // into a RunList containing pair runs (x, {y}) where each run consists of // a list of y's with the same x. type RunList struct { - vector.Vector; - less func(x, y interface{}) bool; + vector.Vector + less func(x, y interface{}) bool } -func (h *RunList) Less(i, j int) bool { return h.less(h.At(i), h.At(j)) } +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); + h.less = less + sort.Sort(h) } @@ -64,15 +64,15 @@ func (h *RunList) sort(less func(x, y interface{}) bool) { // (specified by less) into "runs". func (h *RunList) reduce(less func(x, y interface{}) bool, newRun func(h *RunList, i, j int) interface{}) *RunList { // create runs of entries with equal values - h.sort(less); + h.sort(less) // for each run, make a new run object and collect them in a new RunList - var hh RunList; - i := 0; + var hh RunList + i := 0 for j := 0; j < h.Len(); j++ { if less(h.At(i), h.At(j)) { - hh.Push(newRun(h, i, j)); - i = j; // start a new run + hh.Push(newRun(h, i, j)) + i = j // start a new run } } // add final run, if any @@ -80,7 +80,7 @@ func (h *RunList) reduce(less func(x, y interface{}) bool, newRun func(h *RunLis hh.Push(newRun(h, i, h.Len())) } - return &hh; + return &hh } @@ -103,15 +103,15 @@ type SpotInfo uint32 type SpotKind uint32 const ( - PackageClause SpotKind = iota; - ImportDecl; - ConstDecl; - TypeDecl; - VarDecl; - FuncDecl; - MethodDecl; - Use; - nKinds; + PackageClause SpotKind = iota + ImportDecl + ConstDecl + TypeDecl + VarDecl + FuncDecl + MethodDecl + Use + nKinds ) @@ -127,7 +127,7 @@ func init() { // makeSpotInfo makes a SpotInfo. func makeSpotInfo(kind SpotKind, lori int, isIndex bool) SpotInfo { // encode lori: bits [4..32) - x := SpotInfo(lori) << 4; + x := SpotInfo(lori) << 4 if int(x>>4) != lori { // lori value doesn't fit - since snippet indices are // most certainly always smaller then 1<<28, this can @@ -135,18 +135,18 @@ func makeSpotInfo(kind SpotKind, lori int, isIndex bool) SpotInfo { x = 0 } // encode kind: bits [1..4) - x |= SpotInfo(kind) << 1; + x |= SpotInfo(kind) << 1 // encode isIndex: bit 0 if isIndex { x |= 1 } - return x; + 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 } +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 } // ---------------------------------------------------------------------------- @@ -157,55 +157,55 @@ const removeDuplicates = true // A KindRun is a run of SpotInfos of the same kind in a given file. type KindRun struct { - Kind SpotKind; - Infos []SpotInfo; + Kind SpotKind + 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] } +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() } +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(); - infos := make([]SpotInfo, j-i); - k := 0; + kind := h.At(i).(SpotInfo).Kind() + infos := make([]SpotInfo, j-i) + k := 0 for ; i < j; i++ { - infos[k] = h.At(i).(SpotInfo); - k++; + infos[k] = h.At(i).(SpotInfo) + k++ } - run := &KindRun{kind, infos}; + run := &KindRun{kind, infos} // Spots were sorted by file and kind to create this run. // Within this run, sort them by line number or index. - sort.Sort(run); + sort.Sort(run) if removeDuplicates { // Since both the lori and kind field must be // same for duplicates, and since the isIndex // bit is always the same for all infos in one // list we can simply compare the entire info. - k := 0; - var prev SpotInfo; + k := 0 + var prev SpotInfo for i, x := range infos { if x != prev || i == 0 { - infos[k] = x; - k++; - prev = x; + infos[k] = x + k++ + prev = x } } - run.Infos = infos[0:k]; + run.Infos = infos[0:k] } - return run; + return run } @@ -214,8 +214,8 @@ func newKindRun(h *RunList, i, j int) interface{} { // A Pak describes a Go package. type Pak struct { - Path string; // path of directory containing the package - Name string; // package name as declared by package clause + Path string // path of directory containing the package + Name string // package name as declared by package clause } // Paks are sorted by name (primary key) and by import path (secondary key). @@ -226,49 +226,49 @@ func (p *Pak) less(q *Pak) bool { // A File describes a Go file. type File struct { - Path string; // complete file name - Pak Pak; // the package to which the file belongs + Path string // complete file name + Pak Pak // the package to which the file belongs } // A Spot describes a single occurence of a word. type Spot struct { - File *File; - Info SpotInfo; + File *File + Info SpotInfo } // A FileRun is a list of KindRuns belonging to the same file. type FileRun struct { - File *File; - Groups []*KindRun; + 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 } +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; + file := h0.At(i).(Spot).File // reduce the list of Spots into a list of KindRuns - var h1 RunList; - h1.Vector.Resize(j-i, 0); - k := 0; + var h1 RunList + h1.Vector.Resize(j-i, 0) + k := 0 for ; i < j; i++ { - h1.Set(k, h0.At(i).(Spot).Info); - k++; + h1.Set(k, h0.At(i).(Spot).Info) + k++ } - h2 := h1.reduce(lessKind, newKindRun); + h2 := h1.reduce(lessKind, newKindRun) // create the FileRun - groups := make([]*KindRun, h2.Len()); + groups := make([]*KindRun, h2.Len()) for i := 0; i < h2.Len(); i++ { groups[i] = h2.At(i).(*KindRun) } - return &FileRun{file, groups}; + return &FileRun{file, groups} } @@ -277,14 +277,14 @@ func newFileRun(h0 *RunList, i, j int) interface{} { // A PakRun describes a run of *FileRuns of a package. type PakRun struct { - Pak Pak; - Files []*FileRun; + Pak Pak + Files []*FileRun } // Sorting support for files within a PakRun. -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] } +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. @@ -295,16 +295,16 @@ func lessFileRun(x, y interface{}) bool { // 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; - files := make([]*FileRun, j-i); - k := 0; + pak := h.At(i).(*FileRun).File.Pak + files := make([]*FileRun, j-i) + k := 0 for ; i < j; i++ { - files[k] = h.At(i).(*FileRun); - k++; + files[k] = h.At(i).(*FileRun) + k++ } - run := &PakRun{pak, files}; - sort.Sort(run); // files were sorted by package; sort them by file now - return run; + run := &PakRun{pak, files} + sort.Sort(run) // files were sorted by package; sort them by file now + return run } @@ -316,43 +316,43 @@ type HitList []*PakRun // PakRuns are sorted by package. -func lessPakRun(x, y interface{}) bool { return x.(*PakRun).Pak.less(&y.(*PakRun).Pak) } +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); + h1 := h0.reduce(lessSpot, newFileRun) // reduce a list of FileRuns into a list of PakRuns - h2 := h1.reduce(lessFileRun, newPakRun); + h2 := h1.reduce(lessFileRun, newPakRun) // sort the list of PakRuns by package - h2.sort(lessPakRun); + h2.sort(lessPakRun) // create a HitList - h := make(HitList, h2.Len()); + h := make(HitList, h2.Len()) for i := 0; i < h2.Len(); i++ { h[i] = h2.At(i).(*PakRun) } - return h; + return h } func (h HitList) filter(pakname string) HitList { // determine number of matching packages (most of the time just one) - n := 0; + n := 0 for _, p := range h { if p.Pak.Name == pakname { n++ } } // create filtered HitList - hh := make(HitList, n); - i := 0; + hh := make(HitList, n) + i := 0 for _, p := range h { if p.Pak.Name == pakname { - hh[i] = p; - i++; + hh[i] = p + i++ } } - return hh; + return hh } @@ -360,33 +360,33 @@ func (h HitList) filter(pakname string) HitList { // AltWords type wordPair struct { - canon string; // canonical word spelling (all lowercase) - alt string; // alternative spelling + canon string // canonical word spelling (all lowercase) + alt string // alternative spelling } // An AltWords describes a list of alternative spellings for a // canonical (all lowercase) spelling of a word. type AltWords struct { - Canon string; // canonical word spelling (all lowercase) - Alts []string; // alternative spelling for the same word + Canon string // canonical word spelling (all lowercase) + 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 } +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; - alts := make([]string, j-i); - k := 0; + canon := h.At(i).(*wordPair).canon + alts := make([]string, j-i) + k := 0 for ; i < j; i++ { - alts[k] = h.At(i).(*wordPair).alt; - k++; + alts[k] = h.At(i).(*wordPair).alt + k++ } - return &AltWords{canon, alts}; + return &AltWords{canon, alts} } @@ -397,15 +397,15 @@ func (a *AltWords) filter(s string) *AltWords { } // make a new AltWords with the current spelling removed - alts := make([]string, len(a.Alts)); - i := 0; + alts := make([]string, len(a.Alts)) + i := 0 for _, w := range a.Alts { if w != s { - alts[i] = w; - i++; + alts[i] = w + i++ } } - return &AltWords{a.Canon, alts[0:i]}; + return &AltWords{a.Canon, alts[0:i]} } @@ -418,8 +418,8 @@ const excludeTestFiles = false type IndexResult struct { - Decls RunList; // package-level declarations (with snippets) - Others RunList; // all other occurences + Decls RunList // package-level declarations (with snippets) + Others RunList // all other occurences } @@ -428,18 +428,18 @@ type IndexResult struct { // interface for walking file trees, and the ast.Visitor interface for // walking Go ASTs. type Indexer struct { - words map[string]*IndexResult; // RunLists of Spots - snippets vector.Vector; // vector of *Snippets, indexed by snippet indices - file *File; // current file - decl ast.Decl; // current decl - nspots int; // number of spots encountered + words map[string]*IndexResult // RunLists of Spots + snippets vector.Vector // vector of *Snippets, indexed by snippet indices + file *File // current file + decl ast.Decl // current decl + nspots int // number of spots encountered } func (x *Indexer) addSnippet(s *Snippet) int { - index := x.snippets.Len(); - x.snippets.Push(s); - return index; + index := x.snippets.Len() + x.snippets.Push(s) + return index } @@ -452,24 +452,24 @@ func (x *Indexer) visitComment(c *ast.CommentGroup) { func (x *Indexer) visitIdent(kind SpotKind, id *ast.Ident) { if id != nil { - lists, found := x.words[id.Value]; + lists, found := x.words[id.Value] if !found { - lists = new(IndexResult); - x.words[id.Value] = lists; + lists = new(IndexResult) + x.words[id.Value] = lists } if kind == Use || x.decl == nil { // not a declaration or no snippet required - info := makeSpotInfo(kind, id.Pos().Line, false); - lists.Others.Push(Spot{x.file, info}); + info := makeSpotInfo(kind, id.Pos().Line, false) + lists.Others.Push(Spot{x.file, info}) } else { // a declaration with snippet - index := x.addSnippet(NewSnippet(x.decl, id)); - info := makeSpotInfo(kind, index, true); - lists.Decls.Push(Spot{x.file, info}); + index := x.addSnippet(NewSnippet(x.decl, id)) + info := makeSpotInfo(kind, index, true) + lists.Decls.Push(Spot{x.file, info}) } - x.nspots++; + x.nspots++ } } @@ -477,33 +477,33 @@ 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: - x.visitComment(n.Doc); - x.visitIdent(ImportDecl, n.Name); + x.visitComment(n.Doc) + x.visitIdent(ImportDecl, n.Name) for _, s := range n.Path { ast.Walk(x, s) } - x.visitComment(n.Comment); + x.visitComment(n.Comment) case *ast.ValueSpec: - x.visitComment(n.Doc); - kind := ConstDecl; + x.visitComment(n.Doc) + kind := ConstDecl if isVarDecl { kind = VarDecl } for _, n := range n.Names { x.visitIdent(kind, n) } - ast.Walk(x, n.Type); + ast.Walk(x, n.Type) for _, v := range n.Values { ast.Walk(x, v) } - x.visitComment(n.Comment); + x.visitComment(n.Comment) case *ast.TypeSpec: - x.visitComment(n.Doc); - x.visitIdent(TypeDecl, n.Name); - ast.Walk(x, n.Type); - x.visitComment(n.Comment); + x.visitComment(n.Doc) + x.visitIdent(TypeDecl, n.Name) + ast.Walk(x, n.Type) + x.visitComment(n.Comment) } } @@ -518,22 +518,22 @@ func (x *Indexer) Visit(node interface{}) ast.Visitor { x.visitIdent(Use, n) case *ast.Field: - x.decl = nil; // no snippets for fields - x.visitComment(n.Doc); + x.decl = nil // no snippets for fields + x.visitComment(n.Doc) for _, m := range n.Names { x.visitIdent(VarDecl, m) } - ast.Walk(x, n.Type); + ast.Walk(x, n.Type) for _, s := range n.Tag { ast.Walk(x, s) } - x.visitComment(n.Comment); + x.visitComment(n.Comment) case *ast.DeclStmt: if decl, ok := n.Decl.(*ast.GenDecl); ok { // local declarations can only be *ast.GenDecls - x.decl = nil; // no snippets for local declarations - x.visitComment(decl.Doc); + x.decl = nil // no snippets for local declarations + x.visitComment(decl.Doc) for _, s := range decl.Specs { x.visitSpec(s, decl.Tok == token.VAR) } @@ -543,30 +543,30 @@ func (x *Indexer) Visit(node interface{}) ast.Visitor { } case *ast.GenDecl: - x.decl = n; - x.visitComment(n.Doc); + x.decl = n + x.visitComment(n.Doc) for _, s := range n.Specs { x.visitSpec(s, n.Tok == token.VAR) } case *ast.FuncDecl: - x.visitComment(n.Doc); - kind := FuncDecl; + x.visitComment(n.Doc) + kind := FuncDecl if n.Recv != nil { - kind = MethodDecl; - ast.Walk(x, n.Recv); + kind = MethodDecl + ast.Walk(x, n.Recv) } - x.decl = n; - x.visitIdent(kind, n.Name); - ast.Walk(x, n.Type); + x.decl = n + x.visitIdent(kind, n.Name) + ast.Walk(x, n.Type) if n.Body != nil { ast.Walk(x, n.Body) } case *ast.File: - x.visitComment(n.Doc); - x.decl = nil; - x.visitIdent(PackageClause, n.Name); + x.visitComment(n.Doc) + x.decl = nil + x.visitIdent(PackageClause, n.Name) for _, d := range n.Decls { ast.Walk(x, d) } @@ -578,7 +578,7 @@ func (x *Indexer) Visit(node interface{}) ast.Visitor { return x } - return nil; + return nil } @@ -600,15 +600,15 @@ func (x *Indexer) VisitFile(path string, d *os.Dir) { return } - file, err := parser.ParseFile(path, nil, parser.ParseComments); + file, err := parser.ParseFile(path, nil, parser.ParseComments) if err != nil { - return // ignore files with (parse) errors + return // ignore files with (parse) errors } - dir, _ := pathutil.Split(path); - pak := Pak{dir, file.Name.Value}; - x.file = &File{path, pak}; - ast.Walk(x, file); + dir, _ := pathutil.Split(path) + pak := Pak{dir, file.Name.Value} + x.file = &File{path, pak} + ast.Walk(x, file) } @@ -616,65 +616,65 @@ func (x *Indexer) VisitFile(path string, d *os.Dir) { // Index type LookupResult struct { - Decls HitList; // package-level declarations (with snippets) - Others HitList; // all other occurences + Decls HitList // package-level declarations (with snippets) + Others HitList // all other occurences } type Index struct { - words map[string]*LookupResult; // maps words to hit lists - alts map[string]*AltWords; // maps canonical(words) to lists of alternative spellings - snippets []*Snippet; // all snippets, indexed by snippet index - nspots int; // number of spots indexed (a measure of the index size) + words map[string]*LookupResult // maps words to hit lists + alts map[string]*AltWords // maps canonical(words) to lists of alternative spellings + snippets []*Snippet // all snippets, indexed by snippet index + nspots int // number of spots indexed (a measure of the index size) } -func canonical(w string) string { return strings.ToLower(w) } +func canonical(w string) string { return strings.ToLower(w) } // NewIndex creates a new index for the file tree rooted at root. func NewIndex(root string) *Index { - var x Indexer; + var x Indexer // initialize Indexer - x.words = make(map[string]*IndexResult); + x.words = make(map[string]*IndexResult) // collect all Spots - pathutil.Walk(root, &x, nil); + pathutil.Walk(root, &x, nil) // for each word, reduce the RunLists into a LookupResult; // also collect the word with its canonical spelling in a // word list for later computation of alternative spellings - words := make(map[string]*LookupResult); - var wlist RunList; + words := make(map[string]*LookupResult) + var wlist RunList for w, h := range x.words { - decls := reduce(&h.Decls); - others := reduce(&h.Others); + decls := reduce(&h.Decls) + others := reduce(&h.Others) words[w] = &LookupResult{ Decls: decls, Others: others, - }; - wlist.Push(&wordPair{canonical(w), w}); + } + wlist.Push(&wordPair{canonical(w), w}) } // reduce the word list {canonical(w), w} into // a list of AltWords runs {canonical(w), {w}} - alist := wlist.reduce(lessWordPair, newAltWords); + alist := wlist.reduce(lessWordPair, newAltWords) // convert alist into a map of alternative spellings - alts := make(map[string]*AltWords); + alts := make(map[string]*AltWords) for i := 0; i < alist.Len(); i++ { - a := alist.At(i).(*AltWords); - alts[a.Canon] = a; + a := alist.At(i).(*AltWords) + alts[a.Canon] = a } // convert snippet vector into a list - snippets := make([]*Snippet, x.snippets.Len()); + snippets := make([]*Snippet, x.snippets.Len()) for i := 0; i < x.snippets.Len(); i++ { snippets[i] = x.snippets.At(i).(*Snippet) } - return &Index{words, alts, snippets, x.nspots}; + return &Index{words, alts, snippets, x.nspots} } @@ -686,26 +686,26 @@ func (x *Index) Size() (nwords int, nspots int) { func (x *Index) LookupWord(w string) (match *LookupResult, alt *AltWords) { - match, _ = x.words[w]; - alt, _ = x.alts[canonical(w)]; + match, _ = x.words[w] + alt, _ = x.alts[canonical(w)] // remove current spelling from alternatives // (if there is no match, the alternatives do // not contain the current spelling) if match != nil && alt != nil { alt = alt.filter(w) } - return; + return } func isIdentifier(s string) bool { - var S scanner.Scanner; - S.Init("", strings.Bytes(s), nil, 0); + var S scanner.Scanner + S.Init("", strings.Bytes(s), nil, 0) if _, tok, _ := S.Scan(); tok == token.IDENT { - _, tok, _ := S.Scan(); - return tok == token.EOF; + _, tok, _ := S.Scan() + return tok == token.EOF } - return false; + return false } @@ -713,13 +713,13 @@ func isIdentifier(s string) bool { // identifier, Lookup returns a LookupResult, and a list of alternative // spellings, if any. If the query syntax is wrong, illegal is set. func (x *Index) Lookup(query string) (match *LookupResult, alt *AltWords, illegal bool) { - ss := strings.Split(query, ".", 0); + ss := strings.Split(query, ".", 0) // check query syntax for _, s := range ss { if !isIdentifier(s) { - illegal = true; - return; + illegal = true + return } } @@ -728,20 +728,20 @@ func (x *Index) Lookup(query string) (match *LookupResult, alt *AltWords, illega match, alt = x.LookupWord(ss[0]) case 2: - pakname := ss[0]; - match, alt = x.LookupWord(ss[1]); + pakname := ss[0] + match, alt = x.LookupWord(ss[1]) if match != nil { // found a match - filter by package name - decls := match.Decls.filter(pakname); - others := match.Others.filter(pakname); - match = &LookupResult{decls, others}; + decls := match.Decls.filter(pakname) + others := match.Others.filter(pakname) + match = &LookupResult{decls, others} } default: illegal = true } - return; + return } @@ -750,5 +750,5 @@ func (x *Index) Snippet(i int) *Snippet { if 0 <= i && i < len(x.snippets) { return x.snippets[i] } - return nil; + return nil } diff --git a/src/cmd/godoc/main.go b/src/cmd/godoc/main.go index b8967e4bf..701cd006e 100644 --- a/src/cmd/godoc/main.go +++ b/src/cmd/godoc/main.go @@ -26,74 +26,74 @@ package main import ( - "bytes"; - "flag"; - "fmt"; - "http"; - "io"; - "log"; - "os"; - "time"; + "bytes" + "flag" + "fmt" + "http" + "io" + "log" + "os" + "time" ) var ( // periodic sync - syncCmd = flag.String("sync", "", "sync command; disabled if empty"); - syncMin = flag.Int("sync_minutes", 0, "sync interval in minutes; disabled if <= 0"); - syncDelay delayTime; // actual sync delay in minutes; usually syncDelay == syncMin, but delay may back off exponentially + syncCmd = flag.String("sync", "", "sync command; disabled if empty") + syncMin = flag.Int("sync_minutes", 0, "sync interval in minutes; disabled if <= 0") + syncDelay delayTime // actual sync delay in minutes; usually syncDelay == syncMin, but delay may back off exponentially // server control - httpaddr = flag.String("http", "", "HTTP service address (e.g., ':6060')"); + httpaddr = flag.String("http", "", "HTTP service address (e.g., ':6060')") // layout control - html = flag.Bool("html", false, "print HTML in command-line mode"); + html = flag.Bool("html", false, "print HTML in command-line mode") ) func exec(c *http.Conn, args []string) (status int) { - r, w, err := os.Pipe(); + r, w, err := os.Pipe() if err != nil { - log.Stderrf("os.Pipe(): %v\n", err); - return 2; + log.Stderrf("os.Pipe(): %v\n", err) + return 2 } - bin := args[0]; - fds := []*os.File{nil, w, w}; + bin := args[0] + fds := []*os.File{nil, w, w} if *verbose { log.Stderrf("executing %v", args) } - pid, err := os.ForkExec(bin, args, os.Environ(), goroot, fds); - defer r.Close(); - w.Close(); + pid, err := os.ForkExec(bin, args, os.Environ(), goroot, fds) + defer r.Close() + w.Close() if err != nil { - log.Stderrf("os.ForkExec(%q): %v\n", bin, err); - return 2; + log.Stderrf("os.ForkExec(%q): %v\n", bin, err) + return 2 } - var buf bytes.Buffer; - io.Copy(&buf, r); - wait, err := os.Wait(pid, 0); + var buf bytes.Buffer + io.Copy(&buf, r) + wait, err := os.Wait(pid, 0) if err != nil { - os.Stderr.Write(buf.Bytes()); - log.Stderrf("os.Wait(%d, 0): %v\n", pid, err); - return 2; + os.Stderr.Write(buf.Bytes()) + log.Stderrf("os.Wait(%d, 0): %v\n", pid, err) + return 2 } - status = wait.ExitStatus(); + status = wait.ExitStatus() if !wait.Exited() || status > 1 { - os.Stderr.Write(buf.Bytes()); - log.Stderrf("executing %v failed (exit status = %d)", args, status); - return; + os.Stderr.Write(buf.Bytes()) + log.Stderrf("executing %v failed (exit status = %d)", args, status) + return } if *verbose { os.Stderr.Write(buf.Bytes()) } if c != nil { - c.SetHeader("content-type", "text/plain; charset=utf-8"); - c.Write(buf.Bytes()); + c.SetHeader("content-type", "text/plain; charset=utf-8") + c.Write(buf.Bytes()) } - return; + return } @@ -101,7 +101,7 @@ func exec(c *http.Conn, args []string) (status int) { const maxDirDepth = 24 func dosync(c *http.Conn, r *http.Request) { - args := []string{"/bin/sh", "-c", *syncCmd}; + args := []string{"/bin/sh", "-c", *syncCmd} switch exec(c, args) { case 0: // sync succeeded and some files have changed; @@ -109,12 +109,12 @@ func dosync(c *http.Conn, r *http.Request) { // TODO(gri): The directory tree may be temporarily out-of-sync. // Consider keeping separate time stamps so the web- // page can indicate this discrepancy. - fsTree.set(newDirectory(".", maxDirDepth)); - fallthrough; + fsTree.set(newDirectory(".", maxDirDepth)) + fallthrough case 1: // sync failed because no files changed; // don't change the package tree - syncDelay.set(*syncMin) // revert to regular sync schedule + syncDelay.set(*syncMin) // revert to regular sync schedule default: // sync failed because of an error - back off exponentially, but try at least once a day syncDelay.backoff(24 * 60) @@ -125,23 +125,23 @@ func dosync(c *http.Conn, r *http.Request) { func usage() { fmt.Fprintf(os.Stderr, "usage: godoc package [name ...]\n"+ - " godoc -http=:6060\n"); - flag.PrintDefaults(); - os.Exit(2); + " godoc -http=:6060\n") + flag.PrintDefaults() + os.Exit(2) } func loggingHandler(h http.Handler) http.Handler { return http.HandlerFunc(func(c *http.Conn, req *http.Request) { - log.Stderrf("%s\t%s", c.RemoteAddr, req.URL); - h.ServeHTTP(c, req); + log.Stderrf("%s\t%s", c.RemoteAddr, req.URL) + h.ServeHTTP(c, req) }) } func main() { - flag.Usage = usage; - flag.Parse(); + flag.Usage = usage + flag.Parse() // Check usage: either server and no args, or command line and args if (*httpaddr != "") != (flag.NArg() == 0) { @@ -156,23 +156,23 @@ func main() { log.Exitf("chdir %s: %v", goroot, err) } - readTemplates(); + readTemplates() if *httpaddr != "" { // HTTP server mode. - var handler http.Handler = http.DefaultServeMux; + var handler http.Handler = http.DefaultServeMux if *verbose { - log.Stderrf("Go Documentation Server\n"); - log.Stderrf("address = %s\n", *httpaddr); - log.Stderrf("goroot = %s\n", goroot); - log.Stderrf("cmdroot = %s\n", *cmdroot); - log.Stderrf("pkgroot = %s\n", *pkgroot); - log.Stderrf("tmplroot = %s\n", *tmplroot); - log.Stderrf("tabwidth = %d\n", *tabwidth); - handler = loggingHandler(handler); + log.Stderrf("Go Documentation Server\n") + log.Stderrf("address = %s\n", *httpaddr) + log.Stderrf("goroot = %s\n", goroot) + log.Stderrf("cmdroot = %s\n", *cmdroot) + log.Stderrf("pkgroot = %s\n", *pkgroot) + log.Stderrf("tmplroot = %s\n", *tmplroot) + log.Stderrf("tabwidth = %d\n", *tabwidth) + handler = loggingHandler(handler) } - registerPublicHandlers(http.DefaultServeMux); + registerPublicHandlers(http.DefaultServeMux) if *syncCmd != "" { http.Handle("/debug/sync", http.HandlerFunc(dosync)) } @@ -180,39 +180,39 @@ func main() { // Initialize directory tree with corresponding timestamp. // Do it in two steps: // 1) set timestamp right away so that the indexer is kicked on - fsTree.set(nil); + fsTree.set(nil) // 2) compute initial directory tree in a goroutine so that launch is quick - go func() { fsTree.set(newDirectory(".", maxDirDepth)) }(); + go func() { fsTree.set(newDirectory(".", maxDirDepth)) }() // Start sync goroutine, if enabled. if *syncCmd != "" && *syncMin > 0 { - syncDelay.set(*syncMin); // initial sync delay + syncDelay.set(*syncMin) // initial sync delay go func() { for { - dosync(nil, nil); - delay, _ := syncDelay.get(); + dosync(nil, nil) + delay, _ := syncDelay.get() if *verbose { log.Stderrf("next sync in %dmin", delay.(int)) } - time.Sleep(int64(delay.(int)) * 60e9); + time.Sleep(int64(delay.(int)) * 60e9) } - }(); + }() } // Start indexing goroutine. - go indexer(); + go indexer() // The server may have been restarted; always wait 1sec to // give the forking server a chance to shut down and release // the http port. // TODO(gri): Do we still need this? - time.Sleep(1e9); + time.Sleep(1e9) // Start http server. if err := http.ListenAndServe(*httpaddr, handler); err != nil { log.Exitf("ListenAndServe %s: %v", *httpaddr, err) } - return; + return } // Command line mode. @@ -220,7 +220,7 @@ func main() { packageText = packageHTML } - info := pkgHandler.getPageInfo(flag.Arg(0)); + info := pkgHandler.getPageInfo(flag.Arg(0)) if info.PDoc == nil && info.Dirs == nil { // try again, this time assume it's a command @@ -228,8 +228,8 @@ func main() { } if info.PDoc != nil && flag.NArg() > 1 { - args := flag.Args(); - info.PDoc.Filter(args[1:]); + args := flag.Args() + info.PDoc.Filter(args[1:]) } if err := packageText.Execute(info, os.Stdout); err != nil { diff --git a/src/cmd/godoc/snippet.go b/src/cmd/godoc/snippet.go index be027ffc8..98bc97285 100755 --- a/src/cmd/godoc/snippet.go +++ b/src/cmd/godoc/snippet.go @@ -10,44 +10,44 @@ package main import ( - "bytes"; - "go/ast"; - "go/printer"; - "fmt"; - "strings"; + "bytes" + "go/ast" + "go/printer" + "fmt" + "strings" ) type Snippet struct { - Line int; - Text string; + Line int + Text string } type snippetStyler struct { - Styler; // defined in godoc.go - highlight *ast.Ident; // identifier to highlight + Styler // defined in godoc.go + highlight *ast.Ident // identifier to highlight } func (s *snippetStyler) LineTag(line int) (text []uint8, tag printer.HTMLTag) { - return // no LineTag for snippets + return // no LineTag for snippets } func (s *snippetStyler) Ident(id *ast.Ident) (text []byte, tag printer.HTMLTag) { - text = strings.Bytes(id.Value); + text = strings.Bytes(id.Value) if s.highlight == id { tag = printer.HTMLTag{"<span class=highlight>", "</span>"} } - return; + return } func newSnippet(decl ast.Decl, id *ast.Ident) *Snippet { - var buf bytes.Buffer; - writeNode(&buf, decl, true, &snippetStyler{highlight: id}); - return &Snippet{id.Pos().Line, buf.String()}; + var buf bytes.Buffer + writeNode(&buf, decl, true, &snippetStyler{highlight: id}) + return &Snippet{id.Pos().Line, buf.String()} } @@ -70,32 +70,32 @@ func findSpec(list []ast.Spec, id *ast.Ident) ast.Spec { } } } - return nil; + return nil } func genSnippet(d *ast.GenDecl, id *ast.Ident) *Snippet { - s := findSpec(d.Specs, id); + s := findSpec(d.Specs, id) if s == nil { - return nil // declaration doesn't contain id - exit gracefully + return nil // declaration doesn't contain id - exit gracefully } // only use the spec containing the id for the snippet - dd := &ast.GenDecl{d.Doc, d.Position, d.Tok, d.Lparen, []ast.Spec{s}, d.Rparen}; + dd := &ast.GenDecl{d.Doc, d.Position, d.Tok, d.Lparen, []ast.Spec{s}, d.Rparen} - return newSnippet(dd, id); + return newSnippet(dd, id) } func funcSnippet(d *ast.FuncDecl, id *ast.Ident) *Snippet { if d.Name != id { - return nil // declaration doesn't contain id - exit gracefully + return nil // declaration doesn't contain id - exit gracefully } // only use the function signature for the snippet - dd := &ast.FuncDecl{d.Doc, d.Recv, d.Name, d.Type, nil}; + dd := &ast.FuncDecl{d.Doc, d.Recv, d.Name, d.Type, nil} - return newSnippet(dd, id); + return newSnippet(dd, id) } @@ -118,5 +118,5 @@ func NewSnippet(decl ast.Decl, id *ast.Ident) (s *Snippet) { fmt.Sprintf(`could not generate a snippet for <span class="highlight">%s</span>`, id.Value), } } - return; + return } diff --git a/src/cmd/godoc/spec.go b/src/cmd/godoc/spec.go index 15ce2fb9e..15f3cba20 100644 --- a/src/cmd/godoc/spec.go +++ b/src/cmd/godoc/spec.go @@ -11,35 +11,35 @@ package main import ( - "bytes"; - "fmt"; - "go/scanner"; - "go/token"; - "io"; - "strings"; + "bytes" + "fmt" + "go/scanner" + "go/token" + "io" + "strings" ) type ebnfParser struct { - out io.Writer; // parser output - src []byte; // parser source - scanner scanner.Scanner; - prev int; // offset of previous token - pos token.Position; // token position - tok token.Token; // one token look-ahead - lit []byte; // token literal + out io.Writer // parser output + src []byte // parser source + scanner scanner.Scanner + prev int // offset of previous token + pos token.Position // token position + tok token.Token // one token look-ahead + lit []byte // token literal } func (p *ebnfParser) flush() { - p.out.Write(p.src[p.prev:p.pos.Offset]); - p.prev = p.pos.Offset; + p.out.Write(p.src[p.prev:p.pos.Offset]) + p.prev = p.pos.Offset } func (p *ebnfParser) next() { - p.flush(); - p.pos, p.tok, p.lit = p.scanner.Scan(); + p.flush() + p.pos, p.tok, p.lit = p.scanner.Scan() if p.tok.IsKeyword() { // TODO Should keyword mapping always happen outside scanner? // Or should there be a flag to scanner to enable keyword mapping? @@ -54,38 +54,38 @@ func (p *ebnfParser) Error(pos token.Position, msg string) { func (p *ebnfParser) errorExpected(pos token.Position, msg string) { - msg = "expected " + msg; + msg = "expected " + msg if pos.Offset == p.pos.Offset { // the error happened at the current position; // make the error message more specific - msg += ", found '" + p.tok.String() + "'"; + msg += ", found '" + p.tok.String() + "'" if p.tok.IsLiteral() { msg += " " + string(p.lit) } } - p.Error(pos, msg); + p.Error(pos, msg) } func (p *ebnfParser) expect(tok token.Token) token.Position { - pos := p.pos; + pos := p.pos if p.tok != tok { p.errorExpected(pos, "'"+tok.String()+"'") } - p.next(); // make progress in any case - return pos; + p.next() // make progress in any case + return pos } func (p *ebnfParser) parseIdentifier(def bool) { - name := string(p.lit); - p.expect(token.IDENT); + name := string(p.lit) + p.expect(token.IDENT) if def { fmt.Fprintf(p.out, `<a id="%s">%s</a>`, name, name) } else { fmt.Fprintf(p.out, `<a href="#%s" class="noline">%s</a>`, name, name) } - p.prev += len(name); // skip identifier when calling flush + p.prev += len(name) // skip identifier when calling flush } @@ -95,32 +95,32 @@ func (p *ebnfParser) parseTerm() bool { p.parseIdentifier(false) case token.STRING: - p.next(); + p.next() if p.tok == token.ELLIPSIS { - p.next(); - p.expect(token.STRING); + p.next() + p.expect(token.STRING) } case token.LPAREN: - p.next(); - p.parseExpression(); - p.expect(token.RPAREN); + p.next() + p.parseExpression() + p.expect(token.RPAREN) case token.LBRACK: - p.next(); - p.parseExpression(); - p.expect(token.RBRACK); + p.next() + p.parseExpression() + p.expect(token.RBRACK) case token.LBRACE: - p.next(); - p.parseExpression(); - p.expect(token.RBRACE); + p.next() + p.parseExpression() + p.expect(token.RBRACE) default: return false } - return true; + return true } @@ -132,70 +132,70 @@ func (p *ebnfParser) parseSequence() { func (p *ebnfParser) parseExpression() { for { - p.parseSequence(); + p.parseSequence() if p.tok != token.OR { break } - p.next(); + p.next() } } func (p *ebnfParser) parseProduction() { - p.parseIdentifier(true); - p.expect(token.ASSIGN); - p.parseExpression(); - p.expect(token.PERIOD); + p.parseIdentifier(true) + p.expect(token.ASSIGN) + p.parseExpression() + p.expect(token.PERIOD) } func (p *ebnfParser) parse(out io.Writer, src []byte) { // initialize ebnfParser - p.out = out; - p.src = src; - p.scanner.Init("", src, p, 0); - p.next(); // initializes pos, tok, lit + p.out = out + p.src = src + p.scanner.Init("", src, p, 0) + p.next() // initializes pos, tok, lit // process source for p.tok != token.EOF { p.parseProduction() } - p.flush(); + p.flush() } // Markers around EBNF sections var ( - openTag = strings.Bytes(`<pre class="ebnf">`); - closeTag = strings.Bytes(`</pre>`); + openTag = strings.Bytes(`<pre class="ebnf">`) + closeTag = strings.Bytes(`</pre>`) ) func linkify(out io.Writer, src []byte) { for len(src) > 0 { - n := len(src); + n := len(src) // i: beginning of EBNF text (or end of source) - i := bytes.Index(src, openTag); + i := bytes.Index(src, openTag) if i < 0 { i = n - len(openTag) } - i += len(openTag); + i += len(openTag) // j: end of EBNF text (or end of source) - j := bytes.Index(src[i:n], closeTag); // close marker + j := bytes.Index(src[i:n], closeTag) // close marker if j < 0 { j = n - i } - j += i; + j += i // write text before EBNF - out.Write(src[0:i]); + out.Write(src[0:i]) // parse and write EBNF - var p ebnfParser; - p.parse(out, src[i:j]); + var p ebnfParser + p.parse(out, src[i:j]) // advance - src = src[j:n]; + src = src[j:n] } } diff --git a/src/cmd/gofmt/gofmt.go b/src/cmd/gofmt/gofmt.go index f0f23cb00..ee3147d4f 100644 --- a/src/cmd/gofmt/gofmt.go +++ b/src/cmd/gofmt/gofmt.go @@ -5,65 +5,65 @@ package main import ( - "bytes"; - oldParser "exp/parser"; - "flag"; - "fmt"; - "go/ast"; - "go/parser"; - "go/printer"; - "go/scanner"; - "io/ioutil"; - "os"; - pathutil "path"; - "strings"; + "bytes" + oldParser "exp/parser" + "flag" + "fmt" + "go/ast" + "go/parser" + "go/printer" + "go/scanner" + "io/ioutil" + "os" + pathutil "path" + "strings" ) var ( // main operation modes - list = flag.Bool("l", false, "list files whose formatting differs from gofmt's"); - write = flag.Bool("w", false, "write result to (source) file instead of stdout"); - rewriteRule = flag.String("r", "", "rewrite rule (e.g., 'α[β:len(α)] -> α[β:]')"); + list = flag.Bool("l", false, "list files whose formatting differs from gofmt's") + write = flag.Bool("w", false, "write result to (source) file instead of stdout") + rewriteRule = flag.String("r", "", "rewrite rule (e.g., 'α[β:len(α)] -> α[β:]')") // debugging support - comments = flag.Bool("comments", true, "print comments"); - trace = flag.Bool("trace", false, "print parse trace"); + comments = flag.Bool("comments", true, "print comments") + trace = flag.Bool("trace", false, "print parse trace") // layout control - tabWidth = flag.Int("tabwidth", 8, "tab width"); - tabIndent = flag.Bool("tabindent", false, "indent with tabs independent of -spaces"); - useSpaces = flag.Bool("spaces", false, "align with spaces instead of tabs"); + tabWidth = flag.Int("tabwidth", 8, "tab width") + tabIndent = flag.Bool("tabindent", true, "indent with tabs independent of -spaces") + useSpaces = flag.Bool("spaces", true, "align with spaces instead of tabs") // semicolon transition - useOldParser = flag.Bool("oldparser", true, "parse old syntax (required semicolons)"); - useOldPrinter = flag.Bool("oldprinter", true, "print old syntax (required semicolons)"); + useOldParser = flag.Bool("oldparser", false, "parse old syntax (required semicolons)") + useOldPrinter = flag.Bool("oldprinter", false, "print old syntax (required semicolons)") ) var ( - exitCode = 0; - rewrite func(*ast.File) *ast.File; - parserMode uint; - printerMode uint; + exitCode = 0 + rewrite func(*ast.File) *ast.File + parserMode uint + printerMode uint ) func report(err os.Error) { - scanner.PrintError(os.Stderr, err); - exitCode = 2; + scanner.PrintError(os.Stderr, err) + exitCode = 2 } func usage() { - fmt.Fprintf(os.Stderr, "usage: gofmt [flags] [path ...]\n"); - flag.PrintDefaults(); - os.Exit(2); + fmt.Fprintf(os.Stderr, "usage: gofmt [flags] [path ...]\n") + flag.PrintDefaults() + os.Exit(2) } func initParserMode() { - parserMode = uint(0); + parserMode = uint(0) if *comments { parserMode |= parser.ParseComments } @@ -74,7 +74,7 @@ func initParserMode() { func initPrinterMode() { - printerMode = uint(0); + printerMode = uint(0) if *tabIndent { printerMode |= printer.TabIndent } @@ -94,12 +94,12 @@ func isGoFile(d *os.Dir) bool { func processFile(f *os.File) os.Error { - src, err := ioutil.ReadAll(f); + src, err := ioutil.ReadAll(f) if err != nil { return err } - var file *ast.File; + var file *ast.File if *useOldParser { file, err = oldParser.ParseFile(f.Name(), src, parserMode) } else { @@ -113,8 +113,8 @@ func processFile(f *os.File) os.Error { file = rewrite(file) } - var res bytes.Buffer; - _, err = (&printer.Config{printerMode, *tabWidth, nil}).Fprint(&res, file); + var res bytes.Buffer + _, err = (&printer.Config{printerMode, *tabWidth, nil}).Fprint(&res, file) if err != nil { return err } @@ -125,7 +125,7 @@ func processFile(f *os.File) os.Error { fmt.Fprintln(os.Stdout, f.Name()) } if *write { - err = ioutil.WriteFile(f.Name(), res.Bytes(), 0); + err = ioutil.WriteFile(f.Name(), res.Bytes(), 0) if err != nil { return err } @@ -136,17 +136,17 @@ func processFile(f *os.File) os.Error { _, err = os.Stdout.Write(res.Bytes()) } - return err; + return err } func processFileByName(filename string) (err os.Error) { - file, err := os.Open(filename, os.O_RDONLY, 0); + file, err := os.Open(filename, os.O_RDONLY, 0) if err != nil { return } - defer file.Close(); - return processFile(file); + defer file.Close() + return processFile(file) } @@ -159,7 +159,7 @@ func (v fileVisitor) VisitDir(path string, d *os.Dir) bool { func (v fileVisitor) VisitFile(path string, d *os.Dir) { if isGoFile(d) { - v <- nil; // synchronize error handler + v <- nil // synchronize error handler if err := processFileByName(path); err != nil { v <- err } @@ -169,34 +169,34 @@ func (v fileVisitor) VisitFile(path string, d *os.Dir) { func walkDir(path string) { // start an error handler - done := make(chan bool); - v := make(fileVisitor); + done := make(chan bool) + v := make(fileVisitor) go func() { for err := range v { if err != nil { report(err) } } - done <- true; - }(); + done <- true + }() // walk the tree - pathutil.Walk(path, v, v); - close(v); // terminate error handler loop - <-done; // wait for all errors to be reported + pathutil.Walk(path, v, v) + close(v) // terminate error handler loop + <-done // wait for all errors to be reported } func main() { - flag.Usage = usage; - flag.Parse(); + flag.Usage = usage + flag.Parse() if *tabWidth < 0 { - fmt.Fprintf(os.Stderr, "negative tabwidth %d\n", *tabWidth); - os.Exit(2); + fmt.Fprintf(os.Stderr, "negative tabwidth %d\n", *tabWidth) + os.Exit(2) } - initParserMode(); - initPrinterMode(); - initRewrite(); + initParserMode() + initPrinterMode() + initRewrite() if flag.NArg() == 0 { if err := processFile(os.Stdin); err != nil { @@ -205,7 +205,7 @@ func main() { } for i := 0; i < flag.NArg(); i++ { - path := flag.Arg(i); + path := flag.Arg(i) switch dir, err := os.Stat(path); { case err != nil: report(err) @@ -218,5 +218,5 @@ func main() { } } - os.Exit(exitCode); + os.Exit(exitCode) } diff --git a/src/cmd/gofmt/rewrite.go b/src/cmd/gofmt/rewrite.go index ccbfe1d7f..fe35bfb08 100644 --- a/src/cmd/gofmt/rewrite.go +++ b/src/cmd/gofmt/rewrite.go @@ -5,15 +5,15 @@ package main import ( - "fmt"; - "go/ast"; - "go/parser"; - "go/token"; - "os"; - "reflect"; - "strings"; - "unicode"; - "utf8"; + "fmt" + "go/ast" + "go/parser" + "go/token" + "os" + "reflect" + "strings" + "unicode" + "utf8" ) @@ -21,14 +21,14 @@ func initRewrite() { if *rewriteRule == "" { return } - f := strings.Split(*rewriteRule, "->", 0); + f := strings.Split(*rewriteRule, "->", 0) if len(f) != 2 { - fmt.Fprintf(os.Stderr, "rewrite rule must be of the form 'pattern -> replacement'\n"); - os.Exit(2); + fmt.Fprintf(os.Stderr, "rewrite rule must be of the form 'pattern -> replacement'\n") + os.Exit(2) } - pattern := parseExpr(f[0], "pattern"); - replace := parseExpr(f[1], "replacement"); - rewrite = func(p *ast.File) *ast.File { return rewriteFile(pattern, replace, p) }; + pattern := parseExpr(f[0], "pattern") + replace := parseExpr(f[1], "replacement") + rewrite = func(p *ast.File) *ast.File { return rewriteFile(pattern, replace, p) } } @@ -37,41 +37,41 @@ func initRewrite() { // but there are problems with preserving formatting and also // with what a wildcard for a statement looks like. func parseExpr(s string, what string) ast.Expr { - stmts, err := parser.ParseStmtList("input", s); + stmts, err := parser.ParseStmtList("input", s) if err != nil { - fmt.Fprintf(os.Stderr, "parsing %s %s: %s\n", what, s, err); - os.Exit(2); + fmt.Fprintf(os.Stderr, "parsing %s %s: %s\n", what, s, err) + os.Exit(2) } if len(stmts) != 1 { - fmt.Fprintf(os.Stderr, "%s must be single expression\n", what); - os.Exit(2); + fmt.Fprintf(os.Stderr, "%s must be single expression\n", what) + os.Exit(2) } - x, ok := stmts[0].(*ast.ExprStmt); + x, ok := stmts[0].(*ast.ExprStmt) if !ok { - fmt.Fprintf(os.Stderr, "%s must be single expression\n", what); - os.Exit(2); + fmt.Fprintf(os.Stderr, "%s must be single expression\n", what) + os.Exit(2) } - return x.X; + return x.X } // rewriteFile applys 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); - pat := reflect.NewValue(pattern); - repl := reflect.NewValue(replace); - var f func(val reflect.Value) reflect.Value; // f is recursive + m := make(map[string]reflect.Value) + pat := reflect.NewValue(pattern) + repl := reflect.NewValue(replace) + var f func(val reflect.Value) reflect.Value // f is recursive f = func(val reflect.Value) reflect.Value { for k := range m { m[k] = nil, false } - val = apply(f, val); + val = apply(f, val) if match(m, pat, val) { val = subst(m, repl, reflect.NewValue(val.Interface().(ast.Node).Pos())) } - return val; - }; - return apply(f, reflect.NewValue(p)).Interface().(*ast.File); + return val + } + return apply(f, reflect.NewValue(p)).Interface().(*ast.File) } @@ -80,8 +80,8 @@ var identType = reflect.Typeof((*ast.Ident)(nil)) func isWildcard(s string) bool { - rune, size := utf8.DecodeRuneInString(s); - return size == len(s) && unicode.IsLower(rune); + rune, size := utf8.DecodeRuneInString(s) + return size == len(s) && unicode.IsLower(rune) } @@ -94,19 +94,19 @@ func apply(f func(reflect.Value) reflect.Value, val reflect.Value) reflect.Value switch v := reflect.Indirect(val).(type) { case *reflect.SliceValue: for i := 0; i < v.Len(); i++ { - e := v.Elem(i); - e.SetValue(f(e)); + e := v.Elem(i) + e.SetValue(f(e)) } case *reflect.StructValue: for i := 0; i < v.NumField(); i++ { - e := v.Field(i); - e.SetValue(f(e)); + e := v.Field(i) + e.SetValue(f(e)) } case *reflect.InterfaceValue: - e := v.Elem(); - v.SetValue(f(e)); + e := v.Elem() + v.SetValue(f(e)) } - return val; + return val } @@ -118,13 +118,13 @@ func match(m map[string]reflect.Value, pattern, val reflect.Value) bool { // times in the pattern, it must match the same expression // each time. if m != nil && pattern.Type() == identType { - name := pattern.Interface().(*ast.Ident).Value; + name := pattern.Interface().(*ast.Ident).Value if isWildcard(name) { if old, ok := m[name]; ok { return match(nil, old, val) } - m[name] = val; - return true; + m[name] = val + return true } } @@ -141,35 +141,35 @@ func match(m map[string]reflect.Value, pattern, val reflect.Value) bool { return true } - p := reflect.Indirect(pattern); - v := reflect.Indirect(val); + p := reflect.Indirect(pattern) + v := reflect.Indirect(val) switch p := p.(type) { case *reflect.SliceValue: - v := v.(*reflect.SliceValue); + v := v.(*reflect.SliceValue) for i := 0; i < p.Len(); i++ { if !match(m, p.Elem(i), v.Elem(i)) { return false } } - return true; + return true case *reflect.StructValue: - v := v.(*reflect.StructValue); + v := v.(*reflect.StructValue) for i := 0; i < p.NumField(); i++ { if !match(m, p.Field(i), v.Field(i)) { return false } } - return true; + return true case *reflect.InterfaceValue: - v := v.(*reflect.InterfaceValue); - return match(m, p.Elem(), v.Elem()); + v := v.(*reflect.InterfaceValue) + return match(m, p.Elem(), v.Elem()) } // Handle token integers, etc. - return p.Interface() == v.Interface(); + return p.Interface() == v.Interface() } @@ -184,7 +184,7 @@ func subst(m map[string]reflect.Value, pattern reflect.Value, pos reflect.Value) // Wildcard gets replaced with map value. if m != nil && pattern.Type() == identType { - name := pattern.Interface().(*ast.Ident).Value; + name := pattern.Interface().(*ast.Ident).Value if isWildcard(name) { if old, ok := m[name]; ok { return subst(nil, old, nil) @@ -199,29 +199,29 @@ func subst(m map[string]reflect.Value, pattern reflect.Value, pos reflect.Value) // Otherwise copy. switch p := pattern.(type) { case *reflect.SliceValue: - v := reflect.MakeSlice(p.Type().(*reflect.SliceType), p.Len(), p.Len()); + v := reflect.MakeSlice(p.Type().(*reflect.SliceType), p.Len(), p.Len()) for i := 0; i < p.Len(); i++ { v.Elem(i).SetValue(subst(m, p.Elem(i), pos)) } - return v; + return v case *reflect.StructValue: - v := reflect.MakeZero(p.Type()).(*reflect.StructValue); + v := reflect.MakeZero(p.Type()).(*reflect.StructValue) for i := 0; i < p.NumField(); i++ { v.Field(i).SetValue(subst(m, p.Field(i), pos)) } - return v; + return v case *reflect.PtrValue: - v := reflect.MakeZero(p.Type()).(*reflect.PtrValue); - v.PointTo(subst(m, p.Elem(), pos)); - return v; + v := reflect.MakeZero(p.Type()).(*reflect.PtrValue) + v.PointTo(subst(m, p.Elem(), pos)) + return v case *reflect.InterfaceValue: - v := reflect.MakeZero(p.Type()).(*reflect.InterfaceValue); - v.SetValue(subst(m, p.Elem(), pos)); - return v; + v := reflect.MakeZero(p.Type()).(*reflect.InterfaceValue) + v.SetValue(subst(m, p.Elem(), pos)) + return v } - return pattern; + return pattern } diff --git a/src/cmd/goyacc/goyacc.go b/src/cmd/goyacc/goyacc.go index cdaa7f1cd..59c975232 100644 --- a/src/cmd/goyacc/goyacc.go +++ b/src/cmd/goyacc/goyacc.go @@ -45,62 +45,62 @@ package main // import ( - "flag"; - "fmt"; - "bufio"; - "os"; + "flag" + "fmt" + "bufio" + "os" ) // the following are adjustable // according to memory size const ( - ACTSIZE = 30000; - NSTATES = 2000; - TEMPSIZE = 2000; + ACTSIZE = 30000 + NSTATES = 2000 + TEMPSIZE = 2000 - SYMINC = 50; // increase for non-term or term - RULEINC = 50; // increase for max rule length prodptr[i] - PRODINC = 100; // increase for productions prodptr - WSETINC = 50; // increase for working sets wsets - STATEINC = 200; // increase for states statemem + SYMINC = 50 // increase for non-term or term + RULEINC = 50 // increase for max rule length prodptr[i] + PRODINC = 100 // increase for productions prodptr + WSETINC = 50 // increase for working sets wsets + STATEINC = 200 // increase for states statemem - NAMESIZE = 50; - NTYPES = 63; - ISIZE = 400; + NAMESIZE = 50 + NTYPES = 63 + ISIZE = 400 - PRIVATE = 0xE000; // unicode private use + PRIVATE = 0xE000 // unicode private use // relationships which must hold: // TEMPSIZE >= NTERMS + NNONTERM + 1; // TEMPSIZE >= NSTATES; // - NTBASE = 010000; - ERRCODE = 8190; - ACCEPTCODE = 8191; - YYLEXUNK = 3; - TOKSTART = 4; //index of first defined token + NTBASE = 010000 + ERRCODE = 8190 + ACCEPTCODE = 8191 + YYLEXUNK = 3 + TOKSTART = 4 //index of first defined token ) // no, left, right, binary assoc. const ( - NOASC = iota; - LASC; - RASC; - BASC; + NOASC = iota + LASC + RASC + BASC ) // flags for state generation const ( - DONE = iota; - MUSTDO; - MUSTLOOKAHEAD; + DONE = iota + MUSTDO + MUSTLOOKAHEAD ) // flags for a rule having an action, and being reduced const ( - ACTFLAG = 1 << (iota + 2); - REDFLAG; + ACTFLAG = 1 << (iota + 2) + REDFLAG ) // output parser flags @@ -108,20 +108,20 @@ const YYFLAG = -1000 // parse tokens const ( - IDENTIFIER = PRIVATE + iota; - MARK; - TERM; - LEFT; - RIGHT; - BINARY; - PREC; - LCURLY; - IDENTCOLON; - NUMBER; - START; - TYPEDEF; - TYPENAME; - UNION; + IDENTIFIER = PRIVATE + iota + MARK + TERM + LEFT + RIGHT + BINARY + PREC + LCURLY + IDENTCOLON + NUMBER + START + TYPEDEF + TYPENAME + UNION ) const ENDFILE = 0 @@ -131,97 +131,97 @@ const OK = 1 const NOMORE = -1000 // macros for getting associativity and precedence levels -func ASSOC(i int) int { return i & 3 } +func ASSOC(i int) int { return i & 3 } -func PLEVEL(i int) int { return (i >> 4) & 077 } +func PLEVEL(i int) int { return (i >> 4) & 077 } -func TYPE(i int) int { return (i >> 10) & 077 } +func TYPE(i int) int { return (i >> 10) & 077 } // macros for setting associativity and precedence levels -func SETASC(i, j int) int { return i | j } +func SETASC(i, j int) int { return i | j } -func SETPLEV(i, j int) int { return i | (j << 4) } +func SETPLEV(i, j int) int { return i | (j << 4) } -func SETTYPE(i, j int) int { return i | (j << 10) } +func SETTYPE(i, j int) int { return i | (j << 10) } // I/O descriptors -var finput *bufio.Reader // input file +var finput *bufio.Reader // input file var stderr *bufio.Writer -var ftable *bufio.Writer // y.go file -var foutput *bufio.Writer // y.output file +var ftable *bufio.Writer // y.go file +var foutput *bufio.Writer // y.output file -var oflag string // -o [y.go] - y.go file -var vflag string // -v [y.output] - y.output file -var lflag bool // -l - disable line directives +var oflag string // -o [y.go] - y.go file +var vflag string // -v [y.output] - y.output file +var lflag bool // -l - disable line directives var stacksize = 200 // communication variables between various I/O routines -var infile string // input file name -var numbval int // value of an input number -var tokname string // input token name, slop for runes and 0 +var infile string // input file name +var numbval int // value of an input number +var tokname string // input token name, slop for runes and 0 var tokflag = false // structure declarations type Lkset []int type Pitem struct { - prod []int; - off int; // offset within the production - first int; // first term or non-term in item - prodno int; // production number for sorting + prod []int + off int // offset within the production + first int // first term or non-term in item + prodno int // production number for sorting } type Item struct { - pitem Pitem; - look Lkset; + pitem Pitem + look Lkset } type Symb struct { - name string; - value int; + name string + value int } type Wset struct { - pitem Pitem; - flag int; - ws Lkset; + pitem Pitem + flag int + ws Lkset } // storage of types -var ntypes int // number of types defined -var typeset [NTYPES]string // pointers to type tags +var ntypes int // number of types defined +var typeset [NTYPES]string // pointers to type tags // token information -var ntokens = 0 // number of tokens +var ntokens = 0 // number of tokens var tokset []Symb -var toklev []int // vector with the precedence of the terminals +var toklev []int // vector with the precedence of the terminals // nonterminal information -var nnonter = -1 // the number of nonterminals +var nnonter = -1 // the number of nonterminals var nontrst []Symb -var start int // start symbol +var start int // start symbol // state information -var nstate = 0 // number of states -var pstate = make([]int, NSTATES+2) // index into statemem to the descriptions of the states +var nstate = 0 // number of states +var pstate = make([]int, NSTATES+2) // index into statemem to the descriptions of the states var statemem []Item -var tystate = make([]int, NSTATES) // contains type information about the states -var tstates []int // states generated by terminal gotos -var ntstates []int // states generated by nonterminal gotos -var mstates = make([]int, NSTATES) // chain of overflows of term/nonterm generation lists -var lastred int // number of last reduction of a state -var defact = make([]int, NSTATES) // default actions of states +var tystate = make([]int, NSTATES) // contains type information about the states +var tstates []int // states generated by terminal gotos +var ntstates []int // states generated by nonterminal gotos +var mstates = make([]int, NSTATES) // chain of overflows of term/nonterm generation lists +var lastred int // number of last reduction of a state +var defact = make([]int, NSTATES) // default actions of states // lookahead set information var lkst []Lkset -var nolook = 0 // flag to turn off lookahead computations -var tbitset = 0 // size of lookahead sets -var clset Lkset // temporary storage for lookahead computations +var nolook = 0 // flag to turn off lookahead computations +var tbitset = 0 // size of lookahead sets +var clset Lkset // temporary storage for lookahead computations // working set information @@ -230,16 +230,16 @@ var cwp int // storage for action table -var amem []int // action table storage -var memp int // next free action table position -var indgo = make([]int, NSTATES) // index to the stored goto table +var amem []int // action table storage +var memp int // next free action table position +var indgo = make([]int, NSTATES) // index to the stored goto table // temporary vector, indexable by states, terms, or ntokens -var temp1 = make([]int, TEMPSIZE) // temporary storage, indexed by terms + ntokens or states -var lineno = 1 // current input line number -var fatfl = 1 // if on, error is fatal -var nerrors = 0 // number of errors +var temp1 = make([]int, TEMPSIZE) // temporary storage, indexed by terms + ntokens or states +var lineno = 1 // current input line number +var fatfl = 1 // if on, error is fatal +var nerrors = 0 // number of errors // assigned token type values @@ -247,10 +247,10 @@ var extval = 0 // grammar rule information -var nprod = 1 // number of productions -var prdptr [][]int // pointers to descriptions of productions -var levprd []int // precedence levels for the productions -var rlines []int // line number for this rule +var nprod = 1 // number of productions +var prdptr [][]int // pointers to descriptions of productions +var levprd []int // precedence levels for the productions +var rlines []int // line number for this rule // statistics collection variables @@ -270,29 +270,29 @@ var optst [][]int var ggreed []int var pgo []int -var maxspr int // maximum spread of any entry -var maxoff int // maximum offset into a array +var maxspr int // maximum spread of any entry +var maxoff int // maximum offset into a array var maxa int // storage for information about the nonterminals -var pres [][][]int // vector of pointers to productions yielding each nonterminal +var pres [][][]int // vector of pointers to productions yielding each nonterminal var pfirst []Lkset -var pempty []int // vector of nonterminals nontrivially deriving e +var pempty []int // vector of nonterminals nontrivially deriving e // random stuff picked out from between functions -var indebug = 0 // debugging flag for cpfir -var pidebug = 0 // debugging flag for putitem -var gsdebug = 0 // debugging flag for stagen -var cldebug = 0 // debugging flag for closure -var pkdebug = 0 // debugging flag for apack -var g2debug = 0 // debugging for go2gen -var adb = 0 // debugging for callopt +var indebug = 0 // debugging flag for cpfir +var pidebug = 0 // debugging flag for putitem +var gsdebug = 0 // debugging flag for stagen +var cldebug = 0 // debugging flag for closure +var pkdebug = 0 // debugging flag for apack +var g2debug = 0 // debugging for go2gen +var adb = 0 // debugging for callopt type Resrv struct { - name string; - value int; + name string + value int } var resrv = []Resrv{ @@ -316,59 +316,59 @@ const UTFmax = 0x3f func main() { - setup(); // initialize and read productions + setup() // initialize and read productions - tbitset = (ntokens + 32) / 32; - cpres(); // make table of which productions yield a given nonterminal - cempty(); // make a table of which nonterminals can match the empty string - cpfir(); // make a table of firsts of nonterminals + tbitset = (ntokens + 32) / 32 + cpres() // make table of which productions yield a given nonterminal + cempty() // make a table of which nonterminals can match the empty string + cpfir() // make a table of firsts of nonterminals - stagen(); // generate the states + stagen() // generate the states - yypgo = make([][]int, nnonter+1); - optst = make([][]int, nstate); - output(); // write the states and the tables - go2out(); + yypgo = make([][]int, nnonter+1) + optst = make([][]int, nstate) + output() // write the states and the tables + go2out() - hideprod(); - summary(); + hideprod() + summary() - callopt(); + callopt() - others(); + others() - exit(0); + exit(0) } func setup() { - var j, ty int; + var j, ty int - stderr = bufio.NewWriter(os.NewFile(2, "stderr")); - foutput = nil; + stderr = bufio.NewWriter(os.NewFile(2, "stderr")) + foutput = nil - flag.StringVar(&oflag, "o", "", "parser output"); - flag.StringVar(&vflag, "v", "", "create parsing tables"); - flag.BoolVar(&lflag, "l", false, "disable line directives"); + flag.StringVar(&oflag, "o", "", "parser output") + flag.StringVar(&vflag, "v", "", "create parsing tables") + flag.BoolVar(&lflag, "l", false, "disable line directives") - flag.Parse(); + flag.Parse() if flag.NArg() != 1 { usage() } if stacksize < 1 { // never set so cannot happen - fmt.Fprintf(stderr, "yacc: stack size too small\n"); - usage(); + fmt.Fprintf(stderr, "yacc: stack size too small\n") + usage() } - openup(); + openup() - defin(0, "$end"); - extval = PRIVATE; // tokens start in unicode 'private use' - defin(0, "error"); - defin(1, "$accept"); - defin(0, "$unk"); - i := 0; + defin(0, "$end") + extval = PRIVATE // tokens start in unicode 'private use' + defin(0, "error") + defin(1, "$accept") + defin(0, "$unk") + i := 0 - t := gettok(); + t := gettok() outer: for { @@ -382,25 +382,25 @@ outer: case ';': case START: - t = gettok(); + t = gettok() if t != IDENTIFIER { error("bad %%start construction") } - start = chfind(1, tokname); + start = chfind(1, tokname) case TYPEDEF: - t = gettok(); + t = gettok() if t != TYPENAME { error("bad syntax in %%type") } - ty = numbval; + ty = numbval for { - t = gettok(); + t = gettok() switch t { case IDENTIFIER: - t = chfind(1, tokname); + t = chfind(1, tokname) if t < NTBASE { - j = TYPE(toklev[t]); + j = TYPE(toklev[t]) if j != 0 && j != ty { error("type redeclaration of token ", tokset[t].name) @@ -408,7 +408,7 @@ outer: toklev[t] = SETTYPE(toklev[t], ty) } } else { - j = nontrst[t-NTBASE].value; + j = nontrst[t-NTBASE].value if j != 0 && j != ty { error("type redeclaration of nonterminal %v", nontrst[t-NTBASE].name) @@ -416,45 +416,45 @@ outer: nontrst[t-NTBASE].value = ty } } - continue; + continue case ',': continue } - break; + break } - continue; + continue case UNION: cpyunion() case LEFT, BINARY, RIGHT, TERM: // nonzero means new prec. and assoc. - lev := t - TERM; + lev := t - TERM if lev != 0 { i++ } - ty = 0; + ty = 0 // get identifiers so defined - t = gettok(); + t = gettok() // there is a type defined if t == TYPENAME { - ty = numbval; - t = gettok(); + ty = numbval + t = gettok() } for { switch t { case ',': - t = gettok(); - continue; + t = gettok() + continue case ';': break case IDENTIFIER: - j = chfind(0, tokname); + j = chfind(0, tokname) if j >= NTBASE { error("%v defined earlier as nonterminal", tokname) } @@ -462,31 +462,31 @@ outer: if ASSOC(toklev[j]) != 0 { error("redeclaration of precedence of %v", tokname) } - toklev[j] = SETASC(toklev[j], lev); - toklev[j] = SETPLEV(toklev[j], i); + toklev[j] = SETASC(toklev[j], lev) + toklev[j] = SETPLEV(toklev[j], i) } if ty != 0 { if TYPE(toklev[j]) != 0 { error("redeclaration of type of %v", tokname) } - toklev[j] = SETTYPE(toklev[j], ty); + toklev[j] = SETTYPE(toklev[j], ty) } - t = gettok(); + t = gettok() if t == NUMBER { - tokset[j].value = numbval; - t = gettok(); + tokset[j].value = numbval + t = gettok() } - continue; + continue } - break; + break } - continue; + continue case LCURLY: cpycode() } - t = gettok(); + t = gettok() } if t == ENDFILE { @@ -496,36 +496,36 @@ outer: // put out non-literal terminals for i := TOKSTART; i <= ntokens; i++ { // non-literals - c := tokset[i].name[0]; + c := tokset[i].name[0] if c != ' ' && c != '$' { fmt.Fprintf(ftable, "const\t%v\t= %v\n", tokset[i].name, tokset[i].value) } } // put out names of token names - fmt.Fprintf(ftable, "var\tToknames\t =[]string {\n"); + fmt.Fprintf(ftable, "var\tToknames\t =[]string {\n") for i := TOKSTART; i <= ntokens; i++ { fmt.Fprintf(ftable, "\t\"%v\",\n", tokset[i].name) } - fmt.Fprintf(ftable, "}\n"); + fmt.Fprintf(ftable, "}\n") // put out names of state names - fmt.Fprintf(ftable, "var\tStatenames\t =[]string {\n"); + fmt.Fprintf(ftable, "var\tStatenames\t =[]string {\n") // for i:=TOKSTART; i<=ntokens; i++ { // fmt.Fprintf(ftable, "\t\"%v\",\n", tokset[i].name); // } - fmt.Fprintf(ftable, "}\n"); + fmt.Fprintf(ftable, "}\n") - fmt.Fprintf(ftable, "\nfunc\n"); - fmt.Fprintf(ftable, "yyrun(p int, yypt int) {\n"); - fmt.Fprintf(ftable, "switch p {\n"); + fmt.Fprintf(ftable, "\nfunc\n") + fmt.Fprintf(ftable, "yyrun(p int, yypt int) {\n") + fmt.Fprintf(ftable, "switch p {\n") - moreprod(); - prdptr[0] = []int{NTBASE, start, 1, 0}; + moreprod() + prdptr[0] = []int{NTBASE, start, 1, 0} - nprod = 1; - curprod := make([]int, RULEINC); - t = gettok(); + nprod = 1 + curprod := make([]int, RULEINC) + t = gettok() if t != IDENTCOLON { error("bad syntax on first rule") } @@ -541,85 +541,85 @@ outer: // followd by -nprod for t != MARK && t != ENDFILE { - mem := 0; + mem := 0 // process a rule - rlines[nprod] = lineno; + rlines[nprod] = lineno if t == '|' { - curprod[mem] = prdptr[nprod-1][0]; - mem++; + curprod[mem] = prdptr[nprod-1][0] + mem++ } else if t == IDENTCOLON { - curprod[mem] = chfind(1, tokname); + curprod[mem] = chfind(1, tokname) if curprod[mem] < NTBASE { error("token illegal on LHS of grammar rule") } - mem++; + mem++ } else { error("illegal rule: missing semicolon or | ?") } // read rule body - t = gettok(); + t = gettok() for { for t == IDENTIFIER { - curprod[mem] = chfind(1, tokname); + curprod[mem] = chfind(1, tokname) if curprod[mem] < NTBASE { levprd[nprod] = toklev[curprod[mem]] } - mem++; + mem++ if mem >= len(curprod) { - ncurprod := make([]int, mem+RULEINC); - copy(ncurprod, curprod); - curprod = ncurprod; + ncurprod := make([]int, mem+RULEINC) + copy(ncurprod, curprod) + curprod = ncurprod } - t = gettok(); + t = gettok() } if t == PREC { if gettok() != IDENTIFIER { error("illegal %%prec syntax") } - j = chfind(2, tokname); + j = chfind(2, tokname) if j >= NTBASE { error("nonterminal " + nontrst[j-NTBASE].name + " illegal after %%prec") } - levprd[nprod] = toklev[j]; - t = gettok(); + levprd[nprod] = toklev[j] + t = gettok() } if t != '=' { break } - levprd[nprod] |= ACTFLAG; - fmt.Fprintf(ftable, "\ncase %v:", nprod); - cpyact(curprod, mem); + levprd[nprod] |= ACTFLAG + fmt.Fprintf(ftable, "\ncase %v:", nprod) + cpyact(curprod, mem) // action within rule... - t = gettok(); + t = gettok() if t == IDENTIFIER { // make it a nonterminal - j = chfind(1, fmt.Sprintf("$$%v", nprod)); + j = chfind(1, fmt.Sprintf("$$%v", nprod)) // // the current rule will become rule number nprod+1 // enter null production for action // - prdptr[nprod] = make([]int, 2); - prdptr[nprod][0] = j; - prdptr[nprod][1] = -nprod; + prdptr[nprod] = make([]int, 2) + prdptr[nprod][0] = j + prdptr[nprod][1] = -nprod // update the production information - nprod++; - moreprod(); - levprd[nprod] = levprd[nprod-1] & ^ACTFLAG; - levprd[nprod-1] = ACTFLAG; - rlines[nprod] = lineno; + nprod++ + moreprod() + levprd[nprod] = levprd[nprod-1] & ^ACTFLAG + levprd[nprod-1] = ACTFLAG + rlines[nprod] = lineno // make the action appear in the original rule - curprod[mem] = j; - mem++; + curprod[mem] = j + mem++ if mem >= len(curprod) { - ncurprod := make([]int, mem+RULEINC); - copy(ncurprod, curprod); - curprod = ncurprod; + ncurprod := make([]int, mem+RULEINC) + copy(ncurprod, curprod) + curprod = ncurprod } } } @@ -627,14 +627,14 @@ outer: for t == ';' { t = gettok() } - curprod[mem] = -nprod; - mem++; + curprod[mem] = -nprod + mem++ // check that default action is reasonable if ntypes != 0 && (levprd[nprod]&ACTFLAG) == 0 && nontrst[curprod[0]-NTBASE].value != 0 { // no explicit action, LHS has value - tempty := curprod[1]; + tempty := curprod[1] if tempty < 0 { error("must return a value, since LHS has a type") } @@ -646,16 +646,16 @@ outer: if tempty != nontrst[curprod[0]-NTBASE].value { error("default action causes potential type clash") } - fmt.Fprintf(ftable, "\ncase %v:", nprod); + fmt.Fprintf(ftable, "\ncase %v:", nprod) fmt.Fprintf(ftable, "\n\tYYVAL.%v = YYS[yypt-0].%v;", - typeset[tempty], typeset[tempty]); + typeset[tempty], typeset[tempty]) } - moreprod(); - prdptr[nprod] = make([]int, mem); - copy(prdptr[nprod], curprod); - nprod++; - moreprod(); - levprd[nprod] = 0; + moreprod() + prdptr[nprod] = make([]int, mem) + copy(prdptr[nprod], curprod) + nprod++ + moreprod() + levprd[nprod] = 0 } // @@ -663,12 +663,12 @@ outer: // dump out the prefix code // - fmt.Fprintf(ftable, "\n\t}"); - fmt.Fprintf(ftable, "\n}\n"); + fmt.Fprintf(ftable, "\n\t}") + fmt.Fprintf(ftable, "\n}\n") - fmt.Fprintf(ftable, "const YYEOFCODE = 1\n"); - fmt.Fprintf(ftable, "const YYERRCODE = 2\n"); - fmt.Fprintf(ftable, "const YYMAXDEPTH = %v\n", stacksize); + fmt.Fprintf(ftable, "const YYEOFCODE = 1\n") + fmt.Fprintf(ftable, "const YYERRCODE = 2\n") + fmt.Fprintf(ftable, "const YYMAXDEPTH = %v\n", stacksize) // // copy any postfix code @@ -678,11 +678,11 @@ outer: fmt.Fprintf(ftable, "\n//line %v:%v\n", infile, lineno) } for { - c := getrune(finput); + c := getrune(finput) if c == EOF { break } - putrune(ftable, c); + putrune(ftable, c) } } } @@ -691,20 +691,20 @@ outer: // allocate enough room to hold another production // func moreprod() { - n := len(prdptr); + n := len(prdptr) if nprod >= n { - nn := n + PRODINC; - aprod := make([][]int, nn); - alevprd := make([]int, nn); - arlines := make([]int, nn); + nn := n + PRODINC + aprod := make([][]int, nn) + alevprd := make([]int, nn) + arlines := make([]int, nn) - copy(aprod, prdptr); - copy(alevprd, levprd); - copy(arlines, rlines); + copy(aprod, prdptr) + copy(alevprd, levprd) + copy(arlines, rlines) - prdptr = aprod; - levprd = alevprd; - rlines = arlines; + prdptr = aprod + levprd = alevprd + rlines = arlines } } @@ -713,39 +713,39 @@ func moreprod() { // or a nonterminal if t=1 // func defin(nt int, s string) int { - val := 0; + val := 0 if nt != 0 { - nnonter++; + nnonter++ if nnonter >= len(nontrst) { - anontrst := make([]Symb, nnonter+SYMINC); - copy(anontrst, nontrst); - nontrst = anontrst; + anontrst := make([]Symb, nnonter+SYMINC) + copy(anontrst, nontrst) + nontrst = anontrst } - nontrst[nnonter] = Symb{s, 0}; - return NTBASE + nnonter; + nontrst[nnonter] = Symb{s, 0} + return NTBASE + nnonter } // must be a token - ntokens++; + ntokens++ if ntokens >= len(tokset) { - nn := ntokens + SYMINC; - atokset := make([]Symb, nn); - atoklev := make([]int, nn); + nn := ntokens + SYMINC + atokset := make([]Symb, nn) + atoklev := make([]int, nn) - copy(atoklev, toklev); - copy(atokset, tokset); + copy(atoklev, toklev) + copy(atokset, tokset) - tokset = atokset; - toklev = atoklev; + tokset = atokset + toklev = atoklev } - tokset[ntokens].name = s; - toklev[ntokens] = 0; + tokset[ntokens].name = s + toklev[ntokens] = 0 // establish value for token // single character literal if s[0] == ' ' && len(s) == 1+1 { val = int(s[1]) - } else if s[0] == ' ' && s[1] == '\\' { // escape sequence + } else if s[0] == ' ' && s[1] == '\\' { // escape sequence if len(s) == 2+1 { // single character escape sequence switch s[2] { @@ -770,11 +770,11 @@ func defin(nt int, s string) int { default: error("invalid escape %v", s[1:3]) } - } else if s[2] == 'u' && len(s) == 2+1+4 { // \unnnn sequence - val = 0; - s = s[3:]; + } else if s[2] == 'u' && len(s) == 2+1+4 { // \unnnn sequence + val = 0 + s = s[3:] for s != "" { - c := int(s[0]); + c := int(s[0]) switch { case c >= '0' && c <= '9': c -= '0' @@ -785,8 +785,8 @@ func defin(nt int, s string) int { default: error("illegal \\unnnn construction") } - val = val*16 + c; - s = s[1:]; + val = val*16 + c + s = s[1:] } if val == 0 { error("'\\u0000' is illegal") @@ -795,36 +795,36 @@ func defin(nt int, s string) int { error("unknown escape") } } else { - val = extval; - extval++; + val = extval + extval++ } - tokset[ntokens].value = val; - return ntokens; + tokset[ntokens].value = val + return ntokens } var peekline = 0 func gettok() int { - var i, match, c int; + var i, match, c int - tokname = ""; + tokname = "" for { - lineno += peekline; - peekline = 0; - c = getrune(finput); + lineno += peekline + peekline = 0 + c = getrune(finput) for c == ' ' || c == '\n' || c == '\t' || c == '\v' || c == '\r' { if c == '\n' { lineno++ } - c = getrune(finput); + c = getrune(finput) } // skip comment -- fix if c != '/' { break } - lineno += skipcom(); + lineno += skipcom() } switch c { @@ -832,21 +832,21 @@ func gettok() int { if tokflag { fmt.Printf(">>> ENDFILE %v\n", lineno) } - return ENDFILE; + return ENDFILE case '{': - ungetrune(finput, c); + ungetrune(finput, c) if tokflag { fmt.Printf(">>> ={ %v\n", lineno) } - return '='; + return '=' case '<': // get, and look up, a type name (union member name) - c = getrune(finput); + c = getrune(finput) for c != '>' && c != EOF && c != '\n' { - tokname += string(c); - c = getrune(finput); + tokname += string(c) + c = getrune(finput) } if c != '>' { @@ -855,62 +855,62 @@ func gettok() int { for i = 1; i <= ntypes; i++ { if typeset[i] == tokname { - numbval = i; + numbval = i if tokflag { fmt.Printf(">>> TYPENAME old <%v> %v\n", tokname, lineno) } - return TYPENAME; + return TYPENAME } } - ntypes++; - numbval = ntypes; - typeset[numbval] = tokname; + ntypes++ + numbval = ntypes + typeset[numbval] = tokname if tokflag { fmt.Printf(">>> TYPENAME new <%v> %v\n", tokname, lineno) } - return TYPENAME; + return TYPENAME case '"', '\'': - match = c; - tokname = " "; + match = c + tokname = " " for { - c = getrune(finput); + c = getrune(finput) if c == '\n' || c == EOF { error("illegal or missing ' or \"") } if c == '\\' { - tokname += string('\\'); - c = getrune(finput); + tokname += string('\\') + c = getrune(finput) } else if c == match { if tokflag { fmt.Printf(">>> IDENTIFIER \"%v\" %v\n", tokname, lineno) } - return IDENTIFIER; + return IDENTIFIER } - tokname += string(c); + tokname += string(c) } case '%': - c = getrune(finput); + c = getrune(finput) switch c { case '%': if tokflag { fmt.Printf(">>> MARK %%%% %v\n", lineno) } - return MARK; + return MARK case '=': if tokflag { fmt.Printf(">>> PREC %%= %v\n", lineno) } - return PREC; + return PREC case '{': if tokflag { fmt.Printf(">>> LCURLY %%{ %v\n", lineno) } - return LCURLY; + return LCURLY } - getword(c); + getword(c) // find a reserved word for c = 0; c < len(resrv); c++ { if tokname == resrv[c].name { @@ -918,39 +918,39 @@ func gettok() int { fmt.Printf(">>> %%%v %v %v\n", tokname, resrv[c].value-PRIVATE, lineno) } - return resrv[c].value; + return resrv[c].value } } - error("invalid escape, or illegal reserved word: %v", tokname); + error("invalid escape, or illegal reserved word: %v", tokname) case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - numbval = c - '0'; + numbval = c - '0' for { - c = getrune(finput); + c = getrune(finput) if !isdigit(c) { break } - numbval = numbval*10 + c - '0'; + numbval = numbval*10 + c - '0' } - ungetrune(finput, c); + ungetrune(finput, c) if tokflag { fmt.Printf(">>> NUMBER %v %v\n", numbval, lineno) } - return NUMBER; + return NUMBER default: if isword(c) || c == '.' || c == '$' { - getword(c); - break; + getword(c) + break } if tokflag { fmt.Printf(">>> OPERATOR %v %v\n", string(c), lineno) } - return c; + return c } // look ahead to distinguish IDENTIFIER from IDENTCOLON - c = getrune(finput); + c = getrune(finput) for c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\r' || c == '/' { if c == '\n' { peekline++ @@ -959,49 +959,49 @@ func gettok() int { if c == '/' { peekline += skipcom() } - c = getrune(finput); + c = getrune(finput) } if c == ':' { if tokflag { fmt.Printf(">>> IDENTCOLON %v: %v\n", tokname, lineno) } - return IDENTCOLON; + return IDENTCOLON } - ungetrune(finput, c); + ungetrune(finput, c) if tokflag { fmt.Printf(">>> IDENTIFIER %v %v\n", tokname, lineno) } - return IDENTIFIER; + return IDENTIFIER } func getword(c int) { - tokname = ""; + tokname = "" for isword(c) || isdigit(c) || c == '_' || c == '.' || c == '$' { - tokname += string(c); - c = getrune(finput); + tokname += string(c) + c = getrune(finput) } - ungetrune(finput, c); + ungetrune(finput, c) } // // determine the type of a symbol // func fdtype(t int) int { - var v int; - var s string; + var v int + var s string if t >= NTBASE { - v = nontrst[t-NTBASE].value; - s = nontrst[t-NTBASE].name; + v = nontrst[t-NTBASE].value + s = nontrst[t-NTBASE].name } else { - v = TYPE(toklev[t]); - s = tokset[t].name; + v = TYPE(toklev[t]) + s = tokset[t].name } if v <= 0 { error("must specify type for %v", s) } - return v; + return v } func chfind(t int, s string) int { @@ -1023,7 +1023,7 @@ func chfind(t int, s string) int { if t > 1 { error("%v should have been defined earlier", s) } - return defin(t, s); + return defin(t, s) } // @@ -1034,17 +1034,17 @@ func cpyunion() { if !lflag { fmt.Fprintf(ftable, "\n//line %v %v\n", lineno, infile) } - fmt.Fprintf(ftable, "type\tYYSTYPE\tstruct"); + fmt.Fprintf(ftable, "type\tYYSTYPE\tstruct") - level := 0; + level := 0 out: for { - c := getrune(finput); + c := getrune(finput) if c == EOF { error("EOF encountered while processing %%union") } - putrune(ftable, c); + putrune(ftable, c) switch c { case '\n': lineno++ @@ -1052,50 +1052,50 @@ out: if level == 0 { fmt.Fprintf(ftable, "\n\tyys\tint;") } - level++; + level++ case '}': - level--; + level-- if level == 0 { break out } } } - fmt.Fprintf(ftable, "\n"); - fmt.Fprintf(ftable, "var\tyylval\tYYSTYPE\n"); - fmt.Fprintf(ftable, "var\tYYVAL\tYYSTYPE\n"); - fmt.Fprintf(ftable, "var\tYYS\t[%v]YYSTYPE\n", stacksize); + fmt.Fprintf(ftable, "\n") + fmt.Fprintf(ftable, "var\tyylval\tYYSTYPE\n") + fmt.Fprintf(ftable, "var\tYYVAL\tYYSTYPE\n") + fmt.Fprintf(ftable, "var\tYYS\t[%v]YYSTYPE\n", stacksize) } // // saves code between %{ and %} // func cpycode() { - lno := lineno; + lno := lineno - c := getrune(finput); + c := getrune(finput) if c == '\n' { - c = getrune(finput); - lineno++; + c = getrune(finput) + lineno++ } if !lflag { fmt.Fprintf(ftable, "\n//line %v %v\n", lineno, infile) } for c != EOF { if c == '%' { - c = getrune(finput); + c = getrune(finput) if c == '}' { return } - putrune(ftable, '%'); + putrune(ftable, '%') } - putrune(ftable, c); + putrune(ftable, c) if c == '\n' { lineno++ } - c = getrune(finput); + c = getrune(finput) } - lineno = lno; - error("eof before %%}"); + lineno = lno + error("eof before %%}") } //func @@ -1171,50 +1171,50 @@ func cpycode() { // skipcom is called after reading a '/' // func skipcom() int { - var c int; + var c int - c = getrune(finput); + c = getrune(finput) if c == '/' { for c != EOF { if c == '\n' { return 1 } - c = getrune(finput); + c = getrune(finput) } - error("EOF inside comment"); - return 0; + error("EOF inside comment") + return 0 } if c != '*' { error("illegal comment") } - nl := 0; // lines skipped - c = getrune(finput); + nl := 0 // lines skipped + c = getrune(finput) l1: switch c { case '*': - c = getrune(finput); + c = getrune(finput) if c == '/' { break } - goto l1; + goto l1 case '\n': - nl++; - fallthrough; + nl++ + fallthrough default: - c = getrune(finput); - goto l1; + c = getrune(finput) + goto l1 } - return nl; + return nl } func dumpprod(curprod []int, max int) { - fmt.Printf("\n"); + fmt.Printf("\n") for i := 0; i < max; i++ { - p := curprod[i]; + p := curprod[i] if p < 0 { fmt.Printf("[%v] %v\n", i, p) } else { @@ -1232,77 +1232,77 @@ func cpyact(curprod []int, max int) { fmt.Fprintf(ftable, "\n//line %v %v\n", lineno, infile) } - lno := lineno; - brac := 0; + lno := lineno + brac := 0 loop: for { - c := getrune(finput); + c := getrune(finput) swt: switch c { case ';': if brac == 0 { - putrune(ftable, c); - return; + putrune(ftable, c) + return } case '{': if brac == 0 { } - putrune(ftable, '\t'); - brac++; + putrune(ftable, '\t') + brac++ case '$': - s := 1; - tok := -1; - c = getrune(finput); + s := 1 + tok := -1 + c = getrune(finput) // type description if c == '<' { - ungetrune(finput, c); + ungetrune(finput, c) if gettok() != TYPENAME { error("bad syntax on $<ident> clause") } - tok = numbval; - c = getrune(finput); + tok = numbval + c = getrune(finput) } if c == '$' { - fmt.Fprintf(ftable, "YYVAL"); + fmt.Fprintf(ftable, "YYVAL") // put out the proper tag... if ntypes != 0 { if tok < 0 { tok = fdtype(curprod[0]) } - fmt.Fprintf(ftable, ".%v", typeset[tok]); + fmt.Fprintf(ftable, ".%v", typeset[tok]) } - continue loop; + continue loop } if c == '-' { - s = -s; - c = getrune(finput); + s = -s + c = getrune(finput) } - j := 0; + j := 0 if isdigit(c) { for isdigit(c) { - j = j*10 + c - '0'; - c = getrune(finput); + j = j*10 + c - '0' + c = getrune(finput) } - ungetrune(finput, c); - j = j * s; + ungetrune(finput, c) + j = j * s if j >= max { error("Illegal use of $%v", j) } } else if isword(c) || c == '_' || c == '.' { // look for $name - ungetrune(finput, c); + ungetrune(finput, c) if gettok() != IDENTIFIER { error("$ must be followed by an identifier") } - tokn := chfind(2, tokname); - fnd := -1; - c = getrune(finput); + tokn := chfind(2, tokname) + fnd := -1 + c = getrune(finput) if c != '@' { ungetrune(finput, c) } else if gettok() != NUMBER { @@ -1312,7 +1312,7 @@ loop: } for j = 1; j < max; j++ { if tokn == curprod[j] { - fnd--; + fnd-- if fnd <= 0 { break } @@ -1322,14 +1322,14 @@ loop: error("$name or $name@number not found") } } else { - putrune(ftable, '$'); + putrune(ftable, '$') if s < 0 { putrune(ftable, '-') } - ungetrune(finput, c); - continue loop; + ungetrune(finput, c) + continue loop } - fmt.Fprintf(ftable, "YYS[yypt-%v]", max-j-1); + fmt.Fprintf(ftable, "YYS[yypt-%v]", max-j-1) // put out the proper tag if ntypes != 0 { @@ -1339,41 +1339,41 @@ loop: if tok < 0 { tok = fdtype(curprod[j]) } - fmt.Fprintf(ftable, ".%v", typeset[tok]); + fmt.Fprintf(ftable, ".%v", typeset[tok]) } - continue loop; + continue loop case '}': - brac--; + brac-- if brac != 0 { break } - putrune(ftable, c); - return; + putrune(ftable, c) + return case '/': // a comment - putrune(ftable, c); - c = getrune(finput); + putrune(ftable, c) + c = getrune(finput) for c != EOF { if c == '\n' { - lineno++; - break swt; + lineno++ + break swt } - putrune(ftable, c); - c = getrune(finput); + putrune(ftable, c) + c = getrune(finput) } - error("EOF inside comment"); + error("EOF inside comment") case '\'', '"': // character string or constant - match := c; - putrune(ftable, c); - c = getrune(finput); + match := c + putrune(ftable, c) + c = getrune(finput) for c != EOF { if c == '\\' { - putrune(ftable, c); - c = getrune(finput); + putrune(ftable, c) + c = getrune(finput) if c == '\n' { lineno++ } @@ -1383,43 +1383,43 @@ loop: if c == '\n' { error("newline in string or char const") } - putrune(ftable, c); - c = getrune(finput); + putrune(ftable, c) + c = getrune(finput) } - error("EOF in string or character constant"); + error("EOF in string or character constant") case EOF: - lineno = lno; - error("action does not terminate"); + lineno = lno + error("action does not terminate") case '\n': lineno++ } - putrune(ftable, c); + putrune(ftable, c) } } func openup() { - infile = flag.Arg(0); - finput = open(infile); + infile = flag.Arg(0) + finput = open(infile) if finput == nil { error("cannot open %v", infile) } - foutput = nil; + foutput = nil if vflag != "" { - foutput = create(vflag, 0666); + foutput = create(vflag, 0666) if foutput == nil { error("can't create file %v", vflag) } } - ftable = nil; + ftable = nil if oflag == "" { oflag = "y.go" } - ftable = create(oflag, 0666); + ftable = create(oflag, 0666) if ftable == nil { error("can't create file %v", oflag) } @@ -1430,7 +1430,7 @@ func openup() { // return a pointer to the name of symbol i // func symnam(i int) string { - var s string; + var s string if i >= NTBASE { s = nontrst[i-NTBASE].name @@ -1440,7 +1440,7 @@ func symnam(i int) string { if s[0] == ' ' { s = s[1:] } - return s; + return s } // @@ -1458,8 +1458,8 @@ func aryfil(v []int, n, c int) { // the array pyield has the lists: the total size is only NPROD+1 // func cpres() { - pres = make([][][]int, nnonter+1); - curres := make([][]int, nprod); + pres = make([][][]int, nnonter+1) + curres := make([][]int, nprod) if false { for j := 0; j <= nnonter; j++ { @@ -1470,41 +1470,41 @@ func cpres() { } } - fatfl = 0; // make undefined symbols nonfatal + fatfl = 0 // make undefined symbols nonfatal for i := 0; i <= nnonter; i++ { - n := 0; - c := i + NTBASE; + n := 0 + c := i + NTBASE for j := 0; j < nprod; j++ { if prdptr[j][0] == c { - curres[n] = prdptr[j][1:]; - n++; + curres[n] = prdptr[j][1:] + n++ } } if n == 0 { - error("nonterminal %v not defined", nontrst[i].name); - continue; + error("nonterminal %v not defined", nontrst[i].name) + continue } - pres[i] = make([][]int, n); - copy(pres[i], curres); + pres[i] = make([][]int, n) + copy(pres[i], curres) } - fatfl = 1; + fatfl = 1 if nerrors != 0 { - summary(); - exit(1); + summary() + exit(1) } } func dumppres() { for i := 0; i <= nnonter; i++ { - print("nonterm %d\n", i); - curres := pres[i]; + print("nonterm %d\n", i) + curres := pres[i] for j := 0; j < len(curres); j++ { - print("\tproduction %d:", j); - prd := curres[j]; + print("\tproduction %d:", j) + prd := curres[j] for k := 0; k < len(prd); k++ { print(" %d", prd[k]) } - print("\n"); + print("\n") } } } @@ -1514,24 +1514,24 @@ func dumppres() { // also, look for nonterminals which don't derive any token strings // func cempty() { - var i, p, np int; - var prd []int; + var i, p, np int + var prd []int - pempty = make([]int, nnonter+1); + pempty = make([]int, nnonter+1) // first, use the array pempty to detect productions that can never be reduced // set pempty to WHONOWS - aryfil(pempty, nnonter+1, WHOKNOWS); + aryfil(pempty, nnonter+1, WHOKNOWS) // now, look at productions, marking nonterminals which derive something more: for { for i = 0; i < nprod; i++ { - prd = prdptr[i]; + prd = prdptr[i] if pempty[prd[0]-NTBASE] != 0 { continue } - np = len(prd) - 1; + np = len(prd) - 1 for p = 1; p < np; p++ { if prd[p] >= NTBASE && pempty[prd[p]-NTBASE] == WHOKNOWS { break @@ -1539,11 +1539,11 @@ more: } // production can be derived if p == np { - pempty[prd[0]-NTBASE] = OK; - continue more; + pempty[prd[0]-NTBASE] = OK + continue more } } - break; + break } // now, look at the nonterminals, to see if they are all OK @@ -1553,19 +1553,19 @@ more: continue } if pempty[i] != OK { - fatfl = 0; - error("nonterminal " + nontrst[i].name + " never derives any token string"); + fatfl = 0 + error("nonterminal " + nontrst[i].name + " never derives any token string") } } if nerrors != 0 { - summary(); - exit(1); + summary() + exit(1) } // now, compute the pempty array, to see which nonterminals derive the empty string // set pempty to WHOKNOWS - aryfil(pempty, nnonter+1, WHOKNOWS); + aryfil(pempty, nnonter+1, WHOKNOWS) // loop as long as we keep finding empty nonterminals @@ -1574,11 +1574,11 @@ again: next: for i = 1; i < nprod; i++ { // not known to be empty - prd = prdptr[i]; + prd = prdptr[i] if pempty[prd[0]-NTBASE] != WHOKNOWS { continue } - np = len(prd) - 1; + np = len(prd) - 1 for p = 1; p < np; p++ { if prd[p] < NTBASE || pempty[prd[p]-NTBASE] != EMPTY { continue next @@ -1586,12 +1586,12 @@ again: } // we have a nontrivially empty nonterminal - pempty[prd[0]-NTBASE] = EMPTY; + pempty[prd[0]-NTBASE] = EMPTY // got one ... try for another - continue again; + continue again } - return; + return } } @@ -1607,27 +1607,27 @@ func dumpempty() { // compute an array with the first of nonterminals // func cpfir() { - var s, n, p, np, ch, i int; - var curres [][]int; - var prd []int; + var s, n, p, np, ch, i int + var curres [][]int + var prd []int - wsets = make([]Wset, nnonter+WSETINC); - pfirst = make([]Lkset, nnonter+1); + wsets = make([]Wset, nnonter+WSETINC) + pfirst = make([]Lkset, nnonter+1) for i = 0; i <= nnonter; i++ { - wsets[i].ws = mkset(); - pfirst[i] = mkset(); - curres = pres[i]; - n = len(curres); + wsets[i].ws = mkset() + pfirst[i] = mkset() + curres = pres[i] + n = len(curres) // initially fill the sets for s = 0; s < n; s++ { - prd = curres[s]; - np = len(prd) - 1; + prd = curres[s] + np = len(prd) - 1 for p = 0; p < np; p++ { - ch = prd[p]; + ch = prd[p] if ch < NTBASE { - setbit(pfirst[i], ch); - break; + setbit(pfirst[i], ch) + break } if pempty[ch-NTBASE] == 0 { break @@ -1637,21 +1637,21 @@ func cpfir() { } // now, reflect transitivity - changes := 1; + changes := 1 for changes != 0 { - changes = 0; + changes = 0 for i = 0; i <= nnonter; i++ { - curres = pres[i]; - n = len(curres); + curres = pres[i] + n = len(curres) for s = 0; s < n; s++ { - prd = curres[s]; - np = len(prd) - 1; + prd = curres[s] + np = len(prd) - 1 for p = 0; p < np; p++ { - ch = prd[p] - NTBASE; + ch = prd[p] - NTBASE if ch < 0 { break } - changes |= setunion(pfirst[i], pfirst[ch]); + changes |= setunion(pfirst[i], pfirst[ch]) if pempty[ch] == 0 { break } @@ -1676,20 +1676,20 @@ func cpfir() { // func stagen() { // initialize - nstate = 0; - tstates = make([]int, ntokens+1); // states generated by terminal gotos - ntstates = make([]int, nnonter+1); // states generated by nonterminal gotos - amem = make([]int, ACTSIZE); - memp = 0; - - clset = mkset(); - pstate[0] = 0; - pstate[1] = 0; - aryfil(clset, tbitset, 0); - putitem(Pitem{prdptr[0], 0, 0, 0}, clset); - tystate[0] = MUSTDO; - nstate = 1; - pstate[2] = pstate[1]; + nstate = 0 + tstates = make([]int, ntokens+1) // states generated by terminal gotos + ntstates = make([]int, nnonter+1) // states generated by nonterminal gotos + amem = make([]int, ACTSIZE) + memp = 0 + + clset = mkset() + pstate[0] = 0 + pstate[1] = 0 + aryfil(clset, tbitset, 0) + putitem(Pitem{prdptr[0], 0, 0, 0}, clset) + tystate[0] = MUSTDO + nstate = 1 + pstate[2] = pstate[1] // // now, the main state generation loop @@ -1698,67 +1698,67 @@ func stagen() { // could be sped up a lot by remembering // results of the first pass rather than recomputing // - first := 1; + first := 1 for more := 1; more != 0; first = 0 { - more = 0; + more = 0 for i := 0; i < nstate; i++ { if tystate[i] != MUSTDO { continue } - tystate[i] = DONE; - aryfil(temp1, nnonter+1, 0); + tystate[i] = DONE + aryfil(temp1, nnonter+1, 0) // take state i, close it, and do gotos - closure(i); + closure(i) // generate goto's for p := 0; p < cwp; p++ { - pi := wsets[p]; + pi := wsets[p] if pi.flag != 0 { continue } - wsets[p].flag = 1; - c := pi.pitem.first; + wsets[p].flag = 1 + c := pi.pitem.first if c <= 1 { if pstate[i+1]-pstate[i] <= p { tystate[i] = MUSTLOOKAHEAD } - continue; + continue } // do a goto on c - putitem(wsets[p].pitem, wsets[p].ws); + putitem(wsets[p].pitem, wsets[p].ws) for q := p + 1; q < cwp; q++ { // this item contributes to the goto if c == wsets[q].pitem.first { - putitem(wsets[q].pitem, wsets[q].ws); - wsets[q].flag = 1; + putitem(wsets[q].pitem, wsets[q].ws) + wsets[q].flag = 1 } } if c < NTBASE { - state(c) // register new state + state(c) // register new state } else { temp1[c-NTBASE] = state(c) } } if gsdebug != 0 && foutput != nil { - fmt.Fprintf(foutput, "%v: ", i); + fmt.Fprintf(foutput, "%v: ", i) for j := 0; j <= nnonter; j++ { if temp1[j] != 0 { fmt.Fprintf(foutput, "%v %v,", nontrst[j].name, temp1[j]) } } - fmt.Fprintf(foutput, "\n"); + fmt.Fprintf(foutput, "\n") } if first != 0 { indgo[i] = apack(temp1[1:], nnonter-1) - 1 } - more++; + more++ } } } @@ -1767,67 +1767,67 @@ func stagen() { // generate the closure of state i // func closure(i int) { - zzclose++; + zzclose++ // first, copy kernel of state i to wsets - cwp = 0; - q := pstate[i+1]; + cwp = 0 + q := pstate[i+1] for p := pstate[i]; p < q; p++ { - wsets[cwp].pitem = statemem[p].pitem; - wsets[cwp].flag = 1; // this item must get closed - copy(wsets[cwp].ws, statemem[p].look); - cwp++; + wsets[cwp].pitem = statemem[p].pitem + wsets[cwp].flag = 1 // this item must get closed + copy(wsets[cwp].ws, statemem[p].look) + cwp++ } // now, go through the loop, closing each item - work := 1; + work := 1 for work != 0 { - work = 0; + work = 0 for u := 0; u < cwp; u++ { if wsets[u].flag == 0 { continue } // dot is before c - c := wsets[u].pitem.first; + c := wsets[u].pitem.first if c < NTBASE { - wsets[u].flag = 0; + wsets[u].flag = 0 // only interesting case is where . is before nonterminal - continue; + continue } // compute the lookahead - aryfil(clset, tbitset, 0); + aryfil(clset, tbitset, 0) // find items involving c for v := u; v < cwp; v++ { if wsets[v].flag != 1 || wsets[v].pitem.first != c { continue } - pi := wsets[v].pitem.prod; - ipi := wsets[v].pitem.off + 1; + pi := wsets[v].pitem.prod + ipi := wsets[v].pitem.off + 1 - wsets[v].flag = 0; + wsets[v].flag = 0 if nolook != 0 { continue } - ch := pi[ipi]; - ipi++; + ch := pi[ipi] + ipi++ for ch > 0 { // terminal symbol if ch < NTBASE { - setbit(clset, ch); - break; + setbit(clset, ch) + break } // nonterminal symbol - setunion(clset, pfirst[ch-NTBASE]); + setunion(clset, pfirst[ch-NTBASE]) if pempty[ch-NTBASE] == 0 { break } - ch = pi[ipi]; - ipi++; + ch = pi[ipi] + ipi++ } if ch <= 0 { setunion(clset, wsets[v].ws) @@ -1837,13 +1837,13 @@ func closure(i int) { // // now loop over productions derived from c // - curres := pres[c-NTBASE]; - n := len(curres); + curres := pres[c-NTBASE] + n := len(curres) nexts: // initially fill the sets for s := 0; s < n; s++ { - prd := curres[s]; + prd := curres[s] // // put these items into the closure @@ -1855,42 +1855,42 @@ func closure(i int) { aryeq(wsets[v].pitem.prod, prd) != 0 { if nolook == 0 && setunion(wsets[v].ws, clset) != 0 { - wsets[v].flag = 1; - work = 1; + wsets[v].flag = 1 + work = 1 } - continue nexts; + continue nexts } } // not there; make a new entry if cwp >= len(wsets) { - awsets := make([]Wset, cwp+WSETINC); - copy(awsets, wsets); - wsets = awsets; + awsets := make([]Wset, cwp+WSETINC) + copy(awsets, wsets) + wsets = awsets } - wsets[cwp].pitem = Pitem{prd, 0, prd[0], -prd[len(prd)-1]}; - wsets[cwp].flag = 1; - wsets[cwp].ws = mkset(); + wsets[cwp].pitem = Pitem{prd, 0, prd[0], -prd[len(prd)-1]} + wsets[cwp].flag = 1 + wsets[cwp].ws = mkset() if nolook == 0 { - work = 1; - copy(wsets[cwp].ws, clset); + work = 1 + copy(wsets[cwp].ws, clset) } - cwp++; + cwp++ } } } // have computed closure; flags are reset; return if cldebug != 0 && foutput != nil { - fmt.Fprintf(foutput, "\nState %v, nolook = %v\n", i, nolook); + fmt.Fprintf(foutput, "\nState %v, nolook = %v\n", i, nolook) for u := 0; u < cwp; u++ { if wsets[u].flag != 0 { fmt.Fprintf(foutput, "flag set\n") } - wsets[u].flag = 0; - fmt.Fprintf(foutput, "\t%v", writem(wsets[u].pitem)); - prlook(wsets[u].ws); - fmt.Fprintf(foutput, "\n"); + wsets[u].flag = 0 + fmt.Fprintf(foutput, "\t%v", writem(wsets[u].pitem)) + prlook(wsets[u].ws) + fmt.Fprintf(foutput, "\n") } } } @@ -1899,32 +1899,32 @@ func closure(i int) { // sorts last state,and sees if it equals earlier ones. returns state number // func state(c int) int { - zzstate++; - p1 := pstate[nstate]; - p2 := pstate[nstate+1]; + zzstate++ + p1 := pstate[nstate] + p2 := pstate[nstate+1] if p1 == p2 { - return 0 // null state + return 0 // null state } // sort the items - var k, l int; - for k = p1 + 1; k < p2; k++ { // make k the biggest + var k, l int + for k = p1 + 1; k < p2; k++ { // make k the biggest for l = k; l > p1; l-- { if statemem[l].pitem.prodno < statemem[l-1].pitem.prodno || statemem[l].pitem.prodno == statemem[l-1].pitem.prodno && statemem[l].pitem.off < statemem[l-1].pitem.off { - s := statemem[l]; - statemem[l] = statemem[l-1]; - statemem[l-1] = s; + s := statemem[l] + statemem[l] = statemem[l-1] + statemem[l-1] = s } else { break } } } - size1 := p2 - p1; // size of state + size1 := p2 - p1 // size of state - var i int; + var i int if c >= NTBASE { i = ntstates[c-NTBASE] } else { @@ -1934,116 +1934,116 @@ func state(c int) int { look: for ; i != 0; i = mstates[i] { // get ith state - q1 := pstate[i]; - q2 := pstate[i+1]; - size2 := q2 - q1; + q1 := pstate[i] + q2 := pstate[i+1] + size2 := q2 - q1 if size1 != size2 { continue } - k = p1; + k = p1 for l = q1; l < q2; l++ { if aryeq(statemem[l].pitem.prod, statemem[k].pitem.prod) == 0 || statemem[l].pitem.off != statemem[k].pitem.off { continue look } - k++; + k++ } // found it - pstate[nstate+1] = pstate[nstate]; // delete last state + pstate[nstate+1] = pstate[nstate] // delete last state // fix up lookaheads if nolook != 0 { return i } - k = p1; + k = p1 for l = q1; l < q2; l++ { if setunion(statemem[l].look, statemem[k].look) != 0 { tystate[i] = MUSTDO } - k++; + k++ } - return i; + return i } // state is new - zznewstate++; + zznewstate++ if nolook != 0 { error("yacc state/nolook error") } - pstate[nstate+2] = p2; + pstate[nstate+2] = p2 if nstate+1 >= NSTATES { error("too many states") } if c >= NTBASE { - mstates[nstate] = ntstates[c-NTBASE]; - ntstates[c-NTBASE] = nstate; + mstates[nstate] = ntstates[c-NTBASE] + ntstates[c-NTBASE] = nstate } else { - mstates[nstate] = tstates[c]; - tstates[c] = nstate; + mstates[nstate] = tstates[c] + tstates[c] = nstate } - tystate[nstate] = MUSTDO; - nstate++; - return nstate - 1; + tystate[nstate] = MUSTDO + nstate++ + return nstate - 1 } func putitem(p Pitem, set Lkset) { - p.off++; - p.first = p.prod[p.off]; + p.off++ + p.first = p.prod[p.off] if pidebug != 0 && foutput != nil { fmt.Fprintf(foutput, "putitem(%v), state %v\n", writem(p), nstate) } - j := pstate[nstate+1]; + j := pstate[nstate+1] if j >= len(statemem) { - asm := make([]Item, j+STATEINC); - copy(asm, statemem); - statemem = asm; + asm := make([]Item, j+STATEINC) + copy(asm, statemem) + statemem = asm } - statemem[j].pitem = p; + statemem[j].pitem = p if nolook == 0 { - s := mkset(); - copy(s, set); - statemem[j].look = s; + s := mkset() + copy(s, set) + statemem[j].look = s } - j++; - pstate[nstate+1] = j; + j++ + pstate[nstate+1] = j } // // creates output string for item pointed to by pp // func writem(pp Pitem) string { - var i int; + var i int - p := pp.prod; - q := chcopy(nontrst[prdptr[pp.prodno][0]-NTBASE].name) + ": "; - npi := pp.off; + p := pp.prod + q := chcopy(nontrst[prdptr[pp.prodno][0]-NTBASE].name) + ": " + npi := pp.off - pi := aryeq(p, prdptr[pp.prodno]); + pi := aryeq(p, prdptr[pp.prodno]) for { - c := ' '; + c := ' ' if pi == npi { c = '.' } - q += string(c); + q += string(c) - i = p[pi]; - pi++; + i = p[pi] + pi++ if i <= 0 { break } - q += chcopy(symnam(i)); + q += chcopy(symnam(i)) } // an item calling for a reduction - i = p[npi]; + i = p[npi] if i < 0 { q += fmt.Sprintf(" (%v)", -i) } - return q; + return q } // @@ -2055,8 +2055,8 @@ func apack(p []int, n int) int { // we will only look at entries known to be there... // eliminate leading and trailing 0's // - off := 0; - pp := 0; + off := 0 + pp := 0 for ; pp <= n && p[pp] == 0; pp++ { off-- } @@ -2067,84 +2067,84 @@ func apack(p []int, n int) int { } for ; n > pp && p[n] == 0; n-- { } - p = p[pp : n+1]; + p = p[pp : n+1] // now, find a place for the elements from p to q, inclusive - r := len(amem) - len(p); + r := len(amem) - len(p) nextk: for rr := 0; rr <= r; rr++ { - qq := rr; + qq := rr for pp = 0; pp < len(p); pp++ { if p[pp] != 0 { if p[pp] != amem[qq] && amem[qq] != 0 { continue nextk } } - qq++; + qq++ } // we have found an acceptable k if pkdebug != 0 && foutput != nil { fmt.Fprintf(foutput, "off = %v, k = %v\n", off+rr, rr) } - qq = rr; + qq = rr for pp = 0; pp < len(p); pp++ { if p[pp] != 0 { if qq > memp { memp = qq } - amem[qq] = p[pp]; + amem[qq] = p[pp] } - qq++; + qq++ } if pkdebug != 0 && foutput != nil { for pp = 0; pp <= memp; pp += 10 { - fmt.Fprintf(foutput, "\n"); + fmt.Fprintf(foutput, "\n") for qq = pp; qq <= pp+9; qq++ { fmt.Fprintf(foutput, "%v ", amem[qq]) } - fmt.Fprintf(foutput, "\n"); + fmt.Fprintf(foutput, "\n") } } - return off + rr; + return off + rr } - error("no space in action table"); - return 0; + error("no space in action table") + return 0 } // // print the output for the states // func output() { - var c, u, v int; + var c, u, v int - fmt.Fprintf(ftable, "var\tYYEXCA = []int {\n"); + fmt.Fprintf(ftable, "var\tYYEXCA = []int {\n") - noset := mkset(); + noset := mkset() // output the stuff for state i for i := 0; i < nstate; i++ { - nolook = 0; + nolook = 0 if tystate[i] != MUSTLOOKAHEAD { nolook = 1 } - closure(i); + closure(i) // output actions - nolook = 1; - aryfil(temp1, ntokens+nnonter+1, 0); + nolook = 1 + aryfil(temp1, ntokens+nnonter+1, 0) for u = 0; u < cwp; u++ { - c = wsets[u].pitem.first; + c = wsets[u].pitem.first if c > 1 && c < NTBASE && temp1[c] == 0 { for v = u; v < cwp; v++ { if c == wsets[v].pitem.first { putitem(wsets[v].pitem, noset) } } - temp1[c] = state(c); + temp1[c] = state(c) } else if c > NTBASE { - c -= NTBASE; + c -= NTBASE if temp1[c+ntokens] == 0 { temp1[c+ntokens] = amem[indgo[i]+c] } @@ -2155,23 +2155,23 @@ func output() { } // now, we have the shifts; look at the reductions - lastred = 0; + lastred = 0 for u = 0; u < cwp; u++ { - c = wsets[u].pitem.first; + c = wsets[u].pitem.first // reduction if c > 0 { continue } - lastred = -c; - us := wsets[u].ws; + lastred = -c + us := wsets[u].ws for k := 0; k <= ntokens; k++ { if bitset(us, k) == 0 { continue } if temp1[k] == 0 { temp1[k] = c - } else if temp1[k] < 0 { // reduce/reduce conflict + } else if temp1[k] < 0 { // reduce/reduce conflict if foutput != nil { fmt.Fprintf(foutput, "\n %v: reduce/reduce conflict (red'ns "+ @@ -2181,21 +2181,21 @@ func output() { if -temp1[k] > lastred { temp1[k] = -lastred } - zzrrconf++; + zzrrconf++ } else { // potential shift/reduce conflict precftn(lastred, k, i) } } } - wract(i); + wract(i) } - fmt.Fprintf(ftable, "}\n"); - fmt.Fprintf(ftable, "const\tYYNPROD\t= %v\n", nprod); - fmt.Fprintf(ftable, "const\tYYPRIVATE\t= %v\n", PRIVATE); - fmt.Fprintf(ftable, "var\tYYTOKENNAMES []string\n"); - fmt.Fprintf(ftable, "var\tYYSTATES []string\n"); + fmt.Fprintf(ftable, "}\n") + fmt.Fprintf(ftable, "const\tYYNPROD\t= %v\n", nprod) + fmt.Fprintf(ftable, "const\tYYPRIVATE\t= %v\n", PRIVATE) + fmt.Fprintf(ftable, "var\tYYTOKENNAMES []string\n") + fmt.Fprintf(ftable, "var\tYYSTATES []string\n") } // @@ -2205,10 +2205,10 @@ func output() { // temp1[t] is changed to reflect the action // func precftn(r, t, s int) { - var action int; + var action int - lp := levprd[r]; - lt := toklev[t]; + lp := levprd[r] + lt := toklev[t] if PLEVEL(lt) == 0 || PLEVEL(lp) == 0 { // conflict if foutput != nil { @@ -2216,20 +2216,20 @@ func precftn(r, t, s int) { "\n%v: shift/reduce conflict (shift %v(%v), red'n %v(%v)) on %v", s, temp1[t], PLEVEL(lt), r, PLEVEL(lp), symnam(t)) } - zzsrconf++; - return; + zzsrconf++ + return } if PLEVEL(lt) == PLEVEL(lp) { action = ASSOC(lt) } else if PLEVEL(lt) > PLEVEL(lp) { - action = RASC // shift + action = RASC // shift } else { action = LASC - } // reduce + } // reduce switch action { - case BASC: // error action + case BASC: // error action temp1[t] = ERRCODE - case LASC: // reduce + case LASC: // reduce temp1[t] = -r } } @@ -2239,11 +2239,11 @@ func precftn(r, t, s int) { // temp1 has the actions, lastred the default // func wract(i int) { - var p, p1 int; + var p, p1 int // find the best choice for lastred - lastred = 0; - ntimes := 0; + lastred = 0 + ntimes := 0 for j := 0; j <= ntokens; j++ { if temp1[j] >= 0 { continue @@ -2252,17 +2252,17 @@ func wract(i int) { continue } // count the number of appearances of temp1[j] - count := 0; - tred := -temp1[j]; - levprd[tred] |= REDFLAG; + count := 0 + tred := -temp1[j] + levprd[tred] |= REDFLAG for p = 0; p <= ntokens; p++ { if temp1[p]+tred == 0 { count++ } } if count > ntimes { - lastred = tred; - ntimes = count; + lastred = tred + ntimes = count } } @@ -2276,25 +2276,25 @@ func wract(i int) { // clear out entries in temp1 which equal lastred // count entries in optst table - n := 0; + n := 0 for p = 0; p <= ntokens; p++ { - p1 = temp1[p]; + p1 = temp1[p] if p1+lastred == 0 { - temp1[p] = 0; - p1 = 0; + temp1[p] = 0 + p1 = 0 } if p1 > 0 && p1 != ACCEPTCODE && p1 != ERRCODE { n++ } } - wrstate(i); - defact[i] = lastred; - flag := 0; - os := make([]int, n*2); - n = 0; + wrstate(i) + defact[i] = lastred + flag := 0 + os := make([]int, n*2) + n = 0 for p = 0; p <= ntokens; p++ { - p1 = temp1[p]; + p1 = temp1[p] if p1 != 0 { if p1 < 0 { p1 = -p1 @@ -2303,40 +2303,40 @@ func wract(i int) { } else if p1 == ERRCODE { p1 = 0 } else { - os[n] = p; - n++; - os[n] = p1; - n++; - zzacent++; - continue; + os[n] = p + n++ + os[n] = p1 + n++ + zzacent++ + continue } if flag == 0 { fmt.Fprintf(ftable, "-1, %v,\n", i) } - flag++; - fmt.Fprintf(ftable, "\t%v, %v,\n", p, p1); - zzexcp++; + flag++ + fmt.Fprintf(ftable, "\t%v, %v,\n", p, p1) + zzexcp++ } } if flag != 0 { - defact[i] = -2; - fmt.Fprintf(ftable, "\t-2, %v,\n", lastred); + defact[i] = -2 + fmt.Fprintf(ftable, "\t-2, %v,\n", lastred) } - optst[i] = os; + optst[i] = os } // // writes state i // func wrstate(i int) { - var j0, j1, u int; - var pp, qq int; + var j0, j1, u int + var pp, qq int if foutput == nil { return } - fmt.Fprintf(foutput, "\nstate %v\n", i); - qq = pstate[i+1]; + fmt.Fprintf(foutput, "\nstate %v\n", i) + qq = pstate[i+1] for pp = pstate[i]; pp < qq; pp++ { fmt.Fprintf(foutput, "\t%v\n", writem(statemem[pp].pitem)) } @@ -2351,9 +2351,9 @@ func wrstate(i int) { // check for state equal to another for j0 = 0; j0 <= ntokens; j0++ { - j1 = temp1[j0]; + j1 = temp1[j0] if j1 != 0 { - fmt.Fprintf(foutput, "\n\t%v ", symnam(j0)); + fmt.Fprintf(foutput, "\n\t%v ", symnam(j0)) // shift, error, or accept if j1 > 0 { @@ -2379,9 +2379,9 @@ func wrstate(i int) { } // now, output nonterminal actions - j1 = ntokens; + j1 = ntokens for j0 = 1; j0 <= nnonter; j0++ { - j1++; + j1++ if temp1[j1] != 0 { fmt.Fprintf(foutput, "\t%v goto %v\n", symnam(j0+NTBASE), temp1[j1]) } @@ -2393,11 +2393,11 @@ func wrstate(i int) { // func go2out() { for i := 1; i <= nnonter; i++ { - go2gen(i); + go2gen(i) // find the best one to make default - best := -1; - times := 0; + best := -1 + times := 0 // is j the most frequent for j := 0; j < nstate; j++ { @@ -2409,36 +2409,36 @@ func go2out() { } // is tystate[j] the most frequent - count := 0; - cbest := tystate[j]; + count := 0 + cbest := tystate[j] for k := j; k < nstate; k++ { if tystate[k] == cbest { count++ } } if count > times { - best = cbest; - times = count; + best = cbest + times = count } } // best is now the default entry - zzgobest += times - 1; - n := 0; + zzgobest += times - 1 + n := 0 for j := 0; j < nstate; j++ { if tystate[j] != 0 && tystate[j] != best { n++ } } - goent := make([]int, 2*n+1); - n = 0; + goent := make([]int, 2*n+1) + n = 0 for j := 0; j < nstate; j++ { if tystate[j] != 0 && tystate[j] != best { - goent[n] = j; - n++; - goent[n] = tystate[j]; - n++; - zzgoent++; + goent[n] = j + n++ + goent[n] = tystate[j] + n++ + zzgoent++ } } @@ -2447,9 +2447,9 @@ func go2out() { best = 0 } - zzgoent++; - goent[n] = best; - yypgo[i] = goent; + zzgoent++ + goent[n] = best + yypgo[i] = goent } } @@ -2457,23 +2457,23 @@ func go2out() { // output the gotos for nonterminal c // func go2gen(c int) { - var i, cc, p, q int; + var i, cc, p, q int // first, find nonterminals with gotos on c - aryfil(temp1, nnonter+1, 0); - temp1[c] = 1; - work := 1; + aryfil(temp1, nnonter+1, 0) + temp1[c] = 1 + work := 1 for work != 0 { - work = 0; + work = 0 for i = 0; i < nprod; i++ { // cc is a nonterminal with a goto on c - cc = prdptr[i][1] - NTBASE; + cc = prdptr[i][1] - NTBASE if cc >= 0 && temp1[cc] != 0 { // thus, the left side of production i does too - cc = prdptr[i][0] - NTBASE; + cc = prdptr[i][0] - NTBASE if temp1[cc] == 0 { - work = 1; - temp1[cc] = 1; + work = 1 + temp1[cc] = 1 } } } @@ -2481,26 +2481,26 @@ func go2gen(c int) { // now, we have temp1[c] = 1 if a goto on c in closure of cc if g2debug != 0 && foutput != nil { - fmt.Fprintf(foutput, "%v: gotos on ", nontrst[c].name); + fmt.Fprintf(foutput, "%v: gotos on ", nontrst[c].name) for i = 0; i <= nnonter; i++ { if temp1[i] != 0 { fmt.Fprintf(foutput, "%v ", nontrst[i].name) } } - fmt.Fprintf(foutput, "\n"); + fmt.Fprintf(foutput, "\n") } // now, go through and put gotos into tystate - aryfil(tystate, nstate, 0); + aryfil(tystate, nstate, 0) for i = 0; i < nstate; i++ { - q = pstate[i+1]; + q = pstate[i+1] for p = pstate[i]; p < q; p++ { - cc = statemem[p].pitem.first; + cc = statemem[p].pitem.first if cc >= NTBASE { // goto on c is possible if temp1[cc-NTBASE] != 0 { - tystate[i] = amem[indgo[i]+c]; - break; + tystate[i] = amem[indgo[i]+c] + break } } } @@ -2514,18 +2514,18 @@ func go2gen(c int) { // derived by productions in levprd. // func hideprod() { - nred := 0; - levprd[0] = 0; + nred := 0 + levprd[0] = 0 for i := 1; i < nprod; i++ { if (levprd[i] & REDFLAG) == 0 { if foutput != nil { fmt.Fprintf(foutput, "Rule not reduced: %v\n", writem(Pitem{prdptr[i], 0, 0, i})) } - fmt.Printf("rule %v never reduced\n", writem(Pitem{prdptr[i], 0, 0, i})); - nred++; + fmt.Printf("rule %v never reduced\n", writem(Pitem{prdptr[i], 0, 0, i})) + nred++ } - levprd[i] = prdptr[i][0] - NTBASE; + levprd[i] = prdptr[i][0] - NTBASE } if nred != 0 { fmt.Printf("%v rules never reduced\n", nred) @@ -2533,18 +2533,18 @@ func hideprod() { } func callopt() { - var j, k, p, q, i int; - var v []int; + var j, k, p, q, i int + var v []int - pgo = make([]int, nnonter+1); - pgo[0] = 0; - maxoff = 0; - maxspr = 0; + pgo = make([]int, nnonter+1) + pgo[0] = 0 + maxoff = 0 + maxspr = 0 for i = 0; i < nstate; i++ { - k = 32000; - j = 0; - v = optst[i]; - q = len(v); + k = 32000 + j = 0 + v = optst[i] + q = len(v) for p = 0; p < q; p += 2 { if v[p] > j { j = v[p] @@ -2562,28 +2562,28 @@ func callopt() { maxoff = k } } - tystate[i] = q + 2*j; + tystate[i] = q + 2*j if j > maxspr { maxspr = j } } // initialize ggreed table - ggreed = make([]int, nnonter+1); + ggreed = make([]int, nnonter+1) for i = 1; i <= nnonter; i++ { - ggreed[i] = 1; - j = 0; + ggreed[i] = 1 + j = 0 // minimum entry index is always 0 - v = yypgo[i]; - q = len(v) - 1; + v = yypgo[i] + q = len(v) - 1 for p = 0; p < q; p += 2 { - ggreed[i] += 2; + ggreed[i] += 2 if v[p] > j { j = v[p] } } - ggreed[i] = ggreed[i] + 2*j; + ggreed[i] = ggreed[i] + 2*j if j > maxoff { maxoff = j } @@ -2593,71 +2593,71 @@ func callopt() { for i = 0; i < ACTSIZE; i++ { amem[i] = 0 } - maxa = 0; + maxa = 0 for i = 0; i < nstate; i++ { if tystate[i] == 0 && adb > 1 { fmt.Fprintf(ftable, "State %v: null\n", i) } - indgo[i] = YYFLAG; + indgo[i] = YYFLAG } - i = nxti(); + i = nxti() for i != NOMORE { if i >= 0 { stin(i) } else { gin(-i) } - i = nxti(); + i = nxti() } // print amem array if adb > 2 { for p = 0; p <= maxa; p += 10 { - fmt.Fprintf(ftable, "%v ", p); + fmt.Fprintf(ftable, "%v ", p) for i = 0; i < 10; i++ { fmt.Fprintf(ftable, "%v ", amem[p+i]) } - putrune(ftable, '\n'); + putrune(ftable, '\n') } } - aoutput(); - osummary(); + aoutput() + osummary() } // // finds the next i // func nxti() int { - max := 0; - maxi := 0; + max := 0 + maxi := 0 for i := 1; i <= nnonter; i++ { if ggreed[i] >= max { - max = ggreed[i]; - maxi = -i; + max = ggreed[i] + maxi = -i } } for i := 0; i < nstate; i++ { if tystate[i] >= max { - max = tystate[i]; - maxi = i; + max = tystate[i] + maxi = i } } if max == 0 { return NOMORE } - return maxi; + return maxi } func gin(i int) { - var s int; + var s int // enter gotos on nonterminal i into array amem - ggreed[i] = 0; + ggreed[i] = 0 - q := yypgo[i]; - nq := len(q) - 1; + q := yypgo[i] + nq := len(q) - 1 // now, find amem place for it nextgp: @@ -2666,9 +2666,9 @@ nextgp: continue } for r := 0; r < nq; r += 2 { - s = p + q[r] + 1; + s = p + q[r] + 1 if s > maxa { - maxa = s; + maxa = s if maxa >= ACTSIZE { error("a array overflow") } @@ -2679,38 +2679,38 @@ nextgp: } // we have found amem spot - amem[p] = q[nq]; + amem[p] = q[nq] if p > maxa { maxa = p } for r := 0; r < nq; r += 2 { - s = p + q[r] + 1; - amem[s] = q[r+1]; + s = p + q[r] + 1 + amem[s] = q[r+1] } - pgo[i] = p; + pgo[i] = p if adb > 1 { fmt.Fprintf(ftable, "Nonterminal %v, entry at %v\n", i, pgo[i]) } - return; + return } - error("cannot place goto %v\n", i); + error("cannot place goto %v\n", i) } func stin(i int) { - var s int; + var s int - tystate[i] = 0; + tystate[i] = 0 // enter state i into the amem array - q := optst[i]; - nq := len(q); + q := optst[i] + nq := len(q) nextn: // find an acceptable place for n := -maxoff; n < ACTSIZE; n++ { - flag := 0; + flag := 0 for r := 0; r < nq; r += 2 { - s = q[r] + n; + s = q[r] + n if s < 0 || s > ACTSIZE { continue nextn } @@ -2732,37 +2732,37 @@ nextn: if nq == len(optst[j]) { // states are equal - indgo[i] = n; + indgo[i] = n if adb > 1 { fmt.Fprintf(ftable, "State %v: entry at"+ "%v equals state %v\n", i, n, j) } - return; + return } // we have some disagreement - continue nextn; + continue nextn } } for r := 0; r < nq; r += 2 { - s = q[r] + n; + s = q[r] + n if s > maxa { maxa = s } if amem[s] != 0 && amem[s] != q[r+1] { error("clobber of a array, pos'n %v, by %v", s, q[r+1]) } - amem[s] = q[r+1]; + amem[s] = q[r+1] } - indgo[i] = n; + indgo[i] = n if adb > 1 { fmt.Fprintf(ftable, "State %v: entry at %v\n", i, indgo[i]) } - return; + return } - error("Error; failure to place state %v", i); + error("Error; failure to place state %v", i) } // @@ -2770,20 +2770,20 @@ nextn: // write out the optimized parser // func aoutput() { - fmt.Fprintf(ftable, "const\tYYLAST\t= %v\n", maxa+1); - arout("YYACT", amem, maxa+1); - arout("YYPACT", indgo, nstate); - arout("YYPGO", pgo, nnonter+1); + fmt.Fprintf(ftable, "const\tYYLAST\t= %v\n", maxa+1) + arout("YYACT", amem, maxa+1) + arout("YYPACT", indgo, nstate) + arout("YYPGO", pgo, nnonter+1) } // // put out other arrays, copy the parsers // func others() { - var i, j int; + var i, j int - arout("YYR1", levprd, nprod); - aryfil(temp1, nprod, 0); + arout("YYR1", levprd, nprod) + aryfil(temp1, nprod, 0) // //yyr2 is the number of rules for each production @@ -2791,9 +2791,9 @@ func others() { for i = 1; i < nprod; i++ { temp1[i] = len(prdptr[i]) - 2 } - arout("YYR2", temp1, nprod); + arout("YYR2", temp1, nprod) - aryfil(temp1, nstate, -1000); + aryfil(temp1, nstate, -1000) for i = 0; i <= ntokens; i++ { for j := tstates[i]; j != 0; j = mstates[j] { temp1[j] = i @@ -2804,22 +2804,22 @@ func others() { temp1[j] = -i } } - arout("YYCHK", temp1, nstate); - arout("YYDEF", defact, nstate); + arout("YYCHK", temp1, nstate) + arout("YYDEF", defact, nstate) // put out token translation tables // table 1 has 0-256 - aryfil(temp1, 256, 0); - c := 0; + aryfil(temp1, 256, 0) + c := 0 for i = 1; i <= ntokens; i++ { - j = tokset[i].value; + j = tokset[i].value if j >= 0 && j < 256 { if temp1[j] != 0 { - print("yacc bug -- cant have 2 different Ts with same value\n"); - print(" %s and %s\n", tokset[i].name, tokset[temp1[j]].name); - nerrors++; + print("yacc bug -- cant have 2 different Ts with same value\n") + print(" %s and %s\n", tokset[i].name, tokset[temp1[j]].name) + nerrors++ } - temp1[j] = i; + temp1[j] = i if j > c { c = j } @@ -2830,32 +2830,32 @@ func others() { temp1[i] = YYLEXUNK } } - arout("YYTOK1", temp1, c+1); + arout("YYTOK1", temp1, c+1) // table 2 has PRIVATE-PRIVATE+256 - aryfil(temp1, 256, 0); - c = 0; + aryfil(temp1, 256, 0) + c = 0 for i = 1; i <= ntokens; i++ { - j = tokset[i].value - PRIVATE; + j = tokset[i].value - PRIVATE if j >= 0 && j < 256 { if temp1[j] != 0 { - print("yacc bug -- cant have 2 different Ts with same value\n"); - print(" %s and %s\n", tokset[i].name, tokset[temp1[j]].name); - nerrors++; + print("yacc bug -- cant have 2 different Ts with same value\n") + print(" %s and %s\n", tokset[i].name, tokset[temp1[j]].name) + nerrors++ } - temp1[j] = i; + temp1[j] = i if j > c { c = j } } } - arout("YYTOK2", temp1, c+1); + arout("YYTOK2", temp1, c+1) // table 3 has everything else - fmt.Fprintf(ftable, "var\tYYTOK3\t= []int {\n"); - c = 0; + fmt.Fprintf(ftable, "var\tYYTOK3\t= []int {\n") + c = 0 for i = 1; i <= ntokens; i++ { - j = tokset[i].value; + j = tokset[i].value if j >= 0 && j < 256 { continue } @@ -2863,35 +2863,35 @@ func others() { continue } - fmt.Fprintf(ftable, "%4d,%4d,", j, i); - c++; + fmt.Fprintf(ftable, "%4d,%4d,", j, i) + c++ if c%5 == 0 { putrune(ftable, '\n') } } - fmt.Fprintf(ftable, "%4d,\n };\n", 0); + fmt.Fprintf(ftable, "%4d,\n };\n", 0) // copy parser text - c = getrune(finput); + c = getrune(finput) for c != EOF { - putrune(ftable, c); - c = getrune(finput); + putrune(ftable, c) + c = getrune(finput) } // copy yaccpar - fmt.Fprintf(ftable, "%v", yaccpar); + fmt.Fprintf(ftable, "%v", yaccpar) } func arout(s string, v []int, n int) { - fmt.Fprintf(ftable, "var\t%v\t= []int {\n", s); + fmt.Fprintf(ftable, "var\t%v\t= []int {\n", s) for i := 0; i < n; i++ { if i%10 == 0 { putrune(ftable, '\n') } - fmt.Fprintf(ftable, "%4d", v[i]); - putrune(ftable, ','); + fmt.Fprintf(ftable, "%4d", v[i]) + putrune(ftable, ',') } - fmt.Fprintf(ftable, "\n};\n"); + fmt.Fprintf(ftable, "\n};\n") } // @@ -2899,18 +2899,18 @@ func arout(s string, v []int, n int) { // func summary() { if foutput != nil { - fmt.Fprintf(foutput, "\n%v terminals, %v nonterminals\n", ntokens, nnonter+1); - fmt.Fprintf(foutput, "%v grammar rules, %v/%v states\n", nprod, nstate, NSTATES); - fmt.Fprintf(foutput, "%v shift/reduce, %v reduce/reduce conflicts reported\n", zzsrconf, zzrrconf); - fmt.Fprintf(foutput, "%v working sets used\n", len(wsets)); - fmt.Fprintf(foutput, "memory: parser %v/%v\n", memp, ACTSIZE); - fmt.Fprintf(foutput, "%v extra closures\n", zzclose-2*nstate); - fmt.Fprintf(foutput, "%v shift entries, %v exceptions\n", zzacent, zzexcp); - fmt.Fprintf(foutput, "%v goto entries\n", zzgoent); - fmt.Fprintf(foutput, "%v entries saved by goto default\n", zzgobest); + fmt.Fprintf(foutput, "\n%v terminals, %v nonterminals\n", ntokens, nnonter+1) + fmt.Fprintf(foutput, "%v grammar rules, %v/%v states\n", nprod, nstate, NSTATES) + fmt.Fprintf(foutput, "%v shift/reduce, %v reduce/reduce conflicts reported\n", zzsrconf, zzrrconf) + fmt.Fprintf(foutput, "%v working sets used\n", len(wsets)) + fmt.Fprintf(foutput, "memory: parser %v/%v\n", memp, ACTSIZE) + fmt.Fprintf(foutput, "%v extra closures\n", zzclose-2*nstate) + fmt.Fprintf(foutput, "%v shift entries, %v exceptions\n", zzacent, zzexcp) + fmt.Fprintf(foutput, "%v goto entries\n", zzgoent) + fmt.Fprintf(foutput, "%v entries saved by goto default\n", zzgobest) } if zzsrconf != 0 || zzrrconf != 0 { - fmt.Printf("\nconflicts: "); + fmt.Printf("\nconflicts: ") if zzsrconf != 0 { fmt.Printf("%v shift/reduce", zzsrconf) } @@ -2920,7 +2920,7 @@ func summary() { if zzrrconf != 0 { fmt.Printf("%v reduce/reduce", zzrrconf) } - fmt.Printf("\n"); + fmt.Printf("\n") } } @@ -2931,74 +2931,74 @@ func osummary() { if foutput == nil { return } - i := 0; + i := 0 for p := maxa; p >= 0; p-- { if amem[p] == 0 { i++ } } - fmt.Fprintf(foutput, "Optimizer space used: output %v/%v\n", maxa+1, ACTSIZE); - fmt.Fprintf(foutput, "%v table entries, %v zero\n", maxa+1, i); - fmt.Fprintf(foutput, "maximum spread: %v, maximum offset: %v\n", maxspr, maxoff); + fmt.Fprintf(foutput, "Optimizer space used: output %v/%v\n", maxa+1, ACTSIZE) + fmt.Fprintf(foutput, "%v table entries, %v zero\n", maxa+1, i) + fmt.Fprintf(foutput, "maximum spread: %v, maximum offset: %v\n", maxspr, maxoff) } // // copies and protects "'s in q // func chcopy(q string) string { - s := ""; - i := 0; - j := 0; + s := "" + i := 0 + j := 0 for i = 0; i < len(q); i++ { if q[i] == '"' { - s += q[j:i] + "\\"; - j = i; + s += q[j:i] + "\\" + j = i } } - return s + q[j:i]; + return s + q[j:i] } func usage() { - fmt.Fprintf(stderr, "usage: gacc [-o output] [-v parsetable] input\n"); - exit(1); + fmt.Fprintf(stderr, "usage: gacc [-o output] [-v parsetable] input\n") + exit(1) } -func bitset(set Lkset, bit int) int { return set[bit>>5] & (1 << uint(bit&31)) } +func bitset(set Lkset, bit int) int { return set[bit>>5] & (1 << uint(bit&31)) } -func setbit(set Lkset, bit int) { set[bit>>5] |= (1 << uint(bit&31)) } +func setbit(set Lkset, bit int) { set[bit>>5] |= (1 << uint(bit&31)) } -func mkset() Lkset { return make([]int, tbitset) } +func mkset() Lkset { return make([]int, tbitset) } // // set a to the union of a and b // return 1 if b is not a subset of a, 0 otherwise // func setunion(a, b []int) int { - sub := 0; + sub := 0 for i := 0; i < tbitset; i++ { - x := a[i]; - y := x | b[i]; - a[i] = y; + x := a[i] + y := x | b[i] + a[i] = y if y != x { sub = 1 } } - return sub; + return sub } func prlook(p Lkset) { if p == nil { - fmt.Fprintf(foutput, "\tNULL"); - return; + fmt.Fprintf(foutput, "\tNULL") + return } - fmt.Fprintf(foutput, " { "); + fmt.Fprintf(foutput, " { ") for j := 0; j <= ntokens; j++ { if bitset(p, j) != 0 { fmt.Fprintf(foutput, "%v ", symnam(j)) } } - fmt.Fprintf(foutput, "}"); + fmt.Fprintf(foutput, "}") } // @@ -3006,20 +3006,20 @@ func prlook(p Lkset) { // var peekrune int -func isdigit(c int) bool { return c >= '0' && c <= '9' } +func isdigit(c int) bool { return c >= '0' && c <= '9' } func isword(c int) bool { return c >= 0xa0 || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') } -func mktemp(t string) string { return t } +func mktemp(t string) string { return t } // // return 1 if 2 arrays are equal // return 0 if not equal // func aryeq(a []int, b []int) int { - n := len(a); + n := len(a) if len(b) != n { return 0 } @@ -3028,29 +3028,29 @@ func aryeq(a []int, b []int) int { return 0 } } - return 1; + return 1 } func putrune(f *bufio.Writer, c int) { - s := string(c); + s := string(c) for i := 0; i < len(s); i++ { f.WriteByte(s[i]) } } func getrune(f *bufio.Reader) int { - var r int; + var r int if peekrune != 0 { if peekrune == EOF { return EOF } - r = peekrune; - peekrune = 0; - return r; + r = peekrune + peekrune = 0 + return r } - c, n, err := f.ReadRune(); + c, n, err := f.ReadRune() if n == 0 { return EOF } @@ -3058,7 +3058,7 @@ func getrune(f *bufio.Reader) int { error("read error: %v", err) } //fmt.Printf("rune = %v n=%v\n", string(c), n); - return c; + return c } func ungetrune(f *bufio.Reader, c int) { @@ -3068,59 +3068,59 @@ func ungetrune(f *bufio.Reader, c int) { if peekrune != 0 { panic("ungetc - 2nd unget") } - peekrune = c; + peekrune = c } func write(f *bufio.Writer, b []byte, n int) int { - println("write"); - return 0; + println("write") + return 0 } func open(s string) *bufio.Reader { - fi, err := os.Open(s, os.O_RDONLY, 0); + fi, err := os.Open(s, os.O_RDONLY, 0) if err != nil { error("error opening %v: %v", s, err) } //fmt.Printf("open %v\n", s); - return bufio.NewReader(fi); + return bufio.NewReader(fi) } func create(s string, m int) *bufio.Writer { - fo, err := os.Open(s, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, m); + fo, err := os.Open(s, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, m) if err != nil { error("error opening %v: %v", s, err) } //fmt.Printf("create %v mode %v\n", s, m); - return bufio.NewWriter(fo); + return bufio.NewWriter(fo) } // // write out error comment // func error(s string, v ...) { - nerrors++; - fmt.Fprintf(stderr, s, v); - fmt.Fprintf(stderr, ": %v:%v\n", infile, lineno); + nerrors++ + fmt.Fprintf(stderr, s, v) + fmt.Fprintf(stderr, ": %v:%v\n", infile, lineno) if fatfl != 0 { - summary(); - exit(1); + summary() + exit(1) } } func exit(status int) { if ftable != nil { - ftable.Flush(); - ftable = nil; + ftable.Flush() + ftable = nil } if foutput != nil { - foutput.Flush(); - foutput = nil; + foutput.Flush() + foutput = nil } if stderr != nil { - stderr.Flush(); - stderr = nil; + stderr.Flush() + stderr = nil } - os.Exit(status); + os.Exit(status) } var yaccpar = ` diff --git a/src/cmd/hgpatch/main.go b/src/cmd/hgpatch/main.go index 3d2b0817e..282122daa 100644 --- a/src/cmd/hgpatch/main.go +++ b/src/cmd/hgpatch/main.go @@ -5,35 +5,35 @@ package main import ( - "bytes"; - "container/vector"; - "exec"; - "flag"; - "fmt"; - "io"; - "io/ioutil"; - "os"; - "patch"; - "path"; - "sort"; - "strings"; + "bytes" + "container/vector" + "exec" + "flag" + "fmt" + "io" + "io/ioutil" + "os" + "patch" + "path" + "sort" + "strings" ) var checkSync = flag.Bool("checksync", true, "check whether repository is out of sync") func usage() { - fmt.Fprintf(os.Stderr, "usage: hgpatch [options] [patchfile]\n"); - flag.PrintDefaults(); - os.Exit(2); + fmt.Fprintf(os.Stderr, "usage: hgpatch [options] [patchfile]\n") + flag.PrintDefaults() + os.Exit(2) } func main() { - flag.Usage = usage; - flag.Parse(); + flag.Usage = usage + flag.Parse() - args := flag.Args(); - var data []byte; - var err os.Error; + args := flag.Args() + var data []byte + var err os.Error switch len(args) { case 0: data, err = ioutil.ReadAll(os.Stdin) @@ -42,31 +42,31 @@ func main() { default: usage() } - chk(err); + chk(err) - pset, err := patch.Parse(data); - chk(err); + pset, err := patch.Parse(data) + chk(err) // Change to hg root directory, because // patch paths are relative to root. - root, err := hgRoot(); - chk(err); - chk(os.Chdir(root)); + root, err := hgRoot() + chk(err) + chk(os.Chdir(root)) // Make sure there are no pending changes on the server. if *checkSync && hgIncoming() { - fmt.Fprintf(os.Stderr, "incoming changes waiting; run hg sync first\n"); - os.Exit(2); + fmt.Fprintf(os.Stderr, "incoming changes waiting; run hg sync first\n") + os.Exit(2) } // Make sure we won't be editing files with local pending changes. - dirtylist, err := hgModified(); - chk(err); - dirty := make(map[string]int); + dirtylist, err := hgModified() + chk(err) + dirty := make(map[string]int) for _, f := range dirtylist { dirty[f] = 1 } - conflict := make(map[string]int); + conflict := make(map[string]int) for _, f := range pset.File { if f.Verb == patch.Delete || f.Verb == patch.Rename { if _, ok := dirty[f.Src]; ok { @@ -80,21 +80,21 @@ func main() { } } if len(conflict) > 0 { - fmt.Fprintf(os.Stderr, "cannot apply patch to locally modified files:\n"); + fmt.Fprintf(os.Stderr, "cannot apply patch to locally modified files:\n") for name := range conflict { fmt.Fprintf(os.Stderr, "\t%s\n", name) } - os.Exit(2); + os.Exit(2) } // Apply changes in memory. - op, err := pset.Apply(ioutil.ReadFile); - chk(err); + op, err := pset.Apply(ioutil.ReadFile) + chk(err) // Write changes to disk copy: order of commands matters. // Accumulate undo log as we go, in case there is an error. // Also accumulate list of modified files to print at end. - changed := make(map[string]int); + changed := make(map[string]int) // Copy, Rename create the destination file, so they // must happen before we write the data out. @@ -102,82 +102,82 @@ func main() { // with the same source, so we have to run all the // Copy in one pass, then all the Rename. for i := range op { - o := &op[i]; + o := &op[i] if o.Verb == patch.Copy { - makeParent(o.Dst); - chk(hgCopy(o.Dst, o.Src)); - undoRevert(o.Dst); - changed[o.Dst] = 1; + makeParent(o.Dst) + chk(hgCopy(o.Dst, o.Src)) + undoRevert(o.Dst) + changed[o.Dst] = 1 } } for i := range op { - o := &op[i]; + o := &op[i] if o.Verb == patch.Rename { - makeParent(o.Dst); - chk(hgRename(o.Dst, o.Src)); - undoRevert(o.Dst); - undoRevert(o.Src); - changed[o.Src] = 1; - changed[o.Dst] = 1; + makeParent(o.Dst) + chk(hgRename(o.Dst, o.Src)) + undoRevert(o.Dst) + undoRevert(o.Src) + changed[o.Src] = 1 + changed[o.Dst] = 1 } } // Run Delete before writing to files in case one of the // deleted paths is becoming a directory. for i := range op { - o := &op[i]; + o := &op[i] if o.Verb == patch.Delete { - chk(hgRemove(o.Src)); - undoRevert(o.Src); - changed[o.Src] = 1; + chk(hgRemove(o.Src)) + undoRevert(o.Src) + changed[o.Src] = 1 } } // Write files. for i := range op { - o := &op[i]; + o := &op[i] if o.Verb == patch.Delete { continue } if o.Verb == patch.Add { - makeParent(o.Dst); - changed[o.Dst] = 1; + makeParent(o.Dst) + changed[o.Dst] = 1 } if o.Data != nil { - chk(ioutil.WriteFile(o.Dst, o.Data, 0644)); + chk(ioutil.WriteFile(o.Dst, o.Data, 0644)) if o.Verb == patch.Add { undoRm(o.Dst) } else { undoRevert(o.Dst) } - changed[o.Dst] = 1; + changed[o.Dst] = 1 } if o.Mode != 0 { - chk(os.Chmod(o.Dst, o.Mode&0755)); - undoRevert(o.Dst); - changed[o.Dst] = 1; + chk(os.Chmod(o.Dst, o.Mode&0755)) + undoRevert(o.Dst) + changed[o.Dst] = 1 } } // hg add looks at the destination file, so it must happen // after we write the data out. for i := range op { - o := &op[i]; + o := &op[i] if o.Verb == patch.Add { - chk(hgAdd(o.Dst)); - undoRevert(o.Dst); - changed[o.Dst] = 1; + chk(hgAdd(o.Dst)) + undoRevert(o.Dst) + changed[o.Dst] = 1 } } // Finished editing files. Write the list of changed files to stdout. - list := make([]string, len(changed)); - i := 0; + list := make([]string, len(changed)) + i := 0 for f := range changed { - list[i] = f; - i++; + list[i] = f + i++ } - sort.SortStrings(list); + sort.SortStrings(list) for _, f := range list { fmt.Printf("%s\n", f) } @@ -186,58 +186,58 @@ func main() { // make parent directory for name, if necessary func makeParent(name string) { - parent, _ := path.Split(name); - chk(mkdirAll(parent, 0755)); + parent, _ := path.Split(name) + chk(mkdirAll(parent, 0755)) } // Copy of os.MkdirAll but adds to undo log after // creating a directory. func mkdirAll(path string, perm int) os.Error { - dir, err := os.Lstat(path); + dir, err := os.Lstat(path) if err == nil { if dir.IsDirectory() { return nil } - return &os.PathError{"mkdir", path, os.ENOTDIR}; + return &os.PathError{"mkdir", path, os.ENOTDIR} } - i := len(path); - for i > 0 && path[i-1] == '/' { // Skip trailing slashes. + i := len(path) + for i > 0 && path[i-1] == '/' { // Skip trailing slashes. i-- } - j := i; - for j > 0 && path[j-1] != '/' { // Scan backward over element. + j := i + for j > 0 && path[j-1] != '/' { // Scan backward over element. j-- } if j > 0 { - err = mkdirAll(path[0:j-1], perm); + err = mkdirAll(path[0:j-1], perm) if err != nil { return err } } - err = os.Mkdir(path, perm); + err = os.Mkdir(path, perm) if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. - dir, err1 := os.Lstat(path); + dir, err1 := os.Lstat(path) if err1 == nil && dir.IsDirectory() { return nil } - return err; + return err } - undoRm(path); - return nil; + undoRm(path) + return nil } // If err != nil, process the undo log and exit. func chk(err os.Error) { if err != nil { - fmt.Fprintf(os.Stderr, "%s\n", err); - runUndo(); - os.Exit(2); + fmt.Fprintf(os.Stderr, "%s\n", err) + runUndo() + os.Exit(2) } } @@ -245,11 +245,11 @@ func chk(err os.Error) { // Undo log type undo func() os.Error -var undoLog vector.Vector // vector of undo +var undoLog vector.Vector // vector of undo -func undoRevert(name string) { undoLog.Push(undo(func() os.Error { return hgRevert(name) })) } +func undoRevert(name string) { undoLog.Push(undo(func() os.Error { return hgRevert(name) })) } -func undoRm(name string) { undoLog.Push(undo(func() os.Error { return os.Remove(name) })) } +func undoRm(name string) { undoLog.Push(undo(func() os.Error { return os.Remove(name) })) } func runUndo() { for i := undoLog.Len() - 1; i >= 0; i-- { @@ -262,68 +262,68 @@ func runUndo() { // hgRoot returns the root directory of the repository. func hgRoot() (string, os.Error) { - out, err := run([]string{"hg", "root"}, nil); + out, err := run([]string{"hg", "root"}, nil) if err != nil { return "", err } - return strings.TrimSpace(out), nil; + return strings.TrimSpace(out), nil } // hgIncoming returns true if hg sync will pull in changes. func hgIncoming() bool { // hg -q incoming exits 0 when there is nothing incoming, 1 otherwise. - _, err := run([]string{"hg", "-q", "incoming"}, nil); - return err == nil; + _, err := run([]string{"hg", "-q", "incoming"}, nil) + return err == nil } // hgModified returns a list of the modified files in the // repository. func hgModified() ([]string, os.Error) { - out, err := run([]string{"hg", "status", "-n"}, nil); + out, err := run([]string{"hg", "status", "-n"}, nil) if err != nil { return nil, err } - return strings.Split(strings.TrimSpace(out), "\n", 0), nil; + return strings.Split(strings.TrimSpace(out), "\n", 0), nil } // hgAdd adds name to the repository. func hgAdd(name string) os.Error { - _, err := run([]string{"hg", "add", name}, nil); - return err; + _, err := run([]string{"hg", "add", name}, nil) + return err } // hgRemove removes name from the repository. func hgRemove(name string) os.Error { - _, err := run([]string{"hg", "rm", name}, nil); - return err; + _, err := run([]string{"hg", "rm", name}, nil) + return err } // hgRevert reverts name. func hgRevert(name string) os.Error { - _, err := run([]string{"hg", "revert", name}, nil); - return err; + _, err := run([]string{"hg", "revert", name}, nil) + return err } // hgCopy copies src to dst in the repository. // Note that the argument order matches io.Copy, not "hg cp". func hgCopy(dst, src string) os.Error { - _, err := run([]string{"hg", "cp", src, dst}, nil); - return err; + _, err := run([]string{"hg", "cp", src, dst}, nil) + return err } // hgRename renames src to dst in the repository. // Note that the argument order matches io.Copy, not "hg mv". func hgRename(dst, src string) os.Error { - _, err := run([]string{"hg", "mv", src, dst}, nil); - return err; + _, err := run([]string{"hg", "mv", src, dst}, nil) + return err } func copy(a []string) []string { - b := make([]string, len(a)); + b := make([]string, len(a)) for i, s := range a { b[i] = s } - return b; + return b } var lookPathCache = make(map[string]string) @@ -332,61 +332,61 @@ var lookPathCache = make(map[string]string) // It provides input on standard input to the command. func run(argv []string, input []byte) (out string, err os.Error) { if len(argv) < 1 { - err = os.EINVAL; - goto Error; + err = os.EINVAL + goto Error } - prog, ok := lookPathCache[argv[0]]; + prog, ok := lookPathCache[argv[0]] if !ok { - prog, err = exec.LookPath(argv[0]); + prog, err = exec.LookPath(argv[0]) if err != nil { goto Error } - lookPathCache[argv[0]] = prog; + lookPathCache[argv[0]] = prog } // fmt.Fprintf(os.Stderr, "%v\n", argv); - var cmd *exec.Cmd; + var cmd *exec.Cmd if len(input) == 0 { - cmd, err = exec.Run(prog, argv, os.Environ(), exec.DevNull, exec.Pipe, exec.MergeWithStdout); + cmd, err = exec.Run(prog, argv, os.Environ(), exec.DevNull, exec.Pipe, exec.MergeWithStdout) if err != nil { goto Error } } else { - cmd, err = exec.Run(prog, argv, os.Environ(), exec.Pipe, exec.Pipe, exec.MergeWithStdout); + cmd, err = exec.Run(prog, argv, os.Environ(), exec.Pipe, exec.Pipe, exec.MergeWithStdout) if err != nil { goto Error } go func() { - cmd.Stdin.Write(input); - cmd.Stdin.Close(); - }(); + cmd.Stdin.Write(input) + cmd.Stdin.Close() + }() } - defer cmd.Close(); - var buf bytes.Buffer; - _, err = io.Copy(&buf, cmd.Stdout); - out = buf.String(); + defer cmd.Close() + var buf bytes.Buffer + _, err = io.Copy(&buf, cmd.Stdout) + out = buf.String() if err != nil { - cmd.Wait(0); - goto Error; + cmd.Wait(0) + goto Error } - w, err := cmd.Wait(0); + w, err := cmd.Wait(0) if err != nil { goto Error } if !w.Exited() || w.ExitStatus() != 0 { - err = w; - goto Error; + err = w + goto Error } - return; + return Error: - err = &runError{copy(argv), err}; - return; + err = &runError{copy(argv), err} + return } // A runError represents an error that occurred while running a command. type runError struct { - cmd []string; - err os.Error; + cmd []string + err os.Error } -func (e *runError) String() string { return strings.Join(e.cmd, " ") + ": " + e.err.String() } +func (e *runError) String() string { return strings.Join(e.cmd, " ") + ": " + e.err.String() } |