diff options
104 files changed, 7004 insertions, 7004 deletions
diff --git a/src/pkg/go/ast/ast.go b/src/pkg/go/ast/ast.go index 60a90050c..16a0c66a1 100644 --- a/src/pkg/go/ast/ast.go +++ b/src/pkg/go/ast/ast.go @@ -8,9 +8,9 @@ package ast import ( - "go/token"; - "unicode"; - "utf8"; + "go/token" + "unicode" + "utf8" ) @@ -35,28 +35,28 @@ import ( // All node types implement the Node interface. type Node interface { // Pos returns the (beginning) position of the node. - Pos() token.Position; + Pos() token.Position } // All expression nodes implement the Expr interface. type Expr interface { - Node; - exprNode(); + Node + exprNode() } // All statement nodes implement the Stmt interface. type Stmt interface { - Node; - stmtNode(); + Node + stmtNode() } // All declaration nodes implement the Decl interface. type Decl interface { - Node; - declNode(); + Node + declNode() } @@ -65,8 +65,8 @@ type Decl interface { // A Comment node represents a single //-style or /*-style comment. type Comment struct { - token.Position; // beginning position of the comment - Text []byte; // comment text (excluding '\n' for //-style comments) + token.Position // beginning position of the comment + Text []byte // comment text (excluding '\n' for //-style comments) } @@ -74,8 +74,8 @@ type Comment struct { // with no other tokens and no empty lines between. // type CommentGroup struct { - List []*Comment; - Next *CommentGroup; // next comment group in source order + List []*Comment + Next *CommentGroup // next comment group in source order } @@ -87,11 +87,11 @@ type CommentGroup struct { // in a signature. // type Field struct { - Doc *CommentGroup; // associated documentation; or nil - Names []*Ident; // field/method/parameter names; or nil if anonymous field - Type Expr; // field/method/parameter type - Tag []*BasicLit; // field tag; or nil - Comment *CommentGroup; // line comments; or nil + Doc *CommentGroup // associated documentation; or nil + Names []*Ident // field/method/parameter names; or nil if anonymous field + Type Expr // field/method/parameter type + Tag []*BasicLit // field tag; or nil + Comment *CommentGroup // line comments; or nil } @@ -99,7 +99,7 @@ func (f *Field) Pos() token.Position { if len(f.Names) > 0 { return f.Names[0].Pos() } - return f.Type.Pos(); + return f.Type.Pos() } @@ -111,129 +111,129 @@ type ( // syntax errors for which no correct expression nodes can be // created. // - BadExpr struct { - token.Position; // beginning position of bad expression - }; + BadExpr struct { + token.Position // beginning position of bad expression + } // An Ident node represents an identifier. - Ident struct { - token.Position; // identifier position - Value string; // identifier string (e.g. foobar) - }; + Ident struct { + token.Position // identifier position + Value string // identifier string (e.g. foobar) + } // An Ellipsis node stands for the "..." type in a // parameter list or the "..." length in an array type. // - Ellipsis struct { - token.Position; // position of "..." - }; + Ellipsis struct { + token.Position // position of "..." + } // A BasicLit node represents a literal of basic type. - BasicLit struct { - token.Position; // literal position - Kind token.Token; // token.INT, token.FLOAT, token.CHAR, or token.STRING - Value []byte; // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 'a', '\x7f', "foo" or `\m\n\o` - }; + BasicLit struct { + token.Position // literal position + Kind token.Token // token.INT, token.FLOAT, token.CHAR, or token.STRING + Value []byte // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 'a', '\x7f', "foo" or `\m\n\o` + } // A StringList node represents a sequence of adjacent string literals. // A single string literal (common case) is represented by a BasicLit // node; StringList nodes are used only if there are two or more string // literals in a sequence. // - StringList struct { - Strings []*BasicLit; // list of strings, len(Strings) > 1 - }; + StringList struct { + Strings []*BasicLit // list of strings, len(Strings) > 1 + } // A FuncLit node represents a function literal. - FuncLit struct { - Type *FuncType; // function type - Body *BlockStmt; // function body - }; + FuncLit struct { + Type *FuncType // function type + Body *BlockStmt // function body + } // A CompositeLit node represents a composite literal. // - CompositeLit struct { - Type Expr; // literal type - Lbrace token.Position; // position of "{" - Elts []Expr; // list of composite elements - Rbrace token.Position; // position of "}" - }; + CompositeLit struct { + Type Expr // literal type + Lbrace token.Position // position of "{" + Elts []Expr // list of composite elements + Rbrace token.Position // position of "}" + } // A ParenExpr node represents a parenthesized expression. - ParenExpr struct { - token.Position; // position of "(" - X Expr; // parenthesized expression - Rparen token.Position; // position of ")" - }; + ParenExpr struct { + token.Position // position of "(" + X Expr // parenthesized expression + Rparen token.Position // position of ")" + } // A SelectorExpr node represents an expression followed by a selector. - SelectorExpr struct { - X Expr; // expression - Sel *Ident; // field selector - }; + SelectorExpr struct { + X Expr // expression + Sel *Ident // field selector + } // An IndexExpr node represents an expression followed by an index. - IndexExpr struct { - X Expr; // expression - Index Expr; // index expression - }; + IndexExpr struct { + X Expr // expression + Index Expr // index expression + } // An SliceExpr node represents an expression followed by slice indices. - SliceExpr struct { - X Expr; // expression - Index Expr; // beginning of slice range - End Expr; // end of slice range; or nil - }; + SliceExpr struct { + X Expr // expression + Index Expr // beginning of slice range + End Expr // end of slice range; or nil + } // A TypeAssertExpr node represents an expression followed by a // type assertion. // - TypeAssertExpr struct { - X Expr; // expression - Type Expr; // asserted type; nil means type switch X.(type) - }; + TypeAssertExpr struct { + X Expr // expression + Type Expr // asserted type; nil means type switch X.(type) + } // A CallExpr node represents an expression followed by an argument list. - CallExpr struct { - Fun Expr; // function expression - Lparen token.Position; // position of "(" - Args []Expr; // function arguments - Rparen token.Position; // positions of ")" - }; + CallExpr struct { + Fun Expr // function expression + Lparen token.Position // position of "(" + Args []Expr // function arguments + Rparen token.Position // positions of ")" + } // A StarExpr node represents an expression of the form "*" Expression. // Semantically it could be a unary "*" expression, or a pointer type. - StarExpr struct { - token.Position; // position of "*" - X Expr; // operand - }; + StarExpr struct { + token.Position // position of "*" + X Expr // operand + } // A UnaryExpr node represents a unary expression. // Unary "*" expressions are represented via StarExpr nodes. // - UnaryExpr struct { - token.Position; // position of Op - Op token.Token; // operator - X Expr; // operand - }; + UnaryExpr struct { + token.Position // position of Op + Op token.Token // operator + X Expr // operand + } // A BinaryExpr node represents a binary expression. // - BinaryExpr struct { - X Expr; // left operand - OpPos token.Position; // position of Op - Op token.Token; // operator - Y Expr; // right operand - }; + BinaryExpr struct { + X Expr // left operand + OpPos token.Position // position of Op + Op token.Token // operator + Y Expr // right operand + } // A KeyValueExpr node represents (key : value) pairs // in composite literals. // - KeyValueExpr struct { - Key Expr; - Colon token.Position; // position of ":" - Value Expr; - }; + KeyValueExpr struct { + Key Expr + Colon token.Position // position of ":" + Value Expr + } ) @@ -243,8 +243,8 @@ type ( type ChanDir int const ( - SEND ChanDir = 1 << iota; - RECV; + SEND ChanDir = 1 << iota + RECV ) @@ -254,110 +254,110 @@ const ( // type ( // An ArrayType node represents an array or slice type. - ArrayType struct { - token.Position; // position of "[" - Len Expr; // Ellipsis node for [...]T array types, nil for slice types - Elt Expr; // element type - }; + ArrayType struct { + token.Position // position of "[" + Len Expr // Ellipsis node for [...]T array types, nil for slice types + Elt Expr // element type + } // A StructType node represents a struct type. - StructType struct { - token.Position; // position of "struct" keyword - Lbrace token.Position; // position of "{" - Fields []*Field; // list of field declarations - Rbrace token.Position; // position of "}" - Incomplete bool; // true if (source) fields are missing in the Fields list - }; + StructType struct { + token.Position // position of "struct" keyword + Lbrace token.Position // position of "{" + Fields []*Field // list of field declarations + Rbrace token.Position // position of "}" + Incomplete bool // true if (source) fields are missing in the Fields list + } // Pointer types are represented via StarExpr nodes. // A FuncType node represents a function type. - FuncType struct { - token.Position; // position of "func" keyword - Params []*Field; // (incoming) parameters - Results []*Field; // (outgoing) results - }; + FuncType struct { + token.Position // position of "func" keyword + Params []*Field // (incoming) parameters + Results []*Field // (outgoing) results + } // An InterfaceType node represents an interface type. - InterfaceType struct { - token.Position; // position of "interface" keyword - Lbrace token.Position; // position of "{" - Methods []*Field; // list of methods - Rbrace token.Position; // position of "}" - Incomplete bool; // true if (source) methods are missing in the Methods list - }; + InterfaceType struct { + token.Position // position of "interface" keyword + Lbrace token.Position // position of "{" + Methods []*Field // list of methods + Rbrace token.Position // position of "}" + Incomplete bool // true if (source) methods are missing in the Methods list + } // A MapType node represents a map type. - MapType struct { - token.Position; // position of "map" keyword - Key Expr; - Value Expr; - }; + MapType struct { + token.Position // position of "map" keyword + Key Expr + Value Expr + } // A ChanType node represents a channel type. - ChanType struct { - token.Position; // position of "chan" keyword or "<-" (whichever comes first) - Dir ChanDir; // channel direction - Value Expr; // value type - }; + ChanType struct { + token.Position // position of "chan" keyword or "<-" (whichever comes first) + Dir ChanDir // channel direction + Value Expr // value type + } ) // Pos() implementations for expression/type where the position // corresponds to the position of a sub-node. // -func (x *StringList) Pos() token.Position { return x.Strings[0].Pos() } -func (x *FuncLit) Pos() token.Position { return x.Type.Pos() } -func (x *CompositeLit) Pos() token.Position { return x.Type.Pos() } -func (x *SelectorExpr) Pos() token.Position { return x.X.Pos() } -func (x *IndexExpr) Pos() token.Position { return x.X.Pos() } -func (x *SliceExpr) Pos() token.Position { return x.X.Pos() } -func (x *TypeAssertExpr) Pos() token.Position { return x.X.Pos() } -func (x *CallExpr) Pos() token.Position { return x.Fun.Pos() } -func (x *BinaryExpr) Pos() token.Position { return x.X.Pos() } -func (x *KeyValueExpr) Pos() token.Position { return x.Key.Pos() } +func (x *StringList) Pos() token.Position { return x.Strings[0].Pos() } +func (x *FuncLit) Pos() token.Position { return x.Type.Pos() } +func (x *CompositeLit) Pos() token.Position { return x.Type.Pos() } +func (x *SelectorExpr) Pos() token.Position { return x.X.Pos() } +func (x *IndexExpr) Pos() token.Position { return x.X.Pos() } +func (x *SliceExpr) Pos() token.Position { return x.X.Pos() } +func (x *TypeAssertExpr) Pos() token.Position { return x.X.Pos() } +func (x *CallExpr) Pos() token.Position { return x.Fun.Pos() } +func (x *BinaryExpr) Pos() token.Position { return x.X.Pos() } +func (x *KeyValueExpr) Pos() token.Position { return x.Key.Pos() } // exprNode() ensures that only expression/type nodes can be // assigned to an ExprNode. -func (x *BadExpr) exprNode() {} -func (x *Ident) exprNode() {} -func (x *Ellipsis) exprNode() {} -func (x *BasicLit) exprNode() {} -func (x *StringList) exprNode() {} -func (x *FuncLit) exprNode() {} -func (x *CompositeLit) exprNode() {} -func (x *ParenExpr) exprNode() {} -func (x *SelectorExpr) exprNode() {} -func (x *IndexExpr) exprNode() {} -func (x *SliceExpr) exprNode() {} -func (x *TypeAssertExpr) exprNode() {} -func (x *CallExpr) exprNode() {} -func (x *StarExpr) exprNode() {} -func (x *UnaryExpr) exprNode() {} -func (x *BinaryExpr) exprNode() {} -func (x *KeyValueExpr) exprNode() {} - -func (x *ArrayType) exprNode() {} -func (x *StructType) exprNode() {} -func (x *FuncType) exprNode() {} -func (x *InterfaceType) exprNode() {} -func (x *MapType) exprNode() {} -func (x *ChanType) exprNode() {} +func (x *BadExpr) exprNode() {} +func (x *Ident) exprNode() {} +func (x *Ellipsis) exprNode() {} +func (x *BasicLit) exprNode() {} +func (x *StringList) exprNode() {} +func (x *FuncLit) exprNode() {} +func (x *CompositeLit) exprNode() {} +func (x *ParenExpr) exprNode() {} +func (x *SelectorExpr) exprNode() {} +func (x *IndexExpr) exprNode() {} +func (x *SliceExpr) exprNode() {} +func (x *TypeAssertExpr) exprNode() {} +func (x *CallExpr) exprNode() {} +func (x *StarExpr) exprNode() {} +func (x *UnaryExpr) exprNode() {} +func (x *BinaryExpr) exprNode() {} +func (x *KeyValueExpr) exprNode() {} + +func (x *ArrayType) exprNode() {} +func (x *StructType) exprNode() {} +func (x *FuncType) exprNode() {} +func (x *InterfaceType) exprNode() {} +func (x *MapType) exprNode() {} +func (x *ChanType) exprNode() {} // IsExported returns whether name is an exported Go symbol // (i.e., whether it begins with an uppercase letter). func IsExported(name string) bool { - ch, _ := utf8.DecodeRuneInString(name); - return unicode.IsUpper(ch); + ch, _ := utf8.DecodeRuneInString(name) + return unicode.IsUpper(ch) } // IsExported returns whether name is an exported Go symbol // (i.e., whether it begins with an uppercase letter). -func (name *Ident) IsExported() bool { return IsExported(name.Value) } +func (name *Ident) IsExported() bool { return IsExported(name.Value) } -func (name *Ident) String() string { return name.Value } +func (name *Ident) String() string { return name.Value } // ---------------------------------------------------------------------------- @@ -371,196 +371,196 @@ type ( // syntax errors for which no correct statement nodes can be // created. // - BadStmt struct { - token.Position; // beginning position of bad statement - }; + BadStmt struct { + token.Position // beginning position of bad statement + } // A DeclStmt node represents a declaration in a statement list. - DeclStmt struct { - Decl Decl; - }; + DeclStmt struct { + Decl Decl + } // An EmptyStmt node represents an empty statement. // The "position" of the empty statement is the position // of the immediately preceeding semicolon. // - EmptyStmt struct { - token.Position; // position of preceeding ";" - }; + EmptyStmt struct { + token.Position // position of preceeding ";" + } // A LabeledStmt node represents a labeled statement. - LabeledStmt struct { - Label *Ident; - Stmt Stmt; - }; + LabeledStmt struct { + Label *Ident + Stmt Stmt + } // An ExprStmt node represents a (stand-alone) expression // in a statement list. // - ExprStmt struct { - X Expr; // expression - }; + ExprStmt struct { + X Expr // expression + } // An IncDecStmt node represents an increment or decrement statement. - IncDecStmt struct { - X Expr; - Tok token.Token; // INC or DEC - }; + IncDecStmt struct { + X Expr + Tok token.Token // INC or DEC + } // An AssignStmt node represents an assignment or // a short variable declaration. - AssignStmt struct { - Lhs []Expr; - TokPos token.Position; // position of Tok - Tok token.Token; // assignment token, DEFINE - Rhs []Expr; - }; + AssignStmt struct { + Lhs []Expr + TokPos token.Position // position of Tok + Tok token.Token // assignment token, DEFINE + Rhs []Expr + } // A GoStmt node represents a go statement. - GoStmt struct { - token.Position; // position of "go" keyword - Call *CallExpr; - }; + GoStmt struct { + token.Position // position of "go" keyword + Call *CallExpr + } // A DeferStmt node represents a defer statement. - DeferStmt struct { - token.Position; // position of "defer" keyword - Call *CallExpr; - }; + DeferStmt struct { + token.Position // position of "defer" keyword + Call *CallExpr + } // A ReturnStmt node represents a return statement. - ReturnStmt struct { - token.Position; // position of "return" keyword - Results []Expr; - }; + ReturnStmt struct { + token.Position // position of "return" keyword + Results []Expr + } // A BranchStmt node represents a break, continue, goto, // or fallthrough statement. // - BranchStmt struct { - token.Position; // position of Tok - Tok token.Token; // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH) - Label *Ident; - }; + BranchStmt struct { + token.Position // position of Tok + Tok token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH) + Label *Ident + } // A BlockStmt node represents a braced statement list. - BlockStmt struct { - token.Position; // position of "{" - List []Stmt; - Rbrace token.Position; // position of "}" - }; + BlockStmt struct { + token.Position // position of "{" + List []Stmt + Rbrace token.Position // position of "}" + } // An IfStmt node represents an if statement. - IfStmt struct { - token.Position; // position of "if" keyword - Init Stmt; - Cond Expr; - Body *BlockStmt; - Else Stmt; - }; + IfStmt struct { + token.Position // position of "if" keyword + Init Stmt + Cond Expr + Body *BlockStmt + Else Stmt + } // A CaseClause represents a case of an expression switch statement. - CaseClause struct { - token.Position; // position of "case" or "default" keyword - Values []Expr; // nil means default case - Colon token.Position; // position of ":" - Body []Stmt; // statement list; or nil - }; + CaseClause struct { + token.Position // position of "case" or "default" keyword + Values []Expr // nil means default case + Colon token.Position // position of ":" + Body []Stmt // statement list; or nil + } // A SwitchStmt node represents an expression switch statement. - SwitchStmt struct { - token.Position; // position of "switch" keyword - Init Stmt; - Tag Expr; - Body *BlockStmt; // CaseClauses only - }; + SwitchStmt struct { + token.Position // position of "switch" keyword + Init Stmt + Tag Expr + Body *BlockStmt // CaseClauses only + } // A TypeCaseClause represents a case of a type switch statement. - TypeCaseClause struct { - token.Position; // position of "case" or "default" keyword - Types []Expr; // nil means default case - Colon token.Position; // position of ":" - Body []Stmt; // statement list; or nil - }; + TypeCaseClause struct { + token.Position // position of "case" or "default" keyword + Types []Expr // nil means default case + Colon token.Position // position of ":" + Body []Stmt // statement list; or nil + } // An TypeSwitchStmt node represents a type switch statement. - TypeSwitchStmt struct { - token.Position; // position of "switch" keyword - Init Stmt; - Assign Stmt; // x := y.(type) - Body *BlockStmt; // TypeCaseClauses only - }; + TypeSwitchStmt struct { + token.Position // position of "switch" keyword + Init Stmt + Assign Stmt // x := y.(type) + Body *BlockStmt // TypeCaseClauses only + } // A CommClause node represents a case of a select statement. - CommClause struct { - token.Position; // position of "case" or "default" keyword - Tok token.Token; // ASSIGN or DEFINE (valid only if Lhs != nil) - Lhs, Rhs Expr; // Rhs == nil means default case - Colon token.Position; // position of ":" - Body []Stmt; // statement list; or nil - }; + CommClause struct { + token.Position // position of "case" or "default" keyword + Tok token.Token // ASSIGN or DEFINE (valid only if Lhs != nil) + Lhs, Rhs Expr // Rhs == nil means default case + Colon token.Position // position of ":" + Body []Stmt // statement list; or nil + } // An SelectStmt node represents a select statement. - SelectStmt struct { - token.Position; // position of "select" keyword - Body *BlockStmt; // CommClauses only - }; + SelectStmt struct { + token.Position // position of "select" keyword + Body *BlockStmt // CommClauses only + } // A ForStmt represents a for statement. - ForStmt struct { - token.Position; // position of "for" keyword - Init Stmt; - Cond Expr; - Post Stmt; - Body *BlockStmt; - }; + ForStmt struct { + token.Position // position of "for" keyword + Init Stmt + Cond Expr + Post Stmt + Body *BlockStmt + } // A RangeStmt represents a for statement with a range clause. - RangeStmt struct { - token.Position; // position of "for" keyword - Key, Value Expr; // Value may be nil - TokPos token.Position; // position of Tok - Tok token.Token; // ASSIGN, DEFINE - X Expr; // value to range over - Body *BlockStmt; - }; + RangeStmt struct { + token.Position // position of "for" keyword + Key, Value Expr // Value may be nil + TokPos token.Position // position of Tok + Tok token.Token // ASSIGN, DEFINE + X Expr // value to range over + Body *BlockStmt + } ) // Pos() implementations for statement nodes where the position // corresponds to the position of a sub-node. // -func (s *DeclStmt) Pos() token.Position { return s.Decl.Pos() } -func (s *LabeledStmt) Pos() token.Position { return s.Label.Pos() } -func (s *ExprStmt) Pos() token.Position { return s.X.Pos() } -func (s *IncDecStmt) Pos() token.Position { return s.X.Pos() } -func (s *AssignStmt) Pos() token.Position { return s.Lhs[0].Pos() } +func (s *DeclStmt) Pos() token.Position { return s.Decl.Pos() } +func (s *LabeledStmt) Pos() token.Position { return s.Label.Pos() } +func (s *ExprStmt) Pos() token.Position { return s.X.Pos() } +func (s *IncDecStmt) Pos() token.Position { return s.X.Pos() } +func (s *AssignStmt) Pos() token.Position { return s.Lhs[0].Pos() } // stmtNode() ensures that only statement nodes can be // assigned to a StmtNode. // -func (s *BadStmt) stmtNode() {} -func (s *DeclStmt) stmtNode() {} -func (s *EmptyStmt) stmtNode() {} -func (s *LabeledStmt) stmtNode() {} -func (s *ExprStmt) stmtNode() {} -func (s *IncDecStmt) stmtNode() {} -func (s *AssignStmt) stmtNode() {} -func (s *GoStmt) stmtNode() {} -func (s *DeferStmt) stmtNode() {} -func (s *ReturnStmt) stmtNode() {} -func (s *BranchStmt) stmtNode() {} -func (s *BlockStmt) stmtNode() {} -func (s *IfStmt) stmtNode() {} -func (s *CaseClause) stmtNode() {} -func (s *SwitchStmt) stmtNode() {} -func (s *TypeCaseClause) stmtNode() {} -func (s *TypeSwitchStmt) stmtNode() {} -func (s *CommClause) stmtNode() {} -func (s *SelectStmt) stmtNode() {} -func (s *ForStmt) stmtNode() {} -func (s *RangeStmt) stmtNode() {} +func (s *BadStmt) stmtNode() {} +func (s *DeclStmt) stmtNode() {} +func (s *EmptyStmt) stmtNode() {} +func (s *LabeledStmt) stmtNode() {} +func (s *ExprStmt) stmtNode() {} +func (s *IncDecStmt) stmtNode() {} +func (s *AssignStmt) stmtNode() {} +func (s *GoStmt) stmtNode() {} +func (s *DeferStmt) stmtNode() {} +func (s *ReturnStmt) stmtNode() {} +func (s *BranchStmt) stmtNode() {} +func (s *BlockStmt) stmtNode() {} +func (s *IfStmt) stmtNode() {} +func (s *CaseClause) stmtNode() {} +func (s *SwitchStmt) stmtNode() {} +func (s *TypeCaseClause) stmtNode() {} +func (s *TypeSwitchStmt) stmtNode() {} +func (s *CommClause) stmtNode() {} +func (s *SelectStmt) stmtNode() {} +func (s *ForStmt) stmtNode() {} +func (s *RangeStmt) stmtNode() {} // ---------------------------------------------------------------------------- @@ -571,36 +571,36 @@ func (s *RangeStmt) stmtNode() {} // type ( // The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec. - Spec interface { - Node; - specNode(); - }; + Spec interface { + Node + specNode() + } // An ImportSpec node represents a single package import. - ImportSpec struct { - Doc *CommentGroup; // associated documentation; or nil - Name *Ident; // local package name (including "."); or nil - Path []*BasicLit; // package path - Comment *CommentGroup; // line comments; or nil - }; + ImportSpec struct { + Doc *CommentGroup // associated documentation; or nil + Name *Ident // local package name (including "."); or nil + Path []*BasicLit // package path + Comment *CommentGroup // line comments; or nil + } // A ValueSpec node represents a constant or variable declaration // (ConstSpec or VarSpec production). - ValueSpec struct { - Doc *CommentGroup; // associated documentation; or nil - Names []*Ident; // value names - Type Expr; // value type; or nil - Values []Expr; // initial values; or nil - Comment *CommentGroup; // line comments; or nil - }; + ValueSpec struct { + Doc *CommentGroup // associated documentation; or nil + Names []*Ident // value names + Type Expr // value type; or nil + Values []Expr // initial values; or nil + Comment *CommentGroup // line comments; or nil + } // A TypeSpec node represents a type declaration (TypeSpec production). - TypeSpec struct { - Doc *CommentGroup; // associated documentation; or nil - Name *Ident; // type name - Type Expr; - Comment *CommentGroup; // line comments; or nil - }; + TypeSpec struct { + Doc *CommentGroup // associated documentation; or nil + Name *Ident // type name + Type Expr + Comment *CommentGroup // line comments; or nil + } ) @@ -610,19 +610,19 @@ func (s *ImportSpec) Pos() token.Position { if s.Name != nil { return s.Name.Pos() } - return s.Path[0].Pos(); + return s.Path[0].Pos() } -func (s *ValueSpec) Pos() token.Position { return s.Names[0].Pos() } -func (s *TypeSpec) Pos() token.Position { return s.Name.Pos() } +func (s *ValueSpec) Pos() token.Position { return s.Names[0].Pos() } +func (s *TypeSpec) Pos() token.Position { return s.Name.Pos() } // specNode() ensures that only spec nodes can be // assigned to a Spec. // -func (s *ImportSpec) specNode() {} -func (s *ValueSpec) specNode() {} -func (s *TypeSpec) specNode() {} +func (s *ImportSpec) specNode() {} +func (s *ValueSpec) specNode() {} +func (s *TypeSpec) specNode() {} // A declaration is represented by one of the following declaration nodes. @@ -632,9 +632,9 @@ type ( // syntax errors for which no correct declaration nodes can be // created. // - BadDecl struct { - token.Position; // beginning position of bad declaration - }; + BadDecl struct { + token.Position // beginning position of bad declaration + } // A GenDecl node (generic declaration node) represents an import, // constant, type or variable declaration. A valid Lparen position @@ -647,36 +647,36 @@ type ( // token.TYPE *TypeSpec // token.VAR *ValueSpec // - GenDecl struct { - Doc *CommentGroup; // associated documentation; or nil - token.Position; // position of Tok - Tok token.Token; // IMPORT, CONST, TYPE, VAR - Lparen token.Position; // position of '(', if any - Specs []Spec; - Rparen token.Position; // position of ')', if any - }; + GenDecl struct { + Doc *CommentGroup // associated documentation; or nil + token.Position // position of Tok + Tok token.Token // IMPORT, CONST, TYPE, VAR + Lparen token.Position // position of '(', if any + Specs []Spec + Rparen token.Position // position of ')', if any + } // A FuncDecl node represents a function declaration. - FuncDecl struct { - Doc *CommentGroup; // associated documentation; or nil - Recv *Field; // receiver (methods); or nil (functions) - Name *Ident; // function/method name - Type *FuncType; // position of Func keyword, parameters and results - Body *BlockStmt; // function body; or nil (forward declaration) - }; + FuncDecl struct { + Doc *CommentGroup // associated documentation; or nil + Recv *Field // receiver (methods); or nil (functions) + Name *Ident // function/method name + Type *FuncType // position of Func keyword, parameters and results + Body *BlockStmt // function body; or nil (forward declaration) + } ) // The position of a FuncDecl node is the position of its function type. -func (d *FuncDecl) Pos() token.Position { return d.Type.Pos() } +func (d *FuncDecl) Pos() token.Position { return d.Type.Pos() } // declNode() ensures that only declaration nodes can be // assigned to a DeclNode. // -func (d *BadDecl) declNode() {} -func (d *GenDecl) declNode() {} -func (d *FuncDecl) declNode() {} +func (d *BadDecl) declNode() {} +func (d *GenDecl) declNode() {} +func (d *FuncDecl) declNode() {} // ---------------------------------------------------------------------------- @@ -685,11 +685,11 @@ func (d *FuncDecl) declNode() {} // A File node represents a Go source file. // type File struct { - Doc *CommentGroup; // associated documentation; or nil - token.Position; // position of "package" keyword - Name *Ident; // package name - Decls []Decl; // top-level declarations - Comments *CommentGroup; // list of all comments in the source file + Doc *CommentGroup // associated documentation; or nil + token.Position // position of "package" keyword + Name *Ident // package name + Decls []Decl // top-level declarations + Comments *CommentGroup // list of all comments in the source file } @@ -697,7 +697,7 @@ type File struct { // collectively building a Go package. // type Package struct { - Name string; // package name - Path string; // package path - Files map[string]*File; // path-relative filenames + Name string // package name + Path string // package path + Files map[string]*File // path-relative filenames } diff --git a/src/pkg/go/ast/filter.go b/src/pkg/go/ast/filter.go index 772407400..697c9fcdc 100644 --- a/src/pkg/go/ast/filter.go +++ b/src/pkg/go/ast/filter.go @@ -8,14 +8,14 @@ import "go/token" func filterIdentList(list []*Ident) []*Ident { - j := 0; + j := 0 for _, x := range list { if x.IsExported() { - list[j] = x; - j++; + list[j] = x + j++ } } - return list[0:j]; + return list[0:j] } @@ -32,14 +32,14 @@ func isExportedType(typ Expr) bool { case *StarExpr: return isExportedType(t.X) } - return false; + return false } func filterFieldList(list []*Field, incomplete *bool) []*Field { - j := 0; + j := 0 for _, f := range list { - exported := false; + exported := false if len(f.Names) == 0 { // anonymous field // (Note that a non-exported anonymous field @@ -49,23 +49,23 @@ func filterFieldList(list []*Field, incomplete *bool) []*Field { // type information.) exported = isExportedType(f.Type) } else { - n := len(f.Names); - f.Names = filterIdentList(f.Names); + n := len(f.Names) + f.Names = filterIdentList(f.Names) if len(f.Names) < n { *incomplete = true } - exported = len(f.Names) > 0; + exported = len(f.Names) > 0 } if exported { - filterType(f.Type); - list[j] = f; - j++; + filterType(f.Type) + list[j] = f + j++ } } if j < len(list) { *incomplete = true } - return list[0:j]; + return list[0:j] } @@ -85,13 +85,13 @@ func filterType(typ Expr) { case *StructType: t.Fields = filterFieldList(t.Fields, &t.Incomplete) case *FuncType: - filterParamList(t.Params); - filterParamList(t.Results); + filterParamList(t.Params) + filterParamList(t.Results) case *InterfaceType: t.Methods = filterFieldList(t.Methods, &t.Incomplete) case *MapType: - filterType(t.Key); - filterType(t.Value); + filterType(t.Key) + filterType(t.Value) case *ChanType: filterType(t.Value) } @@ -101,48 +101,48 @@ func filterType(typ Expr) { func filterSpec(spec Spec) bool { switch s := spec.(type) { case *ValueSpec: - s.Names = filterIdentList(s.Names); + s.Names = filterIdentList(s.Names) if len(s.Names) > 0 { - filterType(s.Type); - return true; + filterType(s.Type) + return true } case *TypeSpec: // TODO(gri) consider stripping forward declarations // of structs, interfaces, functions, and methods if s.Name.IsExported() { - filterType(s.Type); - return true; + filterType(s.Type) + return true } } - return false; + return false } func filterSpecList(list []Spec) []Spec { - j := 0; + j := 0 for _, s := range list { if filterSpec(s) { - list[j] = s; - j++; + list[j] = s + j++ } } - return list[0:j]; + return list[0:j] } func filterDecl(decl Decl) bool { switch d := decl.(type) { case *GenDecl: - d.Specs = filterSpecList(d.Specs); - return len(d.Specs) > 0; + d.Specs = filterSpecList(d.Specs) + return len(d.Specs) > 0 case *FuncDecl: // TODO consider removing function declaration altogether if // forward declaration (i.e., if d.Body == nil) because // in that case the actual declaration will come later. - d.Body = nil; // strip body - return d.Name.IsExported(); + d.Body = nil // strip body + return d.Name.IsExported() } - return false; + return false } @@ -157,15 +157,15 @@ func filterDecl(decl Decl) bool { // false otherwise. // func FileExports(src *File) bool { - j := 0; + j := 0 for _, d := range src.Decls { if filterDecl(d) { - src.Decls[j] = d; - j++; + src.Decls[j] = d + j++ } } - src.Decls = src.Decls[0:j]; - return j > 0; + src.Decls = src.Decls[0:j] + return j > 0 } @@ -177,13 +177,13 @@ func FileExports(src *File) bool { // returns false otherwise. // func PackageExports(pkg *Package) bool { - hasExports := false; + hasExports := false for _, f := range pkg.Files { if FileExports(f) { hasExports = true } } - return hasExports; + return hasExports } @@ -199,13 +199,13 @@ var separator = &Comment{noPos, []byte{'/', '/'}} func MergePackageFiles(pkg *Package) *File { // Count the number of package comments and declarations across // all package files. - ncomments := 0; - ndecls := 0; + ncomments := 0 + ndecls := 0 for _, f := range pkg.Files { if f.Doc != nil { - ncomments += len(f.Doc.List) + 1 // +1 for separator + ncomments += len(f.Doc.List) + 1 // +1 for separator } - ndecls += len(f.Decls); + ndecls += len(f.Decls) } // Collect package comments from all package files into a single @@ -213,35 +213,35 @@ func MergePackageFiles(pkg *Package) *File { // is unspecified. In general there should be only one file with // a package comment; but it's better to collect extra comments // than drop them on the floor. - var doc *CommentGroup; + var doc *CommentGroup if ncomments > 0 { - list := make([]*Comment, ncomments-1); // -1: no separator before first group - i := 0; + list := make([]*Comment, ncomments-1) // -1: no separator before first group + i := 0 for _, f := range pkg.Files { if f.Doc != nil { if i > 0 { // not the first group - add separator - list[i] = separator; - i++; + list[i] = separator + i++ } for _, c := range f.Doc.List { - list[i] = c; - i++; + list[i] = c + i++ } } } - doc = &CommentGroup{list, nil}; + doc = &CommentGroup{list, nil} } // Collect declarations from all package files. - var decls []Decl; + var decls []Decl if ndecls > 0 { - decls = make([]Decl, ndecls); - i := 0; + decls = make([]Decl, ndecls) + i := 0 for _, f := range pkg.Files { for _, d := range f.Decls { - decls[i] = d; - i++; + decls[i] = d + i++ } } } @@ -249,5 +249,5 @@ func MergePackageFiles(pkg *Package) *File { // TODO(gri) Should collect comments as well. For that the comment // list should be changed back into a []*CommentGroup, // otherwise need to modify the existing linked list. - return &File{doc, noPos, &Ident{noPos, pkg.Name}, decls, nil}; + return &File{doc, noPos, &Ident{noPos, pkg.Name}, decls, nil} } diff --git a/src/pkg/go/ast/scope.go b/src/pkg/go/ast/scope.go index 240953673..e8ad12f97 100644 --- a/src/pkg/go/ast/scope.go +++ b/src/pkg/go/ast/scope.go @@ -11,13 +11,13 @@ package ast // NOTE: WORK IN PROGRESS // type Scope struct { - Outer *Scope; - Names map[string]*Ident; + Outer *Scope + Names map[string]*Ident } // NewScope creates a new scope nested in the outer scope. -func NewScope(outer *Scope) *Scope { return &Scope{outer, make(map[string]*Ident)} } +func NewScope(outer *Scope) *Scope { return &Scope{outer, make(map[string]*Ident)} } // Declare inserts an identifier into the scope s. If the @@ -28,8 +28,8 @@ func (s *Scope) Declare(ident *Ident) bool { if _, found := s.Names[ident.Value]; found { return false } - s.Names[ident.Value] = ident; - return true; + s.Names[ident.Value] = ident + return true } @@ -43,7 +43,7 @@ func (s *Scope) Lookup(name string) *Ident { return ident } } - return nil; + return nil } diff --git a/src/pkg/go/ast/walk.go b/src/pkg/go/ast/walk.go index dc9c1fe3b..104596623 100644 --- a/src/pkg/go/ast/walk.go +++ b/src/pkg/go/ast/walk.go @@ -10,7 +10,7 @@ import "fmt" // If the result visitor w is not nil, Walk visits each of the children // of node with the visitor w, followed by a call of w.Visit(nil). type Visitor interface { - Visit(node interface{}) (w Visitor); + Visit(node interface{}) (w Visitor) } @@ -71,13 +71,13 @@ func Walk(v Visitor, node interface{}) { // comments list. case *Field: - walkCommentGroup(v, n.Doc); - Walk(v, n.Names); - Walk(v, n.Type); + walkCommentGroup(v, n.Doc) + Walk(v, n.Names) + Walk(v, n.Type) for _, x := range n.Tag { Walk(v, x) } - walkCommentGroup(v, n.Comment); + walkCommentGroup(v, n.Comment) // Expressions case *BadExpr, *Ident, *Ellipsis, *BasicLit: @@ -92,35 +92,35 @@ func Walk(v Visitor, node interface{}) { if n != nil { Walk(v, n.Type) } - walkBlockStmt(v, n.Body); + walkBlockStmt(v, n.Body) case *CompositeLit: - Walk(v, n.Type); - Walk(v, n.Elts); + Walk(v, n.Type) + Walk(v, n.Elts) case *ParenExpr: Walk(v, n.X) case *SelectorExpr: - Walk(v, n.X); - walkIdent(v, n.Sel); + Walk(v, n.X) + walkIdent(v, n.Sel) case *IndexExpr: - Walk(v, n.X); - Walk(v, n.Index); + Walk(v, n.X) + Walk(v, n.Index) case *SliceExpr: - Walk(v, n.X); - Walk(v, n.Index); - Walk(v, n.End); + Walk(v, n.X) + Walk(v, n.Index) + Walk(v, n.End) case *TypeAssertExpr: - Walk(v, n.X); - Walk(v, n.Type); + Walk(v, n.X) + Walk(v, n.Type) case *CallExpr: - Walk(v, n.Fun); - Walk(v, n.Args); + Walk(v, n.Fun) + Walk(v, n.Args) case *StarExpr: Walk(v, n.X) @@ -129,31 +129,31 @@ func Walk(v Visitor, node interface{}) { Walk(v, n.X) case *BinaryExpr: - Walk(v, n.X); - Walk(v, n.Y); + Walk(v, n.X) + Walk(v, n.Y) case *KeyValueExpr: - Walk(v, n.Key); - Walk(v, n.Value); + Walk(v, n.Key) + Walk(v, n.Value) // Types case *ArrayType: - Walk(v, n.Len); - Walk(v, n.Elt); + Walk(v, n.Len) + Walk(v, n.Elt) case *StructType: Walk(v, n.Fields) case *FuncType: - Walk(v, n.Params); - Walk(v, n.Results); + Walk(v, n.Params) + Walk(v, n.Results) case *InterfaceType: Walk(v, n.Methods) case *MapType: - Walk(v, n.Key); - Walk(v, n.Value); + Walk(v, n.Key) + Walk(v, n.Value) case *ChanType: Walk(v, n.Value) @@ -169,8 +169,8 @@ func Walk(v Visitor, node interface{}) { // nothing to do case *LabeledStmt: - walkIdent(v, n.Label); - Walk(v, n.Stmt); + walkIdent(v, n.Label) + Walk(v, n.Stmt) case *ExprStmt: Walk(v, n.X) @@ -179,8 +179,8 @@ func Walk(v Visitor, node interface{}) { Walk(v, n.X) case *AssignStmt: - Walk(v, n.Lhs); - Walk(v, n.Rhs); + Walk(v, n.Lhs) + Walk(v, n.Rhs) case *GoStmt: if n.Call != nil { @@ -202,99 +202,99 @@ func Walk(v Visitor, node interface{}) { Walk(v, n.List) case *IfStmt: - Walk(v, n.Init); - Walk(v, n.Cond); - walkBlockStmt(v, n.Body); - Walk(v, n.Else); + Walk(v, n.Init) + Walk(v, n.Cond) + walkBlockStmt(v, n.Body) + Walk(v, n.Else) case *CaseClause: - Walk(v, n.Values); - Walk(v, n.Body); + Walk(v, n.Values) + Walk(v, n.Body) case *SwitchStmt: - Walk(v, n.Init); - Walk(v, n.Tag); - walkBlockStmt(v, n.Body); + Walk(v, n.Init) + Walk(v, n.Tag) + walkBlockStmt(v, n.Body) case *TypeCaseClause: - Walk(v, n.Types); - Walk(v, n.Body); + Walk(v, n.Types) + Walk(v, n.Body) case *TypeSwitchStmt: - Walk(v, n.Init); - Walk(v, n.Assign); - walkBlockStmt(v, n.Body); + Walk(v, n.Init) + Walk(v, n.Assign) + walkBlockStmt(v, n.Body) case *CommClause: - Walk(v, n.Lhs); - Walk(v, n.Rhs); - Walk(v, n.Body); + Walk(v, n.Lhs) + Walk(v, n.Rhs) + Walk(v, n.Body) case *SelectStmt: walkBlockStmt(v, n.Body) case *ForStmt: - Walk(v, n.Init); - Walk(v, n.Cond); - Walk(v, n.Post); - walkBlockStmt(v, n.Body); + Walk(v, n.Init) + Walk(v, n.Cond) + Walk(v, n.Post) + walkBlockStmt(v, n.Body) case *RangeStmt: - Walk(v, n.Key); - Walk(v, n.Value); - Walk(v, n.X); - walkBlockStmt(v, n.Body); + Walk(v, n.Key) + Walk(v, n.Value) + Walk(v, n.X) + walkBlockStmt(v, n.Body) // Declarations case *ImportSpec: - walkCommentGroup(v, n.Doc); - walkIdent(v, n.Name); + walkCommentGroup(v, n.Doc) + walkIdent(v, n.Name) for _, x := range n.Path { Walk(v, x) } - walkCommentGroup(v, n.Comment); + walkCommentGroup(v, n.Comment) case *ValueSpec: - walkCommentGroup(v, n.Doc); - Walk(v, n.Names); - Walk(v, n.Type); - Walk(v, n.Values); - walkCommentGroup(v, n.Comment); + walkCommentGroup(v, n.Doc) + Walk(v, n.Names) + Walk(v, n.Type) + Walk(v, n.Values) + walkCommentGroup(v, n.Comment) case *TypeSpec: - walkCommentGroup(v, n.Doc); - walkIdent(v, n.Name); - Walk(v, n.Type); - walkCommentGroup(v, n.Comment); + walkCommentGroup(v, n.Doc) + walkIdent(v, n.Name) + Walk(v, n.Type) + walkCommentGroup(v, n.Comment) case *BadDecl: // nothing to do case *GenDecl: - walkCommentGroup(v, n.Doc); + walkCommentGroup(v, n.Doc) for _, s := range n.Specs { Walk(v, s) } case *FuncDecl: - walkCommentGroup(v, n.Doc); + walkCommentGroup(v, n.Doc) if n.Recv != nil { Walk(v, n.Recv) } - walkIdent(v, n.Name); + walkIdent(v, n.Name) if n.Type != nil { Walk(v, n.Type) } - walkBlockStmt(v, n.Body); + walkBlockStmt(v, n.Body) // Files and packages case *File: - walkCommentGroup(v, n.Doc); - walkIdent(v, n.Name); + walkCommentGroup(v, n.Doc) + walkIdent(v, n.Name) for _, d := range n.Decls { Walk(v, d) } - walkCommentGroup(v, n.Comments); + walkCommentGroup(v, n.Comments) case *Package: for _, f := range n.Files { @@ -322,9 +322,9 @@ func Walk(v Visitor, node interface{}) { } default: - fmt.Printf("ast.Walk: unexpected type %T", n); - panic(); + fmt.Printf("ast.Walk: unexpected type %T", n) + panic() } - v.Visit(nil); + v.Visit(nil) } diff --git a/src/pkg/go/doc/comment.go b/src/pkg/go/doc/comment.go index 79f837927..09622f715 100644 --- a/src/pkg/go/doc/comment.go +++ b/src/pkg/go/doc/comment.go @@ -7,10 +7,10 @@ package doc import ( - "go/ast"; - "io"; - "strings"; - "template"; // for htmlEscape + "go/ast" + "io" + "strings" + "template" // for htmlEscape ) // Comment extraction @@ -21,12 +21,12 @@ func CommentText(comment *ast.CommentGroup) string { if comment == nil { return "" } - comments := make([]string, len(comment.List)); + comments := make([]string, len(comment.List)) for i, c := range comment.List { comments[i] = string(c.Text) } - lines := make([]string, 0, 20); + lines := make([]string, 0, 20) for _, c := range comments { // Remove comment markers. // The parser has given us exactly the comment text. @@ -34,7 +34,7 @@ func CommentText(comment *ast.CommentGroup) string { case n >= 4 && c[0:2] == "/*" && c[n-2:n] == "*/": c = c[2 : n-2] case n >= 2 && c[0:2] == "//": - c = c[2:n]; + c = c[2:n] // Remove leading space after //, if there is one. if len(c) > 0 && c[0] == ' ' { c = c[1:] @@ -42,61 +42,61 @@ func CommentText(comment *ast.CommentGroup) string { } // Split on newlines. - cl := strings.Split(c, "\n", 0); + cl := strings.Split(c, "\n", 0) // Walk lines, stripping trailing white space and adding to list. for _, l := range cl { // Strip trailing white space - m := len(l); + m := len(l) for m > 0 && (l[m-1] == ' ' || l[m-1] == '\n' || l[m-1] == '\t' || l[m-1] == '\r') { m-- } - l = l[0:m]; + l = l[0:m] // Add to list. - n := len(lines); + n := len(lines) if n+1 >= cap(lines) { - newlines := make([]string, n, 2*cap(lines)); + newlines := make([]string, n, 2*cap(lines)) for k := range newlines { newlines[k] = lines[k] } - lines = newlines; + lines = newlines } - lines = lines[0 : n+1]; - lines[n] = l; + lines = lines[0 : n+1] + lines[n] = l } } // Remove leading blank lines; convert runs of // interior blank lines to a single blank line. - n := 0; + n := 0 for _, line := range lines { if line != "" || n > 0 && lines[n-1] != "" { - lines[n] = line; - n++; + lines[n] = line + n++ } } - lines = lines[0:n]; + lines = lines[0:n] // Add final "" entry to get trailing newline from Join. // The original loop always leaves room for one more. if n > 0 && lines[n-1] != "" { - lines = lines[0 : n+1]; - lines[n] = ""; + lines = lines[0 : n+1] + lines[n] = "" } - return strings.Join(lines, "\n"); + return strings.Join(lines, "\n") } // Split bytes into lines. func split(text []byte) [][]byte { // count lines - n := 0; - last := 0; + n := 0 + last := 0 for i, c := range text { if c == '\n' { - last = i + 1; - n++; + last = i + 1 + n++ } } if last < len(text) { @@ -104,76 +104,76 @@ func split(text []byte) [][]byte { } // split - out := make([][]byte, n); - last = 0; - n = 0; + out := make([][]byte, n) + last = 0 + n = 0 for i, c := range text { if c == '\n' { - out[n] = text[last : i+1]; - last = i + 1; - n++; + out[n] = text[last : i+1] + last = i + 1 + n++ } } if last < len(text) { out[n] = text[last:] } - return out; + return out } var ( - ldquo = strings.Bytes("“"); - rdquo = strings.Bytes("”"); + ldquo = strings.Bytes("“") + rdquo = strings.Bytes("”") ) // Escape comment text for HTML. // Also, turn `` into “ and '' into ”. func commentEscape(w io.Writer, s []byte) { - last := 0; + last := 0 for i := 0; i < len(s)-1; i++ { if s[i] == s[i+1] && (s[i] == '`' || s[i] == '\'') { - template.HTMLEscape(w, s[last:i]); - last = i + 2; + template.HTMLEscape(w, s[last:i]) + last = i + 2 switch s[i] { case '`': w.Write(ldquo) case '\'': w.Write(rdquo) } - i++; // loop will add one more + i++ // loop will add one more } } - template.HTMLEscape(w, s[last:]); + template.HTMLEscape(w, s[last:]) } var ( - html_p = strings.Bytes("<p>\n"); - html_endp = strings.Bytes("</p>\n"); - html_pre = strings.Bytes("<pre>"); - html_endpre = strings.Bytes("</pre>\n"); + html_p = strings.Bytes("<p>\n") + html_endp = strings.Bytes("</p>\n") + html_pre = strings.Bytes("<pre>") + html_endpre = strings.Bytes("</pre>\n") ) func indentLen(s []byte) int { - i := 0; + i := 0 for i < len(s) && (s[i] == ' ' || s[i] == '\t') { i++ } - return i; + return i } -func isBlank(s []byte) bool { return len(s) == 0 || (len(s) == 1 && s[0] == '\n') } +func isBlank(s []byte) bool { return len(s) == 0 || (len(s) == 1 && s[0] == '\n') } func commonPrefix(a, b []byte) []byte { - i := 0; + i := 0 for i < len(a) && i < len(b) && a[i] == b[i] { i++ } - return a[0:i]; + return a[0:i] } @@ -183,13 +183,13 @@ func unindent(block [][]byte) { } // compute maximum common white prefix - prefix := block[0][0:indentLen(block[0])]; + prefix := block[0][0:indentLen(block[0])] for _, line := range block { if !isBlank(line) { prefix = commonPrefix(prefix, line[0:indentLen(line)]) } } - n := len(prefix); + n := len(prefix) // remove for i, line := range block { @@ -212,37 +212,37 @@ func unindent(block [][]byte) { // TODO(rsc): I'd like to pass in an array of variable names []string // and then italicize those strings when they appear as words. func ToHTML(w io.Writer, s []byte) { - inpara := false; + inpara := false close := func() { if inpara { - w.Write(html_endp); - inpara = false; + w.Write(html_endp) + inpara = false } - }; + } open := func() { if !inpara { - w.Write(html_p); - inpara = true; + w.Write(html_p) + inpara = true } - }; + } - lines := split(s); - unindent(lines); + lines := split(s) + unindent(lines) for i := 0; i < len(lines); { - line := lines[i]; + line := lines[i] if isBlank(line) { // close paragraph - close(); - i++; - continue; + close() + i++ + continue } if indentLen(line) > 0 { // close paragraph - close(); + close() // count indented or blank lines - j := i + 1; + j := i + 1 for j < len(lines) && (isBlank(lines[j]) || indentLen(lines[j]) > 0) { j++ } @@ -250,25 +250,25 @@ func ToHTML(w io.Writer, s []byte) { for j > i && isBlank(lines[j-1]) { j-- } - block := lines[i:j]; - i = j; + block := lines[i:j] + i = j - unindent(block); + unindent(block) // put those lines in a pre block. // they don't get the nice text formatting, // just html escaping - w.Write(html_pre); + w.Write(html_pre) for _, line := range block { template.HTMLEscape(w, line) } - w.Write(html_endpre); - continue; + w.Write(html_endpre) + continue } // open paragraph - open(); - commentEscape(w, lines[i]); - i++; + open() + commentEscape(w, lines[i]) + i++ } - close(); + close() } diff --git a/src/pkg/go/doc/doc.go b/src/pkg/go/doc/doc.go index b7cc8f3b0..be03ddfd6 100644 --- a/src/pkg/go/doc/doc.go +++ b/src/pkg/go/doc/doc.go @@ -6,11 +6,11 @@ package doc import ( - "container/vector"; - "go/ast"; - "go/token"; - "regexp"; - "sort"; + "container/vector" + "go/ast" + "go/token" + "regexp" + "sort" ) @@ -19,11 +19,11 @@ import ( type typeDoc struct { // len(decl.Specs) == 1, and the element type is *ast.TypeSpec // if the type declaration hasn't been seen yet, decl is nil - decl *ast.GenDecl; + decl *ast.GenDecl // values, factory functions, and methods associated with the type - values *vector.Vector; // list of *ast.GenDecl (consts and vars) - factories map[string]*ast.FuncDecl; - methods map[string]*ast.FuncDecl; + values *vector.Vector // list of *ast.GenDecl (consts and vars) + factories map[string]*ast.FuncDecl + methods map[string]*ast.FuncDecl } @@ -35,27 +35,27 @@ type typeDoc struct { // printing the corresponding AST node). // type docReader struct { - doc *ast.CommentGroup; // package documentation, if any - pkgName string; - values *vector.Vector; // list of *ast.GenDecl (consts and vars) - types map[string]*typeDoc; - funcs map[string]*ast.FuncDecl; - bugs *vector.Vector; // list of *ast.CommentGroup + doc *ast.CommentGroup // package documentation, if any + pkgName string + values *vector.Vector // list of *ast.GenDecl (consts and vars) + types map[string]*typeDoc + funcs map[string]*ast.FuncDecl + bugs *vector.Vector // list of *ast.CommentGroup } func (doc *docReader) init(pkgName string) { - doc.pkgName = pkgName; - doc.values = new(vector.Vector); - doc.types = make(map[string]*typeDoc); - doc.funcs = make(map[string]*ast.FuncDecl); - doc.bugs = new(vector.Vector); + doc.pkgName = pkgName + doc.values = new(vector.Vector) + doc.types = make(map[string]*typeDoc) + doc.funcs = make(map[string]*ast.FuncDecl) + doc.bugs = new(vector.Vector) } func (doc *docReader) addType(decl *ast.GenDecl) { - spec := decl.Specs[0].(*ast.TypeSpec); - typ := doc.lookupTypeDoc(spec.Name.Value); + spec := decl.Specs[0].(*ast.TypeSpec) + typ := doc.lookupTypeDoc(spec.Name.Value) // typ should always be != nil since declared types // are always named - be conservative and check if typ != nil { @@ -68,15 +68,15 @@ func (doc *docReader) addType(decl *ast.GenDecl) { func (doc *docReader) lookupTypeDoc(name string) *typeDoc { if name == "" { - return nil // no type docs for anonymous types + return nil // no type docs for anonymous types } if tdoc, found := doc.types[name]; found { return tdoc } // type wasn't found - add one without declaration - tdoc := &typeDoc{nil, new(vector.Vector), make(map[string]*ast.FuncDecl), make(map[string]*ast.FuncDecl)}; - doc.types[name] = tdoc; - return tdoc; + tdoc := &typeDoc{nil, new(vector.Vector), make(map[string]*ast.FuncDecl), make(map[string]*ast.FuncDecl)} + doc.types[name] = tdoc + return tdoc } @@ -91,7 +91,7 @@ func baseTypeName(typ ast.Expr) string { case *ast.StarExpr: return baseTypeName(t.X) } - return ""; + return "" } @@ -100,12 +100,12 @@ func (doc *docReader) addValue(decl *ast.GenDecl) { // Heuristic: For each typed entry, determine the type name, if any. // If there is exactly one type name that is sufficiently // frequent, associate the decl with the respective type. - domName := ""; - domFreq := 0; - prev := ""; + domName := "" + domFreq := 0 + prev := "" for _, s := range decl.Specs { if v, ok := s.(*ast.ValueSpec); ok { - name := ""; + name := "" switch { case v.Type != nil: // a type is present; determine it's name @@ -122,38 +122,38 @@ func (doc *docReader) addValue(decl *ast.GenDecl) { if domName != "" && domName != name { // more than one type name - do not associate // with any type - domName = ""; - break; + domName = "" + break } - domName = name; - domFreq++; + domName = name + domFreq++ } - prev = name; + prev = name } } // determine values list - const threshold = 0.75; - values := doc.values; + const threshold = 0.75 + values := doc.values if domName != "" && domFreq >= int(float(len(decl.Specs))*threshold) { // typed entries are sufficiently frequent - typ := doc.lookupTypeDoc(domName); + typ := doc.lookupTypeDoc(domName) if typ != nil { - values = typ.values // associate with that type + values = typ.values // associate with that type } } - values.Push(decl); + values.Push(decl) } func (doc *docReader) addFunc(fun *ast.FuncDecl) { - name := fun.Name.Value; + name := fun.Name.Value // determine if it should be associated with a type if fun.Recv != nil { // method - typ := doc.lookupTypeDoc(baseTypeName(fun.Recv.Type)); + typ := doc.lookupTypeDoc(baseTypeName(fun.Recv.Type)) if typ != nil { // exported receiver type typ.methods[name] = fun @@ -163,19 +163,19 @@ func (doc *docReader) addFunc(fun *ast.FuncDecl) { // that can be called because of exported values (consts, vars, or // function results) of that type. Could determine if that is the // case and then show those methods in an appropriate section. - return; + return } // perhaps a factory function // determine result type, if any if len(fun.Type.Results) >= 1 { - res := fun.Type.Results[0]; + res := fun.Type.Results[0] if len(res.Names) <= 1 { // exactly one (named or anonymous) result associated // with the first type in result signature (there may // be more than one result) - tname := baseTypeName(res.Type); - typ := doc.lookupTypeDoc(tname); + tname := baseTypeName(res.Type) + typ := doc.lookupTypeDoc(tname) if typ != nil { // named and exported result type @@ -187,18 +187,18 @@ func (doc *docReader) addFunc(fun *ast.FuncDecl) { if doc.pkgName == "os" && tname == "Error" && name != "NewError" && name != "NewSyscallError" { // not a factory function for os.Error - doc.funcs[name] = fun; // treat as ordinary function - return; + doc.funcs[name] = fun // treat as ordinary function + return } - typ.factories[name] = fun; - return; + typ.factories[name] = fun + return } } } // ordinary function - doc.funcs[name] = fun; + doc.funcs[name] = fun } @@ -212,7 +212,7 @@ func (doc *docReader) addDecl(decl ast.Decl) { doc.addValue(d) case token.TYPE: // types are handled individually - var noPos token.Position; + var noPos token.Position for _, spec := range d.Specs { // make a (fake) GenDecl node for this TypeSpec // (we need to do this here - as opposed to just @@ -237,17 +237,17 @@ func (doc *docReader) addDecl(decl ast.Decl) { func copyCommentList(list []*ast.Comment) []*ast.Comment { - copy := make([]*ast.Comment, len(list)); + copy := make([]*ast.Comment, len(list)) for i, c := range list { copy[i] = c } - return copy; + return copy } var ( - bug_markers = regexp.MustCompile("^/[/*][ \t]*BUG\\(.*\\):[ \t]*"); // BUG(uid): - bug_content = regexp.MustCompile("[^ \n\r\t]+"); // at least one non-whitespace char + bug_markers = regexp.MustCompile("^/[/*][ \t]*BUG\\(.*\\):[ \t]*") // BUG(uid): + bug_content = regexp.MustCompile("[^ \n\r\t]+") // at least one non-whitespace char ) @@ -262,8 +262,8 @@ func (doc *docReader) addFile(src *ast.File) { // using ast.MergePackageFiles which handles these // comments correctly (but currently looses BUG(...) // comments). - doc.doc = src.Doc; - src.Doc = nil; // doc consumed - remove from ast.File node + doc.doc = src.Doc + src.Doc = nil // doc consumed - remove from ast.File node } // add all declarations @@ -273,41 +273,41 @@ func (doc *docReader) addFile(src *ast.File) { // collect BUG(...) comments for c := src.Comments; c != nil; c = c.Next { - text := c.List[0].Text; - cstr := string(text); + text := c.List[0].Text + cstr := string(text) if m := bug_markers.ExecuteString(cstr); len(m) > 0 { // found a BUG comment; maybe empty if bstr := cstr[m[1]:]; bug_content.MatchString(bstr) { // non-empty BUG comment; collect comment without BUG prefix - list := copyCommentList(c.List); - list[0].Text = text[m[1]:]; - doc.bugs.Push(&ast.CommentGroup{list, nil}); + list := copyCommentList(c.List) + list[0].Text = text[m[1]:] + doc.bugs.Push(&ast.CommentGroup{list, nil}) } } } - src.Comments = nil; // consumed unassociated comments - remove from ast.File node + src.Comments = nil // consumed unassociated comments - remove from ast.File node } func NewFileDoc(file *ast.File) *PackageDoc { - var r docReader; - r.init(file.Name.Value); - r.addFile(file); - return r.newDoc("", "", nil); + var r docReader + r.init(file.Name.Value) + r.addFile(file) + return r.newDoc("", "", nil) } func NewPackageDoc(pkg *ast.Package, importpath string) *PackageDoc { - var r docReader; - r.init(pkg.Name); - filenames := make([]string, len(pkg.Files)); - i := 0; + var r docReader + r.init(pkg.Name) + filenames := make([]string, len(pkg.Files)) + i := 0 for filename, f := range pkg.Files { - r.addFile(f); - filenames[i] = filename; - i++; + r.addFile(f) + filenames[i] = filename + i++ } - return r.newDoc(importpath, pkg.Path, filenames); + return r.newDoc(importpath, pkg.Path, filenames) } @@ -318,15 +318,15 @@ func NewPackageDoc(pkg *ast.Package, importpath string) *PackageDoc { // values, either vars or consts. // type ValueDoc struct { - Doc string; - Decl *ast.GenDecl; - order int; + Doc string + Decl *ast.GenDecl + order int } type sortValueDoc []*ValueDoc -func (p sortValueDoc) Len() int { return len(p) } -func (p sortValueDoc) Swap(i, j int) { p[i], p[j] = p[j], p[i] } +func (p sortValueDoc) Len() int { return len(p) } +func (p sortValueDoc) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func declName(d *ast.GenDecl) string { @@ -341,7 +341,7 @@ func declName(d *ast.GenDecl) string { return v.Name.Value } - return ""; + return "" } @@ -352,24 +352,24 @@ func (p sortValueDoc) Less(i, j int) bool { if ni, nj := declName(p[i].Decl), declName(p[j].Decl); ni != nj { return ni < nj } - return p[i].order < p[j].order; + return p[i].order < p[j].order } func makeValueDocs(v *vector.Vector, tok token.Token) []*ValueDoc { - d := make([]*ValueDoc, v.Len()); // big enough in any case - n := 0; + d := make([]*ValueDoc, v.Len()) // big enough in any case + n := 0 for i := range d { - decl := v.At(i).(*ast.GenDecl); + decl := v.At(i).(*ast.GenDecl) if decl.Tok == tok { - d[n] = &ValueDoc{CommentText(decl.Doc), decl, i}; - n++; - decl.Doc = nil; // doc consumed - removed from AST + d[n] = &ValueDoc{CommentText(decl.Doc), decl, i} + n++ + decl.Doc = nil // doc consumed - removed from AST } } - d = d[0:n]; - sort.Sort(sortValueDoc(d)); - return d; + d = d[0:n] + sort.Sort(sortValueDoc(d)) + return d } @@ -377,36 +377,36 @@ func makeValueDocs(v *vector.Vector, tok token.Token) []*ValueDoc { // either a top-level function or a method function. // type FuncDoc struct { - Doc string; - Recv ast.Expr; // TODO(rsc): Would like string here - Name string; - Decl *ast.FuncDecl; + Doc string + Recv ast.Expr // TODO(rsc): Would like string here + Name string + Decl *ast.FuncDecl } type sortFuncDoc []*FuncDoc -func (p sortFuncDoc) Len() int { return len(p) } -func (p sortFuncDoc) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -func (p sortFuncDoc) Less(i, j int) bool { return p[i].Name < p[j].Name } +func (p sortFuncDoc) Len() int { return len(p) } +func (p sortFuncDoc) Swap(i, j int) { p[i], p[j] = p[j], p[i] } +func (p sortFuncDoc) Less(i, j int) bool { return p[i].Name < p[j].Name } func makeFuncDocs(m map[string]*ast.FuncDecl) []*FuncDoc { - d := make([]*FuncDoc, len(m)); - i := 0; + d := make([]*FuncDoc, len(m)) + i := 0 for _, f := range m { - doc := new(FuncDoc); - doc.Doc = CommentText(f.Doc); - f.Doc = nil; // doc consumed - remove from ast.FuncDecl node + doc := new(FuncDoc) + doc.Doc = CommentText(f.Doc) + f.Doc = nil // doc consumed - remove from ast.FuncDecl node if f.Recv != nil { doc.Recv = f.Recv.Type } - doc.Name = f.Name.Value; - doc.Decl = f; - d[i] = doc; - i++; + doc.Name = f.Name.Value + doc.Decl = f + d[i] = doc + i++ } - sort.Sort(sortFuncDoc(d)); - return d; + sort.Sort(sortFuncDoc(d)) + return d } @@ -415,20 +415,20 @@ func makeFuncDocs(m map[string]*ast.FuncDecl) []*FuncDoc { // Factories is a sorted list of factory functions that return that type. // Methods is a sorted list of method functions on that type. type TypeDoc struct { - Doc string; - Type *ast.TypeSpec; - Consts []*ValueDoc; - Vars []*ValueDoc; - Factories []*FuncDoc; - Methods []*FuncDoc; - Decl *ast.GenDecl; - order int; + Doc string + Type *ast.TypeSpec + Consts []*ValueDoc + Vars []*ValueDoc + Factories []*FuncDoc + Methods []*FuncDoc + Decl *ast.GenDecl + order int } type sortTypeDoc []*TypeDoc -func (p sortTypeDoc) Len() int { return len(p) } -func (p sortTypeDoc) Swap(i, j int) { p[i], p[j] = p[j], p[i] } +func (p sortTypeDoc) Len() int { return len(p) } +func (p sortTypeDoc) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p sortTypeDoc) Less(i, j int) bool { // sort by name // pull blocks (name = "") up to top @@ -436,7 +436,7 @@ func (p sortTypeDoc) Less(i, j int) bool { if ni, nj := p[i].Type.Name.Value, p[j].Type.Name.Value; ni != nj { return ni < nj } - return p[i].order < p[j].order; + return p[i].order < p[j].order } @@ -444,32 +444,32 @@ func (p sortTypeDoc) Less(i, j int) bool { // blocks, but the doc extractor above has split them into // individual declarations. func (doc *docReader) makeTypeDocs(m map[string]*typeDoc) []*TypeDoc { - d := make([]*TypeDoc, len(m)); - i := 0; + d := make([]*TypeDoc, len(m)) + i := 0 for _, old := range m { // all typeDocs should have a declaration associated with // them after processing an entire package - be conservative // and check if decl := old.decl; decl != nil { - typespec := decl.Specs[0].(*ast.TypeSpec); - t := new(TypeDoc); - doc := typespec.Doc; - typespec.Doc = nil; // doc consumed - remove from ast.TypeSpec node + typespec := decl.Specs[0].(*ast.TypeSpec) + t := new(TypeDoc) + doc := typespec.Doc + typespec.Doc = nil // doc consumed - remove from ast.TypeSpec node if doc == nil { // no doc associated with the spec, use the declaration doc, if any doc = decl.Doc } - decl.Doc = nil; // doc consumed - remove from ast.Decl node - t.Doc = CommentText(doc); - t.Type = typespec; - t.Consts = makeValueDocs(old.values, token.CONST); - t.Vars = makeValueDocs(old.values, token.VAR); - t.Factories = makeFuncDocs(old.factories); - t.Methods = makeFuncDocs(old.methods); - t.Decl = old.decl; - t.order = i; - d[i] = t; - i++; + decl.Doc = nil // doc consumed - remove from ast.Decl node + t.Doc = CommentText(doc) + t.Type = typespec + t.Consts = makeValueDocs(old.values, token.CONST) + t.Vars = makeValueDocs(old.values, token.VAR) + t.Factories = makeFuncDocs(old.factories) + t.Methods = makeFuncDocs(old.methods) + t.Decl = old.decl + t.order = i + d[i] = t + i++ } else { // no corresponding type declaration found - move any associated // values, factory functions, and methods back to the top-level @@ -477,7 +477,7 @@ func (doc *docReader) makeTypeDocs(m map[string]*typeDoc) []*TypeDoc { // file containing the explicit type declaration is missing or if // an unqualified type name was used after a "." import) // 1) move values - doc.values.AppendVector(old.values); + doc.values.AppendVector(old.values) // 2) move factory functions for name, f := range old.factories { doc.funcs[name] = f @@ -491,56 +491,56 @@ func (doc *docReader) makeTypeDocs(m map[string]*typeDoc) []*TypeDoc { } } } - d = d[0:i]; // some types may have been ignored - sort.Sort(sortTypeDoc(d)); - return d; + d = d[0:i] // some types may have been ignored + sort.Sort(sortTypeDoc(d)) + return d } func makeBugDocs(v *vector.Vector) []string { - d := make([]string, v.Len()); + d := make([]string, v.Len()) for i := 0; i < v.Len(); i++ { d[i] = CommentText(v.At(i).(*ast.CommentGroup)) } - return d; + return d } // PackageDoc is the documentation for an entire package. // type PackageDoc struct { - PackageName string; - ImportPath string; - FilePath string; - Filenames []string; - Doc string; - Consts []*ValueDoc; - Types []*TypeDoc; - Vars []*ValueDoc; - Funcs []*FuncDoc; - Bugs []string; + PackageName string + ImportPath string + FilePath string + Filenames []string + Doc string + Consts []*ValueDoc + Types []*TypeDoc + Vars []*ValueDoc + Funcs []*FuncDoc + Bugs []string } // newDoc returns the accumulated documentation for the package. // func (doc *docReader) newDoc(importpath, filepath string, filenames []string) *PackageDoc { - p := new(PackageDoc); - p.PackageName = doc.pkgName; - p.ImportPath = importpath; - p.FilePath = filepath; - sort.SortStrings(filenames); - p.Filenames = filenames; - p.Doc = CommentText(doc.doc); + p := new(PackageDoc) + p.PackageName = doc.pkgName + p.ImportPath = importpath + p.FilePath = filepath + sort.SortStrings(filenames) + p.Filenames = filenames + p.Doc = CommentText(doc.doc) // makeTypeDocs may extend the list of doc.values and // doc.funcs and thus must be called before any other // function consuming those lists - p.Types = doc.makeTypeDocs(doc.types); - p.Consts = makeValueDocs(doc.values, token.CONST); - p.Vars = makeValueDocs(doc.values, token.VAR); - p.Funcs = makeFuncDocs(doc.funcs); - p.Bugs = makeBugDocs(doc.bugs); - return p; + p.Types = doc.makeTypeDocs(doc.types) + p.Consts = makeValueDocs(doc.values, token.CONST) + p.Vars = makeValueDocs(doc.values, token.VAR) + p.Funcs = makeFuncDocs(doc.funcs) + p.Bugs = makeBugDocs(doc.bugs) + return p } @@ -549,7 +549,7 @@ func (doc *docReader) newDoc(importpath, filepath string, filenames []string) *P // Does s look like a regular expression? func isRegexp(s string) bool { - metachars := ".(|)*+?^$[]"; + metachars := ".(|)*+?^$[]" for _, c := range s { for _, m := range metachars { if c == m { @@ -557,7 +557,7 @@ func isRegexp(s string) bool { } } } - return false; + return false } @@ -572,7 +572,7 @@ func match(s string, names []string) bool { return true } } - return false; + return false } @@ -591,54 +591,54 @@ func matchDecl(d *ast.GenDecl, names []string) bool { } } } - return false; + return false } func filterValueDocs(a []*ValueDoc, names []string) []*ValueDoc { - w := 0; + w := 0 for _, vd := range a { if matchDecl(vd.Decl, names) { - a[w] = vd; - w++; + a[w] = vd + w++ } } - return a[0:w]; + return a[0:w] } func filterFuncDocs(a []*FuncDoc, names []string) []*FuncDoc { - w := 0; + w := 0 for _, fd := range a { if match(fd.Name, names) { - a[w] = fd; - w++; + a[w] = fd + w++ } } - return a[0:w]; + return a[0:w] } func filterTypeDocs(a []*TypeDoc, names []string) []*TypeDoc { - w := 0; + w := 0 for _, td := range a { - n := 0; // number of matches + n := 0 // number of matches if matchDecl(td.Decl, names) { n = 1 } else { // type name doesn't match, but we may have matching consts, vars, factories or methods - td.Consts = filterValueDocs(td.Consts, names); - td.Vars = filterValueDocs(td.Vars, names); - td.Factories = filterFuncDocs(td.Factories, names); - td.Methods = filterFuncDocs(td.Methods, names); - n += len(td.Consts) + len(td.Vars) + len(td.Factories) + len(td.Methods); + td.Consts = filterValueDocs(td.Consts, names) + td.Vars = filterValueDocs(td.Vars, names) + td.Factories = filterFuncDocs(td.Factories, names) + td.Methods = filterFuncDocs(td.Methods, names) + n += len(td.Consts) + len(td.Vars) + len(td.Factories) + len(td.Methods) } if n > 0 { - a[w] = td; - w++; + a[w] = td + w++ } } - return a[0:w]; + return a[0:w] } @@ -648,9 +648,9 @@ func filterTypeDocs(a []*TypeDoc, names []string) []*TypeDoc { // TODO(r): maybe precompile the regexps. // func (p *PackageDoc) Filter(names []string) { - p.Consts = filterValueDocs(p.Consts, names); - p.Vars = filterValueDocs(p.Vars, names); - p.Types = filterTypeDocs(p.Types, names); - p.Funcs = filterFuncDocs(p.Funcs, names); - p.Doc = ""; // don't show top-level package doc + p.Consts = filterValueDocs(p.Consts, names) + p.Vars = filterValueDocs(p.Vars, names) + p.Types = filterTypeDocs(p.Types, names) + p.Funcs = filterFuncDocs(p.Funcs, names) + p.Doc = "" // don't show top-level package doc } diff --git a/src/pkg/go/parser/interface.go b/src/pkg/go/parser/interface.go index 7e8f5d25e..b6fe4441e 100644 --- a/src/pkg/go/parser/interface.go +++ b/src/pkg/go/parser/interface.go @@ -7,15 +7,15 @@ package parser import ( - "bytes"; - "fmt"; - "go/ast"; - "go/scanner"; - "io"; - "io/ioutil"; - "os"; - pathutil "path"; - "strings"; + "bytes" + "fmt" + "go/ast" + "go/scanner" + "io" + "io/ioutil" + "os" + pathutil "path" + "strings" ) @@ -36,18 +36,18 @@ func readSource(filename string, src interface{}) ([]byte, os.Error) { return s.Bytes(), nil } case io.Reader: - var buf bytes.Buffer; - _, err := io.Copy(&buf, s); + var buf bytes.Buffer + _, err := io.Copy(&buf, s) if err != nil { return nil, err } - return buf.Bytes(), nil; + return buf.Bytes(), nil default: return nil, os.ErrorString("invalid source") } } - return ioutil.ReadFile(filename); + return ioutil.ReadFile(filename) } @@ -57,14 +57,14 @@ func readSource(filename string, src interface{}) ([]byte, os.Error) { // may be nil or contain a partial AST. // func ParseExpr(filename string, src interface{}) (ast.Expr, os.Error) { - data, err := readSource(filename, src); + data, err := readSource(filename, src) if err != nil { return nil, err } - var p parser; - p.init(filename, data, 0); - return p.parseExpr(), p.GetError(scanner.Sorted); + var p parser + p.init(filename, data, 0) + return p.parseExpr(), p.GetError(scanner.Sorted) } @@ -74,14 +74,14 @@ func ParseExpr(filename string, src interface{}) (ast.Expr, os.Error) { // list may be nil or contain partial ASTs. // func ParseStmtList(filename string, src interface{}) ([]ast.Stmt, os.Error) { - data, err := readSource(filename, src); + data, err := readSource(filename, src) if err != nil { return nil, err } - var p parser; - p.init(filename, data, 0); - return p.parseStmtList(), p.GetError(scanner.Sorted); + var p parser + p.init(filename, data, 0) + return p.parseStmtList(), p.GetError(scanner.Sorted) } @@ -91,14 +91,14 @@ func ParseStmtList(filename string, src interface{}) ([]ast.Stmt, os.Error) { // list may be nil or contain partial ASTs. // func ParseDeclList(filename string, src interface{}) ([]ast.Decl, os.Error) { - data, err := readSource(filename, src); + data, err := readSource(filename, src) if err != nil { return nil, err } - var p parser; - p.init(filename, data, 0); - return p.parseDeclList(), p.GetError(scanner.Sorted); + var p parser + p.init(filename, data, 0) + return p.parseDeclList(), p.GetError(scanner.Sorted) } @@ -121,14 +121,14 @@ func ParseDeclList(filename string, src interface{}) ([]ast.Decl, os.Error) { // are returned via a scanner.ErrorList which is sorted by file position. // func ParseFile(filename string, src interface{}, mode uint) (*ast.File, os.Error) { - data, err := readSource(filename, src); + data, err := readSource(filename, src) if err != nil { return nil, err } - var p parser; - p.init(filename, data, mode); - return p.parseFile(), p.GetError(scanner.NoMultiples); + var p parser + p.init(filename, data, mode) + return p.parseFile(), p.GetError(scanner.NoMultiples) } @@ -139,13 +139,13 @@ func ParseFile(filename string, src interface{}, mode uint) (*ast.File, os.Error // flags that control the amount of source text parsed are ignored. // func ParsePkgFile(pkgname, filename string, mode uint) (*ast.File, os.Error) { - src, err := ioutil.ReadFile(filename); + src, err := ioutil.ReadFile(filename) if err != nil { return nil, err } if pkgname != "" { - prog, err := ParseFile(filename, src, PackageClauseOnly); + prog, err := ParseFile(filename, src, PackageClauseOnly) if err != nil { return nil, err } @@ -155,7 +155,7 @@ func ParsePkgFile(pkgname, filename string, mode uint) (*ast.File, os.Error) { } // ignore flags that control partial parsing - return ParseFile(filename, src, mode&^(PackageClauseOnly|ImportsOnly)); + return ParseFile(filename, src, mode&^(PackageClauseOnly|ImportsOnly)) } @@ -167,27 +167,27 @@ func ParsePkgFile(pkgname, filename string, mode uint) (*ast.File, os.Error) { // Mode flags that control the amount of source text parsed are ignored. // func ParsePackage(path string, filter func(*os.Dir) bool, mode uint) (*ast.Package, os.Error) { - fd, err := os.Open(path, os.O_RDONLY, 0); + fd, err := os.Open(path, os.O_RDONLY, 0) if err != nil { return nil, err } - defer fd.Close(); + defer fd.Close() - list, err := fd.Readdir(-1); + list, err := fd.Readdir(-1) if err != nil { return nil, err } - name := ""; - files := make(map[string]*ast.File); + name := "" + files := make(map[string]*ast.File) for i := 0; i < len(list); i++ { - entry := &list[i]; + entry := &list[i] if filter == nil || filter(entry) { - src, err := ParsePkgFile(name, pathutil.Join(path, entry.Name), mode); + src, err := ParsePkgFile(name, pathutil.Join(path, entry.Name), mode) if err != nil { return nil, err } - files[entry.Name] = src; + files[entry.Name] = src if name == "" { name = src.Name.Value } @@ -198,5 +198,5 @@ func ParsePackage(path string, filter func(*os.Dir) bool, mode uint) (*ast.Packa return nil, os.NewError(path + ": no package found") } - return &ast.Package{name, path, files}, nil; + return &ast.Package{name, path, files}, nil } diff --git a/src/pkg/go/parser/parser.go b/src/pkg/go/parser/parser.go index fa6fb545e..bd7ca158e 100644 --- a/src/pkg/go/parser/parser.go +++ b/src/pkg/go/parser/parser.go @@ -10,11 +10,11 @@ package parser import ( - "container/vector"; - "fmt"; - "go/ast"; - "go/scanner"; - "go/token"; + "container/vector" + "fmt" + "go/ast" + "go/scanner" + "go/token" ) @@ -27,59 +27,59 @@ var noPos token.Position // parser functionality. // const ( - PackageClauseOnly uint = 1 << iota; // parsing stops after package clause - ImportsOnly; // parsing stops after import declarations - ParseComments; // parse comments and add them to AST - Trace; // print a trace of parsed productions + PackageClauseOnly uint = 1 << iota // parsing stops after package clause + ImportsOnly // parsing stops after import declarations + ParseComments // parse comments and add them to AST + Trace // print a trace of parsed productions ) // The parser structure holds the parser's internal state. type parser struct { - scanner.ErrorVector; - scanner scanner.Scanner; + scanner.ErrorVector + scanner scanner.Scanner // Tracing/debugging - mode uint; // parsing mode - trace bool; // == (mode & Trace != 0) - indent uint; // indentation used for tracing output + mode uint // parsing mode + trace bool // == (mode & Trace != 0) + indent uint // indentation used for tracing output // Comments - comments *ast.CommentGroup; // list of collected comments - lastComment *ast.CommentGroup; // last comment in the comments list - leadComment *ast.CommentGroup; // the last lead comment - lineComment *ast.CommentGroup; // the last line comment + comments *ast.CommentGroup // list of collected comments + lastComment *ast.CommentGroup // last comment in the comments list + leadComment *ast.CommentGroup // the last lead comment + lineComment *ast.CommentGroup // the last line comment // Next token - pos token.Position; // token position - tok token.Token; // one token look-ahead - lit []byte; // token literal + pos token.Position // token position + tok token.Token // one token look-ahead + lit []byte // token literal // Non-syntactic parser control - exprLev int; // < 0: in control clause, >= 0: in expression + exprLev int // < 0: in control clause, >= 0: in expression // Scopes - pkgScope *ast.Scope; - fileScope *ast.Scope; - topScope *ast.Scope; + pkgScope *ast.Scope + fileScope *ast.Scope + topScope *ast.Scope } // scannerMode returns the scanner mode bits given the parser's mode bits. func scannerMode(mode uint) uint { - var m uint = scanner.InsertSemis; + var m uint = scanner.InsertSemis if mode&ParseComments != 0 { m |= scanner.ScanComments } - return m; + return m } func (p *parser) init(filename string, src []byte, mode uint) { - p.scanner.Init(filename, src, p, scannerMode(mode)); - p.mode = mode; - p.trace = mode&Trace != 0; // for convenience (p.trace is used frequently) - p.next(); + p.scanner.Init(filename, src, p, scannerMode(mode)) + p.mode = mode + p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently) + p.next() } @@ -88,29 +88,29 @@ func (p *parser) init(filename string, src []byte, mode uint) { func (p *parser) printTrace(a ...) { const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " + - ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "; - const n = uint(len(dots)); - fmt.Printf("%5d:%3d: ", p.pos.Line, p.pos.Column); - i := 2 * p.indent; + ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " + const n = uint(len(dots)) + fmt.Printf("%5d:%3d: ", p.pos.Line, p.pos.Column) + i := 2 * p.indent for ; i > n; i -= n { fmt.Print(dots) } - fmt.Print(dots[0:i]); - fmt.Println(a); + fmt.Print(dots[0:i]) + fmt.Println(a) } func trace(p *parser, msg string) *parser { - p.printTrace(msg, "("); - p.indent++; - return p; + p.printTrace(msg, "(") + p.indent++ + return p } // Usage pattern: defer un(trace(p, "...")); func un(p *parser) { - p.indent--; - p.printTrace(")"); + p.indent-- + p.printTrace(")") } @@ -121,7 +121,7 @@ func (p *parser) next0() { // very first token (p.pos.Line == 0) is not initialized (it // is token.ILLEGAL), so don't print it . if p.trace && p.pos.Line > 0 { - s := p.tok.String(); + s := p.tok.String() switch { case p.tok.IsLiteral(): p.printTrace(s, string(p.lit)) @@ -132,14 +132,14 @@ func (p *parser) next0() { } } - p.pos, p.tok, p.lit = p.scanner.Scan(); + p.pos, p.tok, p.lit = p.scanner.Scan() } // Consume a comment and return it and the line on which it ends. func (p *parser) consumeComment() (comment *ast.Comment, endline int) { // /*-style comments may end on a different line than where they start. // Scan the comment for '\n' chars and adjust endline accordingly. - endline = p.pos.Line; + endline = p.pos.Line if p.lit[1] == '*' { for _, b := range p.lit { if b == '\n' { @@ -148,10 +148,10 @@ func (p *parser) consumeComment() (comment *ast.Comment, endline int) { } } - comment = &ast.Comment{p.pos, p.lit}; - p.next0(); + comment = &ast.Comment{p.pos, p.lit} + p.next0() - return; + return } @@ -161,30 +161,30 @@ func (p *parser) consumeComment() (comment *ast.Comment, endline int) { // a comment group. // func (p *parser) consumeCommentGroup() int { - var list vector.Vector; - endline := p.pos.Line; + var list vector.Vector + endline := p.pos.Line for p.tok == token.COMMENT && endline+1 >= p.pos.Line { - var comment *ast.Comment; - comment, endline = p.consumeComment(); - list.Push(comment); + var comment *ast.Comment + comment, endline = p.consumeComment() + list.Push(comment) } // convert list - group := make([]*ast.Comment, list.Len()); + group := make([]*ast.Comment, list.Len()) for i := 0; i < list.Len(); i++ { group[i] = list.At(i).(*ast.Comment) } // add comment group to the comments list - g := &ast.CommentGroup{group, nil}; + g := &ast.CommentGroup{group, nil} if p.lastComment != nil { p.lastComment.Next = g } else { p.comments = g } - p.lastComment = g; + p.lastComment = g - return endline; + return endline } @@ -204,16 +204,16 @@ func (p *parser) consumeCommentGroup() int { // stored in the AST. // func (p *parser) next() { - p.leadComment = nil; - p.lineComment = nil; - line := p.pos.Line; // current line - p.next0(); + p.leadComment = nil + p.lineComment = nil + line := p.pos.Line // current line + p.next0() if p.tok == token.COMMENT { if p.pos.Line == line { // The comment is on same line as previous token; it // cannot be a lead comment but may be a line comment. - endline := p.consumeCommentGroup(); + endline := p.consumeCommentGroup() if p.pos.Line != endline { // The next token is on a different line, thus // the last comment group is a line comment. @@ -222,7 +222,7 @@ func (p *parser) next() { } // consume successor comments, if any - endline := -1; + endline := -1 for p.tok == token.COMMENT { endline = p.consumeCommentGroup() } @@ -237,26 +237,26 @@ func (p *parser) next() { func (p *parser) 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 *parser) 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 } @@ -271,13 +271,13 @@ func (p *parser) expectSemi() { // Scope support func openScope(p *parser) *parser { - p.topScope = ast.NewScope(p.topScope); - return p; + p.topScope = ast.NewScope(p.topScope) + return p } // Usage pattern: defer close(openScope(p)); -func close(p *parser) { p.topScope = p.topScope.Outer } +func close(p *parser) { p.topScope = p.topScope.Outer } func (p *parser) declare(ident *ast.Ident) { @@ -299,12 +299,12 @@ func (p *parser) declareList(idents []*ast.Ident) { func (p *parser) parseIdent() *ast.Ident { if p.tok == token.IDENT { - x := &ast.Ident{p.pos, string(p.lit)}; - p.next(); - return x; + x := &ast.Ident{p.pos, string(p.lit)} + p.next() + return x } - p.expect(token.IDENT); // use expect() error handling - return &ast.Ident{p.pos, ""}; + p.expect(token.IDENT) // use expect() error handling + return &ast.Ident{p.pos, ""} } @@ -313,29 +313,29 @@ func (p *parser) parseIdentList() []*ast.Ident { defer un(trace(p, "IdentList")) } - var list vector.Vector; - list.Push(p.parseIdent()); + var list vector.Vector + list.Push(p.parseIdent()) for p.tok == token.COMMA { - p.next(); - list.Push(p.parseIdent()); + p.next() + list.Push(p.parseIdent()) } // convert vector - idents := make([]*ast.Ident, list.Len()); + idents := make([]*ast.Ident, list.Len()) for i := 0; i < list.Len(); i++ { idents[i] = list.At(i).(*ast.Ident) } - return idents; + return idents } func makeExprList(list *vector.Vector) []ast.Expr { - exprs := make([]ast.Expr, list.Len()); + exprs := make([]ast.Expr, list.Len()) for i := 0; i < list.Len(); i++ { exprs[i] = list.At(i).(ast.Expr) } - return exprs; + return exprs } @@ -344,14 +344,14 @@ func (p *parser) parseExprList() []ast.Expr { defer un(trace(p, "ExpressionList")) } - var list vector.Vector; - list.Push(p.parseExpr()); + var list vector.Vector + list.Push(p.parseExpr()) for p.tok == token.COMMA { - p.next(); - list.Push(p.parseExpr()); + p.next() + list.Push(p.parseExpr()) } - return makeExprList(&list); + return makeExprList(&list) } @@ -363,15 +363,15 @@ func (p *parser) parseType() ast.Expr { defer un(trace(p, "Type")) } - typ := p.tryType(); + typ := p.tryType() if typ == nil { - p.errorExpected(p.pos, "type"); - p.next(); // make progress - return &ast.BadExpr{p.pos}; + p.errorExpected(p.pos, "type") + p.next() // make progress + return &ast.BadExpr{p.pos} } - return typ; + return typ } @@ -380,14 +380,14 @@ func (p *parser) parseQualifiedIdent() ast.Expr { defer un(trace(p, "QualifiedIdent")) } - var x ast.Expr = p.parseIdent(); + var x ast.Expr = p.parseIdent() if p.tok == token.PERIOD { // first identifier is a package identifier - p.next(); - sel := p.parseIdent(); - x = &ast.SelectorExpr{x, sel}; + p.next() + sel := p.parseIdent() + x = &ast.SelectorExpr{x, sel} } - return x; + return x } @@ -396,7 +396,7 @@ func (p *parser) parseTypeName() ast.Expr { defer un(trace(p, "TypeName")) } - return p.parseQualifiedIdent(); + return p.parseQualifiedIdent() } @@ -405,33 +405,33 @@ func (p *parser) parseArrayType(ellipsisOk bool) ast.Expr { defer un(trace(p, "ArrayType")) } - lbrack := p.expect(token.LBRACK); - var len ast.Expr; + lbrack := p.expect(token.LBRACK) + var len ast.Expr if ellipsisOk && p.tok == token.ELLIPSIS { - len = &ast.Ellipsis{p.pos}; - p.next(); + len = &ast.Ellipsis{p.pos} + p.next() } else if p.tok != token.RBRACK { len = p.parseExpr() } - p.expect(token.RBRACK); - elt := p.parseType(); + p.expect(token.RBRACK) + elt := p.parseType() - return &ast.ArrayType{lbrack, len, elt}; + return &ast.ArrayType{lbrack, len, elt} } func (p *parser) makeIdentList(list *vector.Vector) []*ast.Ident { - idents := make([]*ast.Ident, list.Len()); + idents := make([]*ast.Ident, list.Len()) for i := 0; i < list.Len(); i++ { - ident, isIdent := list.At(i).(*ast.Ident); + ident, isIdent := list.At(i).(*ast.Ident) if !isIdent { - pos := list.At(i).(ast.Expr).Pos(); - p.errorExpected(pos, "identifier"); - idents[i] = &ast.Ident{pos, ""}; + pos := list.At(i).(ast.Expr).Pos() + p.errorExpected(pos, "identifier") + idents[i] = &ast.Ident{pos, ""} } - idents[i] = ident; + idents[i] = ident } - return idents; + return idents } @@ -440,32 +440,32 @@ func (p *parser) parseFieldDecl() *ast.Field { defer un(trace(p, "FieldDecl")) } - doc := p.leadComment; + doc := p.leadComment // a list of identifiers looks like a list of type names - var list vector.Vector; + var list vector.Vector for { // TODO(gri): do not allow ()'s here - list.Push(p.parseType()); + list.Push(p.parseType()) if p.tok != token.COMMA { break } - p.next(); + p.next() } // if we had a list of identifiers, it must be followed by a type - typ := p.tryType(); + typ := p.tryType() // optional tag - var tag []*ast.BasicLit; + var tag []*ast.BasicLit if p.tok == token.STRING { - x := &ast.BasicLit{p.pos, p.tok, p.lit}; - p.next(); - tag = []*ast.BasicLit{x}; + x := &ast.BasicLit{p.pos, p.tok, p.lit} + p.next() + tag = []*ast.BasicLit{x} } // analyze case - var idents []*ast.Ident; + var idents []*ast.Ident if typ != nil { // IdentifierList Type idents = p.makeIdentList(&list) @@ -475,14 +475,14 @@ func (p *parser) parseFieldDecl() *ast.Field { // TODO(gri): check that this looks like a type typ = list.At(0).(ast.Expr) } else { - p.errorExpected(p.pos, "anonymous field"); - typ = &ast.BadExpr{p.pos}; + p.errorExpected(p.pos, "anonymous field") + typ = &ast.BadExpr{p.pos} } } - p.expectSemi(); + p.expectSemi() - return &ast.Field{doc, idents, typ, tag, p.lineComment}; + return &ast.Field{doc, idents, typ, tag, p.lineComment} } @@ -491,21 +491,21 @@ func (p *parser) parseStructType() *ast.StructType { defer un(trace(p, "StructType")) } - pos := p.expect(token.STRUCT); - lbrace := p.expect(token.LBRACE); - var list vector.Vector; + pos := p.expect(token.STRUCT) + lbrace := p.expect(token.LBRACE) + var list vector.Vector for p.tok == token.IDENT || p.tok == token.MUL { list.Push(p.parseFieldDecl()) } - rbrace := p.expect(token.RBRACE); + rbrace := p.expect(token.RBRACE) // convert vector - fields := make([]*ast.Field, list.Len()); + fields := make([]*ast.Field, list.Len()) for i := list.Len() - 1; i >= 0; i-- { fields[i] = list.At(i).(*ast.Field) } - return &ast.StructType{pos, lbrace, fields, rbrace, false}; + return &ast.StructType{pos, lbrace, fields, rbrace, false} } @@ -514,35 +514,35 @@ func (p *parser) parsePointerType() *ast.StarExpr { defer un(trace(p, "PointerType")) } - star := p.expect(token.MUL); - base := p.parseType(); + star := p.expect(token.MUL) + base := p.parseType() - return &ast.StarExpr{star, base}; + return &ast.StarExpr{star, base} } func (p *parser) tryParameterType(ellipsisOk bool) ast.Expr { if ellipsisOk && p.tok == token.ELLIPSIS { - pos := p.pos; - p.next(); + pos := p.pos + p.next() if p.tok != token.RPAREN { // "..." always must be at the very end of a parameter list p.Error(pos, "expected type, found '...'") } - return &ast.Ellipsis{pos}; + return &ast.Ellipsis{pos} } - return p.tryType(); + return p.tryType() } func (p *parser) parseParameterType(ellipsisOk bool) ast.Expr { - typ := p.tryParameterType(ellipsisOk); + typ := p.tryParameterType(ellipsisOk) if typ == nil { - p.errorExpected(p.pos, "type"); - p.next(); // make progress - typ = &ast.BadExpr{p.pos}; + p.errorExpected(p.pos, "type") + p.next() // make progress + typ = &ast.BadExpr{p.pos} } - return typ; + return typ } @@ -552,20 +552,20 @@ func (p *parser) parseParameterDecl(ellipsisOk bool) (*vector.Vector, ast.Expr) } // a list of identifiers looks like a list of type names - var list vector.Vector; + var list vector.Vector for { // TODO(gri): do not allow ()'s here - list.Push(p.parseParameterType(ellipsisOk)); + list.Push(p.parseParameterType(ellipsisOk)) if p.tok != token.COMMA { break } - p.next(); + p.next() } // if we had a list of identifiers, it must be followed by a type - typ := p.tryParameterType(ellipsisOk); + typ := p.tryParameterType(ellipsisOk) - return &list, typ; + return &list, typ } @@ -574,24 +574,24 @@ func (p *parser) parseParameterList(ellipsisOk bool) []*ast.Field { defer un(trace(p, "ParameterList")) } - list, typ := p.parseParameterDecl(ellipsisOk); + list, typ := p.parseParameterDecl(ellipsisOk) if typ != nil { // IdentifierList Type - idents := p.makeIdentList(list); - list.Resize(0, 0); - list.Push(&ast.Field{nil, idents, typ, nil, nil}); + idents := p.makeIdentList(list) + list.Resize(0, 0) + list.Push(&ast.Field{nil, idents, typ, nil, nil}) if p.tok == token.COMMA { p.next() } for p.tok != token.RPAREN && p.tok != token.EOF { - idents := p.parseIdentList(); - typ := p.parseParameterType(ellipsisOk); - list.Push(&ast.Field{nil, idents, typ, nil, nil}); + idents := p.parseIdentList() + typ := p.parseParameterType(ellipsisOk) + list.Push(&ast.Field{nil, idents, typ, nil, nil}) if p.tok != token.COMMA { break } - p.next(); + p.next() } } else { @@ -603,12 +603,12 @@ func (p *parser) parseParameterList(ellipsisOk bool) []*ast.Field { } // convert list - params := make([]*ast.Field, list.Len()); + params := make([]*ast.Field, list.Len()) for i := 0; i < list.Len(); i++ { params[i] = list.At(i).(*ast.Field) } - return params; + return params } @@ -617,14 +617,14 @@ func (p *parser) parseParameters(ellipsisOk bool) []*ast.Field { defer un(trace(p, "Parameters")) } - var params []*ast.Field; - p.expect(token.LPAREN); + var params []*ast.Field + p.expect(token.LPAREN) if p.tok != token.RPAREN { params = p.parseParameterList(ellipsisOk) } - p.expect(token.RPAREN); + p.expect(token.RPAREN) - return params; + return params } @@ -633,18 +633,18 @@ func (p *parser) parseResult() []*ast.Field { defer un(trace(p, "Result")) } - var results []*ast.Field; + var results []*ast.Field if p.tok == token.LPAREN { results = p.parseParameters(false) } else if p.tok != token.FUNC { - typ := p.tryType(); + typ := p.tryType() if typ != nil { - results = make([]*ast.Field, 1); - results[0] = &ast.Field{Type: typ}; + results = make([]*ast.Field, 1) + results[0] = &ast.Field{Type: typ} } } - return results; + return results } @@ -653,10 +653,10 @@ func (p *parser) parseSignature() (params []*ast.Field, results []*ast.Field) { defer un(trace(p, "Signature")) } - params = p.parseParameters(true); - results = p.parseResult(); + params = p.parseParameters(true) + results = p.parseResult() - return; + return } @@ -665,10 +665,10 @@ func (p *parser) parseFuncType() *ast.FuncType { defer un(trace(p, "FuncType")) } - pos := p.expect(token.FUNC); - params, results := p.parseSignature(); + pos := p.expect(token.FUNC) + params, results := p.parseSignature() - return &ast.FuncType{pos, params, results}; + return &ast.FuncType{pos, params, results} } @@ -677,22 +677,22 @@ func (p *parser) parseMethodSpec() *ast.Field { defer un(trace(p, "MethodSpec")) } - doc := p.leadComment; - var idents []*ast.Ident; - var typ ast.Expr; - x := p.parseQualifiedIdent(); + doc := p.leadComment + var idents []*ast.Ident + var typ ast.Expr + x := p.parseQualifiedIdent() if ident, isIdent := x.(*ast.Ident); isIdent && p.tok == token.LPAREN { // method - idents = []*ast.Ident{ident}; - params, results := p.parseSignature(); - typ = &ast.FuncType{noPos, params, results}; + idents = []*ast.Ident{ident} + params, results := p.parseSignature() + typ = &ast.FuncType{noPos, params, results} } else { // embedded interface typ = x } - p.expectSemi(); + p.expectSemi() - return &ast.Field{doc, idents, typ, nil, p.lineComment}; + return &ast.Field{doc, idents, typ, nil, p.lineComment} } @@ -701,21 +701,21 @@ func (p *parser) parseInterfaceType() *ast.InterfaceType { defer un(trace(p, "InterfaceType")) } - pos := p.expect(token.INTERFACE); - lbrace := p.expect(token.LBRACE); - var list vector.Vector; + pos := p.expect(token.INTERFACE) + lbrace := p.expect(token.LBRACE) + var list vector.Vector for p.tok == token.IDENT { list.Push(p.parseMethodSpec()) } - rbrace := p.expect(token.RBRACE); + rbrace := p.expect(token.RBRACE) // convert vector - methods := make([]*ast.Field, list.Len()); + methods := make([]*ast.Field, list.Len()) for i := list.Len() - 1; i >= 0; i-- { methods[i] = list.At(i).(*ast.Field) } - return &ast.InterfaceType{pos, lbrace, methods, rbrace, false}; + return &ast.InterfaceType{pos, lbrace, methods, rbrace, false} } @@ -724,13 +724,13 @@ func (p *parser) parseMapType() *ast.MapType { defer un(trace(p, "MapType")) } - pos := p.expect(token.MAP); - p.expect(token.LBRACK); - key := p.parseType(); - p.expect(token.RBRACK); - value := p.parseType(); + pos := p.expect(token.MAP) + p.expect(token.LBRACK) + key := p.parseType() + p.expect(token.RBRACK) + value := p.parseType() - return &ast.MapType{pos, key, value}; + return &ast.MapType{pos, key, value} } @@ -739,22 +739,22 @@ func (p *parser) parseChanType() *ast.ChanType { defer un(trace(p, "ChanType")) } - pos := p.pos; - dir := ast.SEND | ast.RECV; + pos := p.pos + dir := ast.SEND | ast.RECV if p.tok == token.CHAN { - p.next(); + p.next() if p.tok == token.ARROW { - p.next(); - dir = ast.SEND; + p.next() + dir = ast.SEND } } else { - p.expect(token.ARROW); - p.expect(token.CHAN); - dir = ast.RECV; + p.expect(token.ARROW) + p.expect(token.CHAN) + dir = ast.RECV } - value := p.parseType(); + value := p.parseType() - return &ast.ChanType{pos, dir, value}; + return &ast.ChanType{pos, dir, value} } @@ -777,30 +777,30 @@ func (p *parser) tryRawType(ellipsisOk bool) ast.Expr { case token.CHAN, token.ARROW: return p.parseChanType() case token.LPAREN: - lparen := p.pos; - p.next(); - typ := p.parseType(); - rparen := p.expect(token.RPAREN); - return &ast.ParenExpr{lparen, typ, rparen}; + lparen := p.pos + p.next() + typ := p.parseType() + rparen := p.expect(token.RPAREN) + return &ast.ParenExpr{lparen, typ, rparen} } // no type found - return nil; + return nil } -func (p *parser) tryType() ast.Expr { return p.tryRawType(false) } +func (p *parser) tryType() ast.Expr { return p.tryRawType(false) } // ---------------------------------------------------------------------------- // Blocks func makeStmtList(list *vector.Vector) []ast.Stmt { - stats := make([]ast.Stmt, list.Len()); + stats := make([]ast.Stmt, list.Len()) for i := 0; i < list.Len(); i++ { stats[i] = list.At(i).(ast.Stmt) } - return stats; + return stats } @@ -809,12 +809,12 @@ func (p *parser) parseStmtList() []ast.Stmt { defer un(trace(p, "StatementList")) } - var list vector.Vector; + var list vector.Vector for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF { list.Push(p.parseStmt()) } - return makeStmtList(&list); + return makeStmtList(&list) } @@ -823,13 +823,13 @@ func (p *parser) parseBlockStmt() *ast.BlockStmt { defer un(trace(p, "BlockStmt")) } - defer close(openScope(p)); + defer close(openScope(p)) - lbrace := p.expect(token.LBRACE); - list := p.parseStmtList(); - rbrace := p.expect(token.RBRACE); + lbrace := p.expect(token.LBRACE) + list := p.parseStmtList() + rbrace := p.expect(token.RBRACE) - return &ast.BlockStmt{lbrace, list, rbrace}; + return &ast.BlockStmt{lbrace, list, rbrace} } @@ -841,17 +841,17 @@ func (p *parser) parseFuncTypeOrLit() ast.Expr { defer un(trace(p, "FuncTypeOrLit")) } - typ := p.parseFuncType(); + typ := p.parseFuncType() if p.tok != token.LBRACE { // function type only return typ } - p.exprLev++; - body := p.parseBlockStmt(); - p.exprLev--; + p.exprLev++ + body := p.parseBlockStmt() + p.exprLev-- - return &ast.FuncLit{typ, body}; + return &ast.FuncLit{typ, body} } @@ -868,32 +868,32 @@ func (p *parser) parseOperand() ast.Expr { return p.parseIdent() case token.INT, token.FLOAT, token.CHAR, token.STRING: - x := &ast.BasicLit{p.pos, p.tok, p.lit}; - p.next(); - return x; + x := &ast.BasicLit{p.pos, p.tok, p.lit} + p.next() + return x case token.LPAREN: - lparen := p.pos; - p.next(); - p.exprLev++; - x := p.parseExpr(); - p.exprLev--; - rparen := p.expect(token.RPAREN); - return &ast.ParenExpr{lparen, x, rparen}; + lparen := p.pos + p.next() + p.exprLev++ + x := p.parseExpr() + p.exprLev-- + rparen := p.expect(token.RPAREN) + return &ast.ParenExpr{lparen, x, rparen} case token.FUNC: return p.parseFuncTypeOrLit() default: - t := p.tryRawType(true); // could be type for composite literal or conversion + t := p.tryRawType(true) // could be type for composite literal or conversion if t != nil { return t } } - p.errorExpected(p.pos, "operand"); - p.next(); // make progress - return &ast.BadExpr{p.pos}; + p.errorExpected(p.pos, "operand") + p.next() // make progress + return &ast.BadExpr{p.pos} } @@ -902,25 +902,25 @@ func (p *parser) parseSelectorOrTypeAssertion(x ast.Expr) ast.Expr { defer un(trace(p, "SelectorOrTypeAssertion")) } - p.expect(token.PERIOD); + p.expect(token.PERIOD) if p.tok == token.IDENT { // selector - sel := p.parseIdent(); - return &ast.SelectorExpr{x, sel}; + sel := p.parseIdent() + return &ast.SelectorExpr{x, sel} } // type assertion - p.expect(token.LPAREN); - var typ ast.Expr; + p.expect(token.LPAREN) + var typ ast.Expr if p.tok == token.TYPE { // type switch: typ == nil p.next() } else { typ = p.parseType() } - p.expect(token.RPAREN); + p.expect(token.RPAREN) - return &ast.TypeAssertExpr{x, typ}; + return &ast.TypeAssertExpr{x, typ} } @@ -929,23 +929,23 @@ func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr { defer un(trace(p, "IndexOrSlice")) } - p.expect(token.LBRACK); - p.exprLev++; - index := p.parseExpr(); + p.expect(token.LBRACK) + p.exprLev++ + index := p.parseExpr() if p.tok == token.COLON { - p.next(); - var end ast.Expr; + p.next() + var end ast.Expr if p.tok != token.RBRACK { end = p.parseExpr() } - x = &ast.SliceExpr{x, index, end}; + x = &ast.SliceExpr{x, index, end} } else { x = &ast.IndexExpr{x, index} } - p.exprLev--; - p.expect(token.RBRACK); + p.exprLev-- + p.expect(token.RBRACK) - return x; + return x } @@ -954,20 +954,20 @@ func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr { defer un(trace(p, "CallOrConversion")) } - lparen := p.expect(token.LPAREN); - p.exprLev++; - var list vector.Vector; + lparen := p.expect(token.LPAREN) + p.exprLev++ + var list vector.Vector for p.tok != token.RPAREN && p.tok != token.EOF { - list.Push(p.parseExpr()); + list.Push(p.parseExpr()) if p.tok != token.COMMA { break } - p.next(); + p.next() } - p.exprLev--; - rparen := p.expect(token.RPAREN); + p.exprLev-- + rparen := p.expect(token.RPAREN) - return &ast.CallExpr{fun, lparen, makeExprList(&list), rparen}; + return &ast.CallExpr{fun, lparen, makeExprList(&list), rparen} } @@ -976,14 +976,14 @@ func (p *parser) parseElement() ast.Expr { defer un(trace(p, "Element")) } - x := p.parseExpr(); + x := p.parseExpr() if p.tok == token.COLON { - colon := p.pos; - p.next(); - x = &ast.KeyValueExpr{x, colon, p.parseExpr()}; + colon := p.pos + p.next() + x = &ast.KeyValueExpr{x, colon, p.parseExpr()} } - return x; + return x } @@ -992,16 +992,16 @@ func (p *parser) parseElementList() []ast.Expr { defer un(trace(p, "ElementList")) } - var list vector.Vector; + var list vector.Vector for p.tok != token.RBRACE && p.tok != token.EOF { - list.Push(p.parseElement()); + list.Push(p.parseElement()) if p.tok != token.COMMA { break } - p.next(); + p.next() } - return makeExprList(&list); + return makeExprList(&list) } @@ -1010,13 +1010,13 @@ func (p *parser) parseCompositeLit(typ ast.Expr) ast.Expr { defer un(trace(p, "CompositeLit")) } - lbrace := p.expect(token.LBRACE); - var elts []ast.Expr; + lbrace := p.expect(token.LBRACE) + var elts []ast.Expr if p.tok != token.RBRACE { elts = p.parseElementList() } - rbrace := p.expect(token.RBRACE); - return &ast.CompositeLit{typ, lbrace, elts, rbrace}; + rbrace := p.expect(token.RBRACE) + return &ast.CompositeLit{typ, lbrace, elts, rbrace} } @@ -1042,24 +1042,24 @@ func (p *parser) checkExpr(x ast.Expr) ast.Expr { case *ast.TypeAssertExpr: if t.Type == nil { // the form X.(type) is only allowed in type switch expressions - p.errorExpected(x.Pos(), "expression"); - x = &ast.BadExpr{x.Pos()}; + p.errorExpected(x.Pos(), "expression") + x = &ast.BadExpr{x.Pos()} } case *ast.CallExpr: case *ast.StarExpr: case *ast.UnaryExpr: if t.Op == token.RANGE { // the range operator is only allowed at the top of a for statement - p.errorExpected(x.Pos(), "expression"); - x = &ast.BadExpr{x.Pos()}; + p.errorExpected(x.Pos(), "expression") + x = &ast.BadExpr{x.Pos()} } case *ast.BinaryExpr: default: // all other nodes are not proper expressions - p.errorExpected(x.Pos(), "expression"); - x = &ast.BadExpr{x.Pos()}; + p.errorExpected(x.Pos(), "expression") + x = &ast.BadExpr{x.Pos()} } - return x; + return x } @@ -1070,13 +1070,13 @@ func isTypeName(x ast.Expr) bool { case *ast.BadExpr: case *ast.Ident: case *ast.ParenExpr: - return isTypeName(t.X) // TODO(gri): should (TypeName) be illegal? + return isTypeName(t.X) // TODO(gri): should (TypeName) be illegal? case *ast.SelectorExpr: return isTypeName(t.X) default: - return false // all other nodes are not type names + return false // all other nodes are not type names } - return true; + return true } @@ -1094,9 +1094,9 @@ func isCompositeLitType(x ast.Expr) bool { case *ast.StructType: case *ast.MapType: default: - return false // all other nodes are not legal composite literal types + return false // all other nodes are not legal composite literal types } - return true; + return true } @@ -1109,18 +1109,18 @@ func (p *parser) checkExprOrType(x ast.Expr) ast.Expr { case *ast.UnaryExpr: if t.Op == token.RANGE { // the range operator is only allowed at the top of a for statement - p.errorExpected(x.Pos(), "expression"); - x = &ast.BadExpr{x.Pos()}; + p.errorExpected(x.Pos(), "expression") + x = &ast.BadExpr{x.Pos()} } case *ast.ArrayType: if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis { - p.Error(len.Pos(), "expected array length, found '...'"); - x = &ast.BadExpr{x.Pos()}; + p.Error(len.Pos(), "expected array length, found '...'") + x = &ast.BadExpr{x.Pos()} } } // all other nodes are expressions or types - return x; + return x } @@ -1129,8 +1129,8 @@ func (p *parser) parsePrimaryExpr() ast.Expr { defer un(trace(p, "PrimaryExpr")) } - x := p.parseOperand(); -L: for { + x := p.parseOperand() +L: for { switch p.tok { case token.PERIOD: x = p.parseSelectorOrTypeAssertion(p.checkExpr(x)) @@ -1149,7 +1149,7 @@ L: for { } } - return x; + return x } @@ -1160,20 +1160,20 @@ func (p *parser) parseUnaryExpr() ast.Expr { switch p.tok { case token.ADD, token.SUB, token.NOT, token.XOR, token.ARROW, token.AND, token.RANGE: - pos, op := p.pos, p.tok; - p.next(); - x := p.parseUnaryExpr(); - return &ast.UnaryExpr{pos, op, p.checkExpr(x)}; + pos, op := p.pos, p.tok + p.next() + x := p.parseUnaryExpr() + return &ast.UnaryExpr{pos, op, p.checkExpr(x)} case token.MUL: // unary "*" expression or pointer type - pos := p.pos; - p.next(); - x := p.parseUnaryExpr(); - return &ast.StarExpr{pos, p.checkExprOrType(x)}; + pos := p.pos + p.next() + x := p.parseUnaryExpr() + return &ast.StarExpr{pos, p.checkExprOrType(x)} } - return p.parsePrimaryExpr(); + return p.parsePrimaryExpr() } @@ -1182,17 +1182,17 @@ func (p *parser) parseBinaryExpr(prec1 int) ast.Expr { defer un(trace(p, "BinaryExpr")) } - x := p.parseUnaryExpr(); + x := p.parseUnaryExpr() for prec := p.tok.Precedence(); prec >= prec1; prec-- { for p.tok.Precedence() == prec { - pos, op := p.pos, p.tok; - p.next(); - y := p.parseBinaryExpr(prec + 1); - x = &ast.BinaryExpr{p.checkExpr(x), pos, op, p.checkExpr(y)}; + pos, op := p.pos, p.tok + p.next() + y := p.parseBinaryExpr(prec + 1) + x = &ast.BinaryExpr{p.checkExpr(x), pos, op, p.checkExpr(y)} } } - return x; + return x } @@ -1203,7 +1203,7 @@ func (p *parser) parseExpr() ast.Expr { defer un(trace(p, "Expression")) } - return p.parseBinaryExpr(token.LowestPrec + 1); + return p.parseBinaryExpr(token.LowestPrec + 1) } @@ -1215,19 +1215,19 @@ func (p *parser) parseSimpleStmt(labelOk bool) ast.Stmt { defer un(trace(p, "SimpleStmt")) } - x := p.parseExprList(); + x := p.parseExprList() switch p.tok { case token.COLON: // labeled statement - p.next(); + p.next() if labelOk && len(x) == 1 { if label, isIdent := x[0].(*ast.Ident); isIdent { return &ast.LabeledStmt{label, p.parseStmt()} } } - p.Error(x[0].Pos(), "illegal label declaration"); - return &ast.BadStmt{x[0].Pos()}; + p.Error(x[0].Pos(), "illegal label declaration") + return &ast.BadStmt{x[0].Pos()} case token.DEFINE, token.ASSIGN, token.ADD_ASSIGN, @@ -1235,13 +1235,13 @@ func (p *parser) parseSimpleStmt(labelOk bool) ast.Stmt { token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN, token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN: // assignment statement - pos, tok := p.pos, p.tok; - p.next(); - y := p.parseExprList(); + pos, tok := p.pos, p.tok + p.next() + y := p.parseExprList() if len(x) > 1 && len(y) > 1 && len(x) != len(y) { p.Error(x[0].Pos(), "arity of lhs doesn't match rhs") } - return &ast.AssignStmt{x, pos, tok, y}; + return &ast.AssignStmt{x, pos, tok, y} } if len(x) > 1 { @@ -1251,23 +1251,23 @@ func (p *parser) parseSimpleStmt(labelOk bool) ast.Stmt { if p.tok == token.INC || p.tok == token.DEC { // increment or decrement - s := &ast.IncDecStmt{x[0], p.tok}; - p.next(); // consume "++" or "--" - return s; + s := &ast.IncDecStmt{x[0], p.tok} + p.next() // consume "++" or "--" + return s } // expression - return &ast.ExprStmt{x[0]}; + return &ast.ExprStmt{x[0]} } func (p *parser) parseCallExpr() *ast.CallExpr { - x := p.parseExpr(); + x := p.parseExpr() if call, isCall := x.(*ast.CallExpr); isCall { return call } - p.errorExpected(x.Pos(), "function/method call"); - return nil; + p.errorExpected(x.Pos(), "function/method call") + return nil } @@ -1276,14 +1276,14 @@ func (p *parser) parseGoStmt() ast.Stmt { defer un(trace(p, "GoStmt")) } - pos := p.expect(token.GO); - call := p.parseCallExpr(); - p.expectSemi(); + pos := p.expect(token.GO) + call := p.parseCallExpr() + p.expectSemi() if call == nil { return &ast.BadStmt{pos} } - return &ast.GoStmt{pos, call}; + return &ast.GoStmt{pos, call} } @@ -1292,14 +1292,14 @@ func (p *parser) parseDeferStmt() ast.Stmt { defer un(trace(p, "DeferStmt")) } - pos := p.expect(token.DEFER); - call := p.parseCallExpr(); - p.expectSemi(); + pos := p.expect(token.DEFER) + call := p.parseCallExpr() + p.expectSemi() if call == nil { return &ast.BadStmt{pos} } - return &ast.DeferStmt{pos, call}; + return &ast.DeferStmt{pos, call} } @@ -1308,15 +1308,15 @@ func (p *parser) parseReturnStmt() *ast.ReturnStmt { defer un(trace(p, "ReturnStmt")) } - pos := p.pos; - p.expect(token.RETURN); - var x []ast.Expr; + pos := p.pos + p.expect(token.RETURN) + var x []ast.Expr if p.tok != token.SEMICOLON && p.tok != token.RBRACE { x = p.parseExprList() } - p.expectSemi(); + p.expectSemi() - return &ast.ReturnStmt{pos, x}; + return &ast.ReturnStmt{pos, x} } @@ -1325,14 +1325,14 @@ func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt { defer un(trace(p, "BranchStmt")) } - s := &ast.BranchStmt{p.pos, tok, nil}; - p.expect(tok); + s := &ast.BranchStmt{p.pos, tok, nil} + p.expect(tok) if tok != token.FALLTHROUGH && p.tok == token.IDENT { s.Label = p.parseIdent() } - p.expectSemi(); + p.expectSemi() - return s; + return s } @@ -1343,27 +1343,27 @@ func (p *parser) makeExpr(s ast.Stmt) ast.Expr { if es, isExpr := s.(*ast.ExprStmt); isExpr { return p.checkExpr(es.X) } - p.Error(s.Pos(), "expected condition, found simple statement"); - return &ast.BadExpr{s.Pos()}; + p.Error(s.Pos(), "expected condition, found simple statement") + return &ast.BadExpr{s.Pos()} } func (p *parser) parseControlClause(isForStmt bool) (s1, s2, s3 ast.Stmt) { if p.tok != token.LBRACE { - prevLev := p.exprLev; - p.exprLev = -1; + prevLev := p.exprLev + p.exprLev = -1 if p.tok != token.SEMICOLON { s1 = p.parseSimpleStmt(false) } if p.tok == token.SEMICOLON { - p.next(); + p.next() if p.tok != token.LBRACE && p.tok != token.SEMICOLON { s2 = p.parseSimpleStmt(false) } if isForStmt { // for statements have a 3rd section - p.expectSemi(); + p.expectSemi() if p.tok != token.LBRACE { s3 = p.parseSimpleStmt(false) } @@ -1372,10 +1372,10 @@ func (p *parser) parseControlClause(isForStmt bool) (s1, s2, s3 ast.Stmt) { s1, s2 = nil, s1 } - p.exprLev = prevLev; + p.exprLev = prevLev } - return s1, s2, s3; + return s1, s2, s3 } @@ -1385,20 +1385,20 @@ func (p *parser) parseIfStmt() *ast.IfStmt { } // IfStmt block - defer close(openScope(p)); + defer close(openScope(p)) - pos := p.expect(token.IF); - s1, s2, _ := p.parseControlClause(false); - body := p.parseBlockStmt(); - var else_ ast.Stmt; + pos := p.expect(token.IF) + s1, s2, _ := p.parseControlClause(false) + body := p.parseBlockStmt() + var else_ ast.Stmt if p.tok == token.ELSE { - p.next(); - else_ = p.parseStmt(); + p.next() + else_ = p.parseStmt() } else { p.expectSemi() } - return &ast.IfStmt{pos, s1, p.makeExpr(s2), body, else_}; + return &ast.IfStmt{pos, s1, p.makeExpr(s2), body, else_} } @@ -1408,22 +1408,22 @@ func (p *parser) parseCaseClause() *ast.CaseClause { } // CaseClause block - defer close(openScope(p)); + defer close(openScope(p)) // SwitchCase - pos := p.pos; - var x []ast.Expr; + pos := p.pos + var x []ast.Expr if p.tok == token.CASE { - p.next(); - x = p.parseExprList(); + p.next() + x = p.parseExprList() } else { p.expect(token.DEFAULT) } - colon := p.expect(token.COLON); - body := p.parseStmtList(); + colon := p.expect(token.COLON) + body := p.parseStmtList() - return &ast.CaseClause{pos, x, colon, body}; + return &ast.CaseClause{pos, x, colon, body} } @@ -1432,14 +1432,14 @@ func (p *parser) parseTypeList() []ast.Expr { defer un(trace(p, "TypeList")) } - var list vector.Vector; - list.Push(p.parseType()); + var list vector.Vector + list.Push(p.parseType()) for p.tok == token.COMMA { - p.next(); - list.Push(p.parseType()); + p.next() + list.Push(p.parseType()) } - return makeExprList(&list); + return makeExprList(&list) } @@ -1449,22 +1449,22 @@ func (p *parser) parseTypeCaseClause() *ast.TypeCaseClause { } // TypeCaseClause block - defer close(openScope(p)); + defer close(openScope(p)) // TypeSwitchCase - pos := p.pos; - var types []ast.Expr; + pos := p.pos + var types []ast.Expr if p.tok == token.CASE { - p.next(); - types = p.parseTypeList(); + p.next() + types = p.parseTypeList() } else { p.expect(token.DEFAULT) } - colon := p.expect(token.COLON); - body := p.parseStmtList(); + colon := p.expect(token.COLON) + body := p.parseStmtList() - return &ast.TypeCaseClause{pos, types, colon, body}; + return &ast.TypeCaseClause{pos, types, colon, body} } @@ -1474,11 +1474,11 @@ func isExprSwitch(s ast.Stmt) bool { } if e, ok := s.(*ast.ExprStmt); ok { if a, ok := e.X.(*ast.TypeAssertExpr); ok { - return a.Type != nil // regular type assertion + return a.Type != nil // regular type assertion } - return true; + return true } - return false; + return false } @@ -1488,34 +1488,34 @@ func (p *parser) parseSwitchStmt() ast.Stmt { } // SwitchStmt block - defer close(openScope(p)); + defer close(openScope(p)) - pos := p.expect(token.SWITCH); - s1, s2, _ := p.parseControlClause(false); + pos := p.expect(token.SWITCH) + s1, s2, _ := p.parseControlClause(false) if isExprSwitch(s2) { - lbrace := p.expect(token.LBRACE); - var cases vector.Vector; + lbrace := p.expect(token.LBRACE) + var cases vector.Vector for p.tok == token.CASE || p.tok == token.DEFAULT { cases.Push(p.parseCaseClause()) } - rbrace := p.expect(token.RBRACE); - body := &ast.BlockStmt{lbrace, makeStmtList(&cases), rbrace}; - p.expectSemi(); - return &ast.SwitchStmt{pos, s1, p.makeExpr(s2), body}; + rbrace := p.expect(token.RBRACE) + body := &ast.BlockStmt{lbrace, makeStmtList(&cases), rbrace} + p.expectSemi() + return &ast.SwitchStmt{pos, s1, p.makeExpr(s2), body} } // type switch // TODO(gri): do all the checks! - lbrace := p.expect(token.LBRACE); - var cases vector.Vector; + lbrace := p.expect(token.LBRACE) + var cases vector.Vector for p.tok == token.CASE || p.tok == token.DEFAULT { cases.Push(p.parseTypeCaseClause()) } - rbrace := p.expect(token.RBRACE); - p.expectSemi(); - body := &ast.BlockStmt{lbrace, makeStmtList(&cases), rbrace}; - return &ast.TypeSwitchStmt{pos, s1, s2, body}; + rbrace := p.expect(token.RBRACE) + p.expectSemi() + body := &ast.BlockStmt{lbrace, makeStmtList(&cases), rbrace} + return &ast.TypeSwitchStmt{pos, s1, s2, body} } @@ -1525,29 +1525,29 @@ func (p *parser) parseCommClause() *ast.CommClause { } // CommClause block - defer close(openScope(p)); + defer close(openScope(p)) // CommCase - pos := p.pos; - var tok token.Token; - var lhs, rhs ast.Expr; + pos := p.pos + var tok token.Token + var lhs, rhs ast.Expr if p.tok == token.CASE { - p.next(); + p.next() if p.tok == token.ARROW { // RecvExpr without assignment rhs = p.parseExpr() } else { // SendExpr or RecvExpr - rhs = p.parseExpr(); + rhs = p.parseExpr() if p.tok == token.ASSIGN || p.tok == token.DEFINE { // RecvExpr with assignment - tok = p.tok; - p.next(); - lhs = rhs; + tok = p.tok + p.next() + lhs = rhs if p.tok == token.ARROW { rhs = p.parseExpr() } else { - p.expect(token.ARROW) // use expect() error handling + p.expect(token.ARROW) // use expect() error handling } } // else SendExpr @@ -1556,10 +1556,10 @@ func (p *parser) parseCommClause() *ast.CommClause { p.expect(token.DEFAULT) } - colon := p.expect(token.COLON); - body := p.parseStmtList(); + colon := p.expect(token.COLON) + body := p.parseStmtList() - return &ast.CommClause{pos, tok, lhs, rhs, colon, body}; + return &ast.CommClause{pos, tok, lhs, rhs, colon, body} } @@ -1568,17 +1568,17 @@ func (p *parser) parseSelectStmt() *ast.SelectStmt { defer un(trace(p, "SelectStmt")) } - pos := p.expect(token.SELECT); - lbrace := p.expect(token.LBRACE); - var cases vector.Vector; + pos := p.expect(token.SELECT) + lbrace := p.expect(token.LBRACE) + var cases vector.Vector for p.tok == token.CASE || p.tok == token.DEFAULT { cases.Push(p.parseCommClause()) } - rbrace := p.expect(token.RBRACE); - p.expectSemi(); - body := &ast.BlockStmt{lbrace, makeStmtList(&cases), rbrace}; + rbrace := p.expect(token.RBRACE) + p.expectSemi() + body := &ast.BlockStmt{lbrace, makeStmtList(&cases), rbrace} - return &ast.SelectStmt{pos, body}; + return &ast.SelectStmt{pos, body} } @@ -1588,50 +1588,50 @@ func (p *parser) parseForStmt() ast.Stmt { } // ForStmt block - defer close(openScope(p)); + defer close(openScope(p)) - pos := p.expect(token.FOR); - s1, s2, s3 := p.parseControlClause(true); - body := p.parseBlockStmt(); - p.expectSemi(); + pos := p.expect(token.FOR) + s1, s2, s3 := p.parseControlClause(true) + body := p.parseBlockStmt() + p.expectSemi() if as, isAssign := s2.(*ast.AssignStmt); isAssign { // possibly a for statement with a range clause; check assignment operator if as.Tok != token.ASSIGN && as.Tok != token.DEFINE { - p.errorExpected(as.TokPos, "'=' or ':='"); - return &ast.BadStmt{pos}; + p.errorExpected(as.TokPos, "'=' or ':='") + return &ast.BadStmt{pos} } // check lhs - var key, value ast.Expr; + var key, value ast.Expr switch len(as.Lhs) { case 2: - value = as.Lhs[1]; - fallthrough; + value = as.Lhs[1] + fallthrough case 1: key = as.Lhs[0] default: - p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions"); - return &ast.BadStmt{pos}; + p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions") + return &ast.BadStmt{pos} } // check rhs if len(as.Rhs) != 1 { - p.errorExpected(as.Rhs[0].Pos(), "1 expressions"); - return &ast.BadStmt{pos}; + p.errorExpected(as.Rhs[0].Pos(), "1 expressions") + return &ast.BadStmt{pos} } if rhs, isUnary := as.Rhs[0].(*ast.UnaryExpr); isUnary && rhs.Op == token.RANGE { // rhs is range expression; check lhs return &ast.RangeStmt{pos, key, value, as.TokPos, as.Tok, rhs.X, body} } else { - p.errorExpected(s2.Pos(), "range clause"); - return &ast.BadStmt{pos}; + p.errorExpected(s2.Pos(), "range clause") + return &ast.BadStmt{pos} } } else { // regular for statement return &ast.ForStmt{pos, s1, p.makeExpr(s2), s3, body} } - panic(); // unreachable - return nil; + panic() // unreachable + return nil } @@ -1645,10 +1645,10 @@ func (p *parser) parseStmt() (s ast.Stmt) { s = &ast.DeclStmt{p.parseDecl()} case // tokens that may start a top-level expression - token.IDENT, token.INT, token.FLOAT, token.CHAR, token.STRING, token.FUNC, token.LPAREN, // operand - token.LBRACK, token.STRUCT, // composite type - token.MUL, token.AND, token.ARROW, token.ADD, token.SUB, token.XOR: // unary operators - s = p.parseSimpleStmt(true); + token.IDENT, token.INT, token.FLOAT, token.CHAR, token.STRING, token.FUNC, token.LPAREN, // operand + token.LBRACK, token.STRUCT, // composite type + token.MUL, token.AND, token.ARROW, token.ADD, token.SUB, token.XOR: // unary operators + s = p.parseSimpleStmt(true) // because of the required look-ahead, labeled statements are // parsed by parseSimpleStmt - don't expect a semicolon after // them @@ -1664,8 +1664,8 @@ func (p *parser) parseStmt() (s ast.Stmt) { case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH: s = p.parseBranchStmt(p.tok) case token.LBRACE: - s = p.parseBlockStmt(); - p.expectSemi(); + s = p.parseBlockStmt() + p.expectSemi() case token.IF: s = p.parseIfStmt() case token.SWITCH: @@ -1675,19 +1675,19 @@ func (p *parser) parseStmt() (s ast.Stmt) { case token.FOR: s = p.parseForStmt() case token.SEMICOLON: - p.next(); - fallthrough; + p.next() + fallthrough case token.RBRACE: // a semicolon may be omitted before a closing "}" s = &ast.EmptyStmt{p.pos} default: // no statement found - p.errorExpected(p.pos, "statement"); - p.next(); // make progress - s = &ast.BadStmt{p.pos}; + p.errorExpected(p.pos, "statement") + p.next() // make progress + s = &ast.BadStmt{p.pos} } - return; + return } @@ -1702,25 +1702,25 @@ func parseImportSpec(p *parser, doc *ast.CommentGroup) ast.Spec { defer un(trace(p, "ImportSpec")) } - var ident *ast.Ident; + var ident *ast.Ident if p.tok == token.PERIOD { - ident = &ast.Ident{p.pos, "."}; - p.next(); + ident = &ast.Ident{p.pos, "."} + p.next() } else if p.tok == token.IDENT { ident = p.parseIdent() } - var path []*ast.BasicLit; + var path []*ast.BasicLit if p.tok == token.STRING { - x := &ast.BasicLit{p.pos, p.tok, p.lit}; - p.next(); - path = []*ast.BasicLit{x}; + x := &ast.BasicLit{p.pos, p.tok, p.lit} + p.next() + path = []*ast.BasicLit{x} } else { - p.expect(token.STRING) // use expect() error handling + p.expect(token.STRING) // use expect() error handling } - p.expectSemi(); + p.expectSemi() - return &ast.ImportSpec{doc, ident, path, p.lineComment}; + return &ast.ImportSpec{doc, ident, path, p.lineComment} } @@ -1729,16 +1729,16 @@ func parseConstSpec(p *parser, doc *ast.CommentGroup) ast.Spec { defer un(trace(p, "ConstSpec")) } - idents := p.parseIdentList(); - typ := p.tryType(); - var values []ast.Expr; + idents := p.parseIdentList() + typ := p.tryType() + var values []ast.Expr if typ != nil || p.tok == token.ASSIGN { - p.expect(token.ASSIGN); - values = p.parseExprList(); + p.expect(token.ASSIGN) + values = p.parseExprList() } - p.expectSemi(); + p.expectSemi() - return &ast.ValueSpec{doc, idents, typ, values, p.lineComment}; + return &ast.ValueSpec{doc, idents, typ, values, p.lineComment} } @@ -1747,11 +1747,11 @@ func parseTypeSpec(p *parser, doc *ast.CommentGroup) ast.Spec { defer un(trace(p, "TypeSpec")) } - ident := p.parseIdent(); - typ := p.parseType(); - p.expectSemi(); + ident := p.parseIdent() + typ := p.parseType() + p.expectSemi() - return &ast.TypeSpec{doc, ident, typ, p.lineComment}; + return &ast.TypeSpec{doc, ident, typ, p.lineComment} } @@ -1760,16 +1760,16 @@ func parseVarSpec(p *parser, doc *ast.CommentGroup) ast.Spec { defer un(trace(p, "VarSpec")) } - idents := p.parseIdentList(); - typ := p.tryType(); - var values []ast.Expr; + idents := p.parseIdentList() + typ := p.tryType() + var values []ast.Expr if typ == nil || p.tok == token.ASSIGN { - p.expect(token.ASSIGN); - values = p.parseExprList(); + p.expect(token.ASSIGN) + values = p.parseExprList() } - p.expectSemi(); + p.expectSemi() - return &ast.ValueSpec{doc, idents, typ, values, p.lineComment}; + return &ast.ValueSpec{doc, idents, typ, values, p.lineComment} } @@ -1778,29 +1778,29 @@ func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.Gen defer un(trace(p, keyword.String()+"Decl")) } - doc := p.leadComment; - pos := p.expect(keyword); - var lparen, rparen token.Position; - var list vector.Vector; + doc := p.leadComment + pos := p.expect(keyword) + var lparen, rparen token.Position + var list vector.Vector if p.tok == token.LPAREN { - lparen = p.pos; - p.next(); + lparen = p.pos + p.next() for p.tok != token.RPAREN && p.tok != token.EOF { list.Push(f(p, p.leadComment)) } - rparen = p.expect(token.RPAREN); - p.expectSemi(); + rparen = p.expect(token.RPAREN) + p.expectSemi() } else { list.Push(f(p, nil)) } // convert vector - specs := make([]ast.Spec, list.Len()); + specs := make([]ast.Spec, list.Len()) for i := 0; i < list.Len(); i++ { specs[i] = list.At(i).(ast.Spec) } - return &ast.GenDecl{doc, pos, keyword, lparen, specs, rparen}; + return &ast.GenDecl{doc, pos, keyword, lparen, specs, rparen} } @@ -1809,19 +1809,19 @@ func (p *parser) parseReceiver() *ast.Field { defer un(trace(p, "Receiver")) } - pos := p.pos; - par := p.parseParameters(false); + pos := p.pos + par := p.parseParameters(false) // must have exactly one receiver if len(par) != 1 || len(par) == 1 && len(par[0].Names) > 1 { - p.errorExpected(pos, "exactly one receiver"); - return &ast.Field{Type: &ast.BadExpr{noPos}}; + p.errorExpected(pos, "exactly one receiver") + return &ast.Field{Type: &ast.BadExpr{noPos}} } - recv := par[0]; + recv := par[0] // recv type must be TypeName or *TypeName - base := recv.Type; + base := recv.Type if ptr, isPtr := base.(*ast.StarExpr); isPtr { base = ptr.X } @@ -1829,7 +1829,7 @@ func (p *parser) parseReceiver() *ast.Field { p.errorExpected(base.Pos(), "type name") } - return recv; + return recv } @@ -1838,24 +1838,24 @@ func (p *parser) parseFunctionDecl() *ast.FuncDecl { defer un(trace(p, "FunctionDecl")) } - doc := p.leadComment; - pos := p.expect(token.FUNC); + doc := p.leadComment + pos := p.expect(token.FUNC) - var recv *ast.Field; + var recv *ast.Field if p.tok == token.LPAREN { recv = p.parseReceiver() } - ident := p.parseIdent(); - params, results := p.parseSignature(); + ident := p.parseIdent() + params, results := p.parseSignature() - var body *ast.BlockStmt; + var body *ast.BlockStmt if p.tok == token.LBRACE { body = p.parseBlockStmt() } - p.expectSemi(); + p.expectSemi() - return &ast.FuncDecl{doc, recv, ident, &ast.FuncType{pos, params, results}, body}; + return &ast.FuncDecl{doc, recv, ident, &ast.FuncType{pos, params, results}, body} } @@ -1864,7 +1864,7 @@ func (p *parser) parseDecl() ast.Decl { defer un(trace(p, "Declaration")) } - var f parseSpecFunction; + var f parseSpecFunction switch p.tok { case token.CONST: f = parseConstSpec @@ -1879,14 +1879,14 @@ func (p *parser) parseDecl() ast.Decl { return p.parseFunctionDecl() default: - pos := p.pos; - p.errorExpected(pos, "declaration"); - decl := &ast.BadDecl{pos}; - p.next(); // make progress in any case - return decl; + pos := p.pos + p.errorExpected(pos, "declaration") + decl := &ast.BadDecl{pos} + p.next() // make progress in any case + return decl } - return p.parseGenDecl(p.tok, f); + return p.parseGenDecl(p.tok, f) } @@ -1895,18 +1895,18 @@ func (p *parser) parseDeclList() []ast.Decl { defer un(trace(p, "DeclList")) } - var list vector.Vector; + var list vector.Vector for p.tok != token.EOF { list.Push(p.parseDecl()) } // convert vector - decls := make([]ast.Decl, list.Len()); + decls := make([]ast.Decl, list.Len()) for i := 0; i < list.Len(); i++ { decls[i] = list.At(i).(ast.Decl) } - return decls; + return decls } @@ -1919,22 +1919,22 @@ func (p *parser) parseFile() *ast.File { } // file block - defer close(openScope(p)); + defer close(openScope(p)) // package clause - doc := p.leadComment; - pos := p.expect(token.PACKAGE); - ident := p.parseIdent(); - p.expectSemi(); + doc := p.leadComment + pos := p.expect(token.PACKAGE) + ident := p.parseIdent() + p.expectSemi() - var decls []ast.Decl; + var decls []ast.Decl // Don't bother parsing the rest if we had errors already. // Likely not a Go source file at all. if p.ErrorCount() == 0 && p.mode&PackageClauseOnly == 0 { // import decls - var list vector.Vector; + var list vector.Vector for p.tok == token.IMPORT { list.Push(p.parseGenDecl(token.IMPORT, parseImportSpec)) } @@ -1947,11 +1947,11 @@ func (p *parser) parseFile() *ast.File { } // convert declaration list - decls = make([]ast.Decl, list.Len()); + decls = make([]ast.Decl, list.Len()) for i := 0; i < list.Len(); i++ { decls[i] = list.At(i).(ast.Decl) } } - return &ast.File{doc, pos, ident, decls, p.comments}; + return &ast.File{doc, pos, ident, decls, p.comments} } diff --git a/src/pkg/go/parser/parser_test.go b/src/pkg/go/parser/parser_test.go index ccb8a4511..208a7c513 100644 --- a/src/pkg/go/parser/parser_test.go +++ b/src/pkg/go/parser/parser_test.go @@ -5,8 +5,8 @@ package parser import ( - "os"; - "testing"; + "os" + "testing" ) @@ -20,7 +20,7 @@ var illegalInputs = []interface{}{ func TestParseIllegalInputs(t *testing.T) { for _, src := range illegalInputs { - _, err := ParseFile("", src, 0); + _, err := ParseFile("", src, 0) if err == nil { t.Errorf("ParseFile(%v) should have failed", src) } @@ -37,7 +37,7 @@ var validPrograms = []interface{}{ func TestParseValidPrograms(t *testing.T) { for _, src := range validPrograms { - _, err := ParseFile("", src, 0); + _, err := ParseFile("", src, 0) if err != nil { t.Errorf("ParseFile(%q): %v", src, err) } @@ -53,7 +53,7 @@ var validFiles = []string{ func TestParse3(t *testing.T) { for _, filename := range validFiles { - _, err := ParseFile(filename, nil, 0); + _, err := ParseFile(filename, nil, 0) if err != nil { t.Errorf("ParseFile(%s): %v", filename, err) } @@ -69,16 +69,16 @@ func nameFilter(filename string) bool { default: return false } - return true; + return true } -func dirFilter(d *os.Dir) bool { return nameFilter(d.Name) } +func dirFilter(d *os.Dir) bool { return nameFilter(d.Name) } func TestParse4(t *testing.T) { - path := "."; - pkg, err := ParsePackage(path, dirFilter, 0); + path := "." + pkg, err := ParsePackage(path, dirFilter, 0) if err != nil { t.Fatalf("ParsePackage(%s): %v", path, err) } diff --git a/src/pkg/go/printer/nodes.go b/src/pkg/go/printer/nodes.go index f324bbc90..b082c2e40 100644 --- a/src/pkg/go/printer/nodes.go +++ b/src/pkg/go/printer/nodes.go @@ -9,15 +9,15 @@ package printer import ( - "bytes"; - "go/ast"; - "go/token"; + "bytes" + "go/ast" + "go/token" ) // Disabled formatting - enable eventually and remove the flag. const ( - compositeLitBlank = false; + compositeLitBlank = false ) @@ -43,7 +43,7 @@ const ( // TODO(gri): Reconsider signature (provide position instead of line) // func (p *printer) linebreak(line, min, max int, ws whiteSpace, newSection bool) (printedBreak bool) { - n := line - p.pos.Line; + n := line - p.pos.Line switch { case n < min: n = min @@ -52,18 +52,18 @@ func (p *printer) linebreak(line, min, max int, ws whiteSpace, newSection bool) } if n > 0 { - p.print(ws); + p.print(ws) if newSection { - p.print(formfeed); - n--; - printedBreak = true; + p.print(formfeed) + n-- + printedBreak = true } } for ; n > 0; n-- { - p.print(newline); - printedBreak = true; + p.print(newline) + printedBreak = true } - return; + return } @@ -74,9 +74,9 @@ func (p *printer) linebreak(line, min, max int, ws whiteSpace, newSection bool) // Print a list of individual comments. func (p *printer) commentList(list []*ast.Comment) { for i, c := range list { - t := c.Text; + t := c.Text // TODO(gri): this needs to be styled like normal comments - p.print(c.Pos(), t); + p.print(c.Pos(), t) if t[1] == '/' && i+1 < len(list) { //-style comment which is not at the end; print a newline p.print(newline) @@ -89,8 +89,8 @@ func (p *printer) commentList(list []*ast.Comment) { func (p *printer) leadComment(d *ast.CommentGroup) { // Ignore the comment if we have comments interspersed (p.comment != nil). if p.comment == nil && d != nil { - p.commentList(d.List); - p.print(newline); + p.commentList(d.List) + p.print(newline) } } @@ -101,8 +101,8 @@ func (p *printer) leadComment(d *ast.CommentGroup) { func (p *printer) lineComment(d *ast.CommentGroup) { // Ignore the comment if we have comments interspersed (p.comment != nil). if p.comment == nil && d != nil { - p.print(vtab); - p.commentList(d.List); + p.print(vtab) + p.commentList(d.List) } } @@ -110,34 +110,34 @@ func (p *printer) lineComment(d *ast.CommentGroup) { // Sets multiLine to true if the identifier list spans multiple lines. func (p *printer) identList(list []*ast.Ident, multiLine *bool) { // convert into an expression list so we can re-use exprList formatting - xlist := make([]ast.Expr, len(list)); + xlist := make([]ast.Expr, len(list)) for i, x := range list { xlist[i] = x } - p.exprList(noPos, xlist, 1, commaSep, multiLine); + p.exprList(noPos, xlist, 1, commaSep, multiLine) } // Sets multiLine to true if the string list spans multiple lines. func (p *printer) stringList(list []*ast.BasicLit, multiLine *bool) { // convert into an expression list so we can re-use exprList formatting - xlist := make([]ast.Expr, len(list)); + xlist := make([]ast.Expr, len(list)) for i, x := range list { xlist[i] = x } - p.exprList(noPos, xlist, 1, plusSep, multiLine); + p.exprList(noPos, xlist, 1, plusSep, multiLine) } type exprListMode uint const ( - blankStart exprListMode = 1 << iota; // print a blank before a non-empty list - blankEnd; // print a blank after a non-empty list - plusSep; // elements are separared by + operators - commaSep; // elements are separated by commas - commaTerm; // elements are terminated by comma - noIndent; // no extra indentation in multi-line lists + blankStart exprListMode = 1 << iota // print a blank before a non-empty list + blankEnd // print a blank after a non-empty list + plusSep // elements are separared by + operators + commaSep // elements are separated by commas + commaTerm // elements are terminated by comma + noIndent // no extra indentation in multi-line lists ) @@ -153,12 +153,12 @@ const ( // some reasonable grace period (12/11/09). func (p *printer) beforeComment(pos token.Position) token.Position { if p.comment != nil { - p := p.comment.List[0].Position; + p := p.comment.List[0].Position if !pos.IsValid() || pos.Offset > p.Offset { return p } } - return pos; + return pos } @@ -178,8 +178,8 @@ func (p *printer) exprList(prev token.Position, list []ast.Expr, depth int, mode // TODO(gri): endLine may be incorrect as it is really the beginning // of the last list entry. There may be only one, very long // entry in which case line == endLine. - line := list[0].Pos().Line; - endLine := list[len(list)-1].Pos().Line; + line := list[0].Pos().Line + endLine := list[len(list)-1].Pos().Line if prev.IsValid() && prev.Line == line && line == endLine { // all list entries on a single line @@ -191,14 +191,14 @@ func (p *printer) exprList(prev token.Position, list []ast.Expr, depth int, mode if mode&commaSep != 0 { p.print(token.COMMA) } - p.print(blank); + p.print(blank) } - p.expr0(x, depth, multiLine); + p.expr0(x, depth, multiLine) } if mode&blankEnd != 0 { p.print(blank) } - return; + return } // list entries span multiple lines; @@ -206,19 +206,19 @@ func (p *printer) exprList(prev token.Position, list []ast.Expr, depth int, mode // don't add extra indentation if noIndent is set; // i.e., pretend that the first line is already indented - ws := ignore; + ws := ignore if mode&noIndent == 0 { ws = indent } if prev.IsValid() && prev.Line < line && p.linebreak(line, 1, 2, ws, true) { - ws = ignore; - *multiLine = true; + ws = ignore + *multiLine = true } for i, x := range list { - prev := line; - line = x.Pos().Line; + prev := line + line = x.Pos().Line if i > 0 { if mode&plusSep != 0 { p.print(blank, p.beforeComment(noPos), token.ADD) @@ -228,24 +228,24 @@ func (p *printer) exprList(prev token.Position, list []ast.Expr, depth int, mode } if prev < line && prev > 0 && line > 0 { if p.linebreak(line, 1, 2, ws, true) { - ws = ignore; - *multiLine = true; + ws = ignore + *multiLine = true } } else { p.print(blank) } } - p.expr0(x, depth, multiLine); + p.expr0(x, depth, multiLine) } if mode&commaTerm != 0 { - p.print(token.COMMA); + p.print(token.COMMA) if ws == ignore && mode&noIndent == 0 { // unindent if we indented p.print(unindent) } - p.print(formfeed); // terminating comma needs a line break to look good - return; + p.print(formfeed) // terminating comma needs a line break to look good + return } if mode&blankEnd != 0 { @@ -261,79 +261,79 @@ func (p *printer) exprList(prev token.Position, list []ast.Expr, depth int, mode // Sets multiLine to true if the the parameter list spans multiple lines. func (p *printer) parameters(list []*ast.Field, multiLine *bool) { - p.print(token.LPAREN); + p.print(token.LPAREN) if len(list) > 0 { for i, par := range list { if i > 0 { p.print(token.COMMA, blank) } if len(par.Names) > 0 { - p.identList(par.Names, multiLine); - p.print(blank); + p.identList(par.Names, multiLine) + p.print(blank) } - p.expr(par.Type, multiLine); + p.expr(par.Type, multiLine) } } - p.print(token.RPAREN); + p.print(token.RPAREN) } // Returns true if a separating semicolon is optional. // Sets multiLine to true if the signature spans multiple lines. func (p *printer) signature(params, result []*ast.Field, multiLine *bool) (optSemi bool) { - p.parameters(params, multiLine); + p.parameters(params, multiLine) if result != nil { - p.print(blank); + p.print(blank) if len(result) == 1 && result[0].Names == nil { // single anonymous result; no ()'s unless it's a function type - f := result[0]; + f := result[0] if _, isFtyp := f.Type.(*ast.FuncType); !isFtyp { - optSemi = p.expr(f.Type, multiLine); - return; + optSemi = p.expr(f.Type, multiLine) + return } } - p.parameters(result, multiLine); + p.parameters(result, multiLine) } - return; + return } func identListSize(list []*ast.Ident, maxSize int) (size int) { for i, x := range list { if i > 0 { - size += 2 // ", " + size += 2 // ", " } - size += len(x.Value); + size += len(x.Value) if size >= maxSize { break } } - return; + return } func (p *printer) isOneLineFieldList(list []*ast.Field) bool { if len(list) != 1 { - return false // allow only one field + return false // allow only one field } - f := list[0]; + f := list[0] if f.Tag != nil || f.Comment != nil { - return false // don't allow tags or comments + return false // don't allow tags or comments } // only name(s) and type - const maxSize = 30; // adjust as appropriate, this is an approximate value - namesSize := identListSize(f.Names, maxSize); + const maxSize = 30 // adjust as appropriate, this is an approximate value + namesSize := identListSize(f.Names, maxSize) if namesSize > 0 { - namesSize = 1 // blank between names and types + namesSize = 1 // blank between names and types } - typeSize := p.nodeSize(f.Type, maxSize); - return namesSize+typeSize <= maxSize; + typeSize := p.nodeSize(f.Type, maxSize) + return namesSize+typeSize <= maxSize } @@ -342,63 +342,63 @@ func (p *printer) fieldList(lbrace token.Position, list []*ast.Field, rbrace tok // possibly a one-line struct/interface if len(list) == 0 { // no blank between keyword and {} in this case - p.print(lbrace, token.LBRACE, rbrace, token.RBRACE); - return; + p.print(lbrace, token.LBRACE, rbrace, token.RBRACE) + return } else if ctxt&(compositeLit|structType) == compositeLit|structType && - p.isOneLineFieldList(list) { // for now ignore interfaces + p.isOneLineFieldList(list) { // for now ignore interfaces // small enough - print on one line // (don't use identList and ignore source line breaks) - p.print(lbrace, token.LBRACE, blank); - f := list[0]; + p.print(lbrace, token.LBRACE, blank) + f := list[0] for i, x := range f.Names { if i > 0 { p.print(token.COMMA, blank) } - p.expr(x, ignoreMultiLine); + p.expr(x, ignoreMultiLine) } if len(f.Names) > 0 { p.print(blank) } - p.expr(f.Type, ignoreMultiLine); - p.print(blank, rbrace, token.RBRACE); - return; + p.expr(f.Type, ignoreMultiLine) + p.print(blank, rbrace, token.RBRACE) + return } } // at least one entry or incomplete - p.print(blank, lbrace, token.LBRACE, indent, formfeed); + p.print(blank, lbrace, token.LBRACE, indent, formfeed) if ctxt&structType != 0 { - sep := vtab; + sep := vtab if len(list) == 1 { sep = blank } - var ml bool; + var ml bool for i, f := range list { if i > 0 { p.linebreak(f.Pos().Line, 1, 2, ignore, ml) } - ml = false; - extraTabs := 0; - p.leadComment(f.Doc); + ml = false + extraTabs := 0 + p.leadComment(f.Doc) if len(f.Names) > 0 { // named fields - p.identList(f.Names, &ml); - p.print(sep); - p.expr(f.Type, &ml); - extraTabs = 1; + p.identList(f.Names, &ml) + p.print(sep) + p.expr(f.Type, &ml) + extraTabs = 1 } else { // anonymous field - p.expr(f.Type, &ml); - extraTabs = 2; + p.expr(f.Type, &ml) + extraTabs = 2 } if f.Tag != nil { if len(f.Names) > 0 && sep == vtab { p.print(sep) } - p.print(sep); - p.expr(&ast.StringList{f.Tag}, &ml); - extraTabs = 0; + p.print(sep) + p.expr(&ast.StringList{f.Tag}, &ml) + extraTabs = 0 } if p.Mode&NoSemis == 0 { p.print(token.SEMICOLON) @@ -407,7 +407,7 @@ func (p *printer) fieldList(lbrace token.Position, list []*ast.Field, rbrace tok for ; extraTabs > 0; extraTabs-- { p.print(vtab) } - p.lineComment(f.Comment); + p.lineComment(f.Comment) } } if isIncomplete { @@ -415,22 +415,22 @@ func (p *printer) fieldList(lbrace token.Position, list []*ast.Field, rbrace tok p.print(formfeed) } // TODO(gri): this needs to be styled like normal comments - p.print("// contains unexported fields"); + p.print("// contains unexported fields") } - } else { // interface + } else { // interface - var ml bool; + var ml bool for i, f := range list { if i > 0 { p.linebreak(f.Pos().Line, 1, 2, ignore, ml) } - ml = false; - p.leadComment(f.Doc); + ml = false + p.leadComment(f.Doc) if ftyp, isFtyp := f.Type.(*ast.FuncType); isFtyp { // method - p.expr(f.Names[0], &ml); - p.signature(ftyp.Params, ftyp.Results, &ml); + p.expr(f.Names[0], &ml) + p.signature(ftyp.Params, ftyp.Results, &ml) } else { // embedded interface p.expr(f.Type, &ml) @@ -438,18 +438,18 @@ func (p *printer) fieldList(lbrace token.Position, list []*ast.Field, rbrace tok if p.Mode&NoSemis == 0 { p.print(token.SEMICOLON) } - p.lineComment(f.Comment); + p.lineComment(f.Comment) } if isIncomplete { if len(list) > 0 { p.print(formfeed) } // TODO(gri): this needs to be styled like normal comments - p.print("// contains unexported methods"); + p.print("// contains unexported methods") } } - p.print(unindent, formfeed, rbrace, token.RBRACE); + p.print(unindent, formfeed, rbrace, token.RBRACE) } @@ -460,8 +460,8 @@ func (p *printer) fieldList(lbrace token.Position, list []*ast.Field, rbrace tok type exprContext uint const ( - compositeLit = 1 << iota; - structType; + compositeLit = 1 << iota + structType ) @@ -480,9 +480,9 @@ func walkBinary(e *ast.BinaryExpr) (has5, has6 bool, maxProblem int) { // pretend this is an *ast.ParenExpr and do nothing. break } - h5, h6, mp := walkBinary(l); - has5 = has5 || h5; - has6 = has6 || h6; + h5, h6, mp := walkBinary(l) + has5 = has5 || h5 + has6 = has6 || h6 if maxProblem < mp { maxProblem = mp } @@ -495,9 +495,9 @@ func walkBinary(e *ast.BinaryExpr) (has5, has6 bool, maxProblem int) { // pretend this is an *ast.ParenExpr and do nothing. break } - h5, h6, mp := walkBinary(r); - has5 = has5 || h5; - has6 = has6 || h6; + h5, h6, mp := walkBinary(r) + has5 = has5 || h5 + has6 = has6 || h6 if maxProblem < mp { maxProblem = mp } @@ -517,12 +517,12 @@ func walkBinary(e *ast.BinaryExpr) (has5, has6 bool, maxProblem int) { } } } - return; + return } func cutoff(e *ast.BinaryExpr, depth int) int { - has5, has6, maxProblem := walkBinary(e); + has5, has6, maxProblem := walkBinary(e) if maxProblem > 0 { return maxProblem + 1 } @@ -530,21 +530,21 @@ func cutoff(e *ast.BinaryExpr, depth int) int { if depth == 1 { return 6 } - return 5; + return 5 } if depth == 1 { return 7 } - return 5; + return 5 } func diffPrec(expr ast.Expr, prec int) int { - x, ok := expr.(*ast.BinaryExpr); + x, ok := expr.(*ast.BinaryExpr) if !ok || prec != x.Op.Precedence() { return 1 } - return 0; + return 0 } @@ -584,40 +584,40 @@ func diffPrec(expr ast.Expr, prec int) int { // // Sets multiLine to true if the binary expression spans multiple lines. func (p *printer) binaryExpr(x *ast.BinaryExpr, prec1, cutoff, depth int, multiLine *bool) { - prec := x.Op.Precedence(); + prec := x.Op.Precedence() if prec < prec1 { // parenthesis needed // Note: The parser inserts an ast.ParenExpr node; thus this case // can only occur if the AST is created in a different way. - p.print(token.LPAREN); - p.expr0(x, depth-1, multiLine); // parentheses undo one level of depth - p.print(token.RPAREN); - return; + p.print(token.LPAREN) + p.expr0(x, depth-1, multiLine) // parentheses undo one level of depth + p.print(token.RPAREN) + return } - printBlank := prec < cutoff; + printBlank := prec < cutoff - ws := indent; - p.expr1(x.X, prec, depth+diffPrec(x.X, prec), 0, multiLine); + ws := indent + p.expr1(x.X, prec, depth+diffPrec(x.X, prec), 0, multiLine) if printBlank { p.print(blank) } - xline := p.pos.Line; // before the operator (it may be on the next line!) - yline := x.Y.Pos().Line; - p.print(p.beforeComment(x.OpPos), x.Op); + xline := p.pos.Line // before the operator (it may be on the next line!) + yline := x.Y.Pos().Line + p.print(p.beforeComment(x.OpPos), x.Op) if xline != yline && xline > 0 && yline > 0 { // at least one line break, but respect an extra empty line // in the source if p.linebreak(yline, 1, 2, ws, true) { - ws = ignore; - *multiLine = true; - printBlank = false; // no blank after line break + ws = ignore + *multiLine = true + printBlank = false // no blank after line break } } if printBlank { p.print(blank) } - p.expr1(x.Y, prec+1, depth+1, 0, multiLine); + p.expr1(x.Y, prec+1, depth+1, 0, multiLine) if ws == ignore { p.print(unindent) } @@ -625,15 +625,15 @@ func (p *printer) binaryExpr(x *ast.BinaryExpr, prec1, cutoff, depth int, multiL func isBinary(expr ast.Expr) bool { - _, ok := expr.(*ast.BinaryExpr); - return ok; + _, ok := expr.(*ast.BinaryExpr) + return ok } // Returns true if a separating semicolon is optional. // Sets multiLine to true if the expression spans multiple lines. func (p *printer) expr1(expr ast.Expr, prec1, depth int, ctxt exprContext, multiLine *bool) (optSemi bool) { - p.print(expr.Pos()); + p.print(expr.Pos()) switch x := expr.(type) { case *ast.BadExpr: @@ -644,44 +644,44 @@ func (p *printer) expr1(expr ast.Expr, prec1, depth int, ctxt exprContext, multi case *ast.BinaryExpr: if depth < 1 { - p.internalError("depth < 1:", depth); - depth = 1; + p.internalError("depth < 1:", depth) + depth = 1 } - p.binaryExpr(x, prec1, cutoff(x, depth), depth, multiLine); + p.binaryExpr(x, prec1, cutoff(x, depth), depth, multiLine) case *ast.KeyValueExpr: - p.expr(x.Key, multiLine); - p.print(x.Colon, token.COLON, blank); - p.expr(x.Value, multiLine); + p.expr(x.Key, multiLine) + p.print(x.Colon, token.COLON, blank) + p.expr(x.Value, multiLine) case *ast.StarExpr: - const prec = token.UnaryPrec; + const prec = token.UnaryPrec if prec < prec1 { // parenthesis needed - p.print(token.LPAREN); - p.print(token.MUL); - optSemi = p.expr(x.X, multiLine); - p.print(token.RPAREN); + p.print(token.LPAREN) + p.print(token.MUL) + optSemi = p.expr(x.X, multiLine) + p.print(token.RPAREN) } else { // no parenthesis needed - p.print(token.MUL); - optSemi = p.expr(x.X, multiLine); + p.print(token.MUL) + optSemi = p.expr(x.X, multiLine) } case *ast.UnaryExpr: - const prec = token.UnaryPrec; + const prec = token.UnaryPrec if prec < prec1 { // parenthesis needed - p.print(token.LPAREN); - p.expr(x, multiLine); - p.print(token.RPAREN); + p.print(token.LPAREN) + p.expr(x, multiLine) + p.print(token.RPAREN) } else { // no parenthesis needed - p.print(x.Op); + p.print(x.Op) if x.Op == token.RANGE { p.print(blank) } - p.expr1(x.X, prec, depth, 0, multiLine); + p.expr1(x.X, prec, depth, 0, multiLine) } case *ast.BasicLit: @@ -691,41 +691,41 @@ func (p *printer) expr1(expr ast.Expr, prec1, depth int, ctxt exprContext, multi p.stringList(x.Strings, multiLine) case *ast.FuncLit: - p.expr(x.Type, multiLine); - p.funcBody(x.Body, distance(x.Type.Pos(), p.pos), true, multiLine); + p.expr(x.Type, multiLine) + p.funcBody(x.Body, distance(x.Type.Pos(), p.pos), true, multiLine) case *ast.ParenExpr: - p.print(token.LPAREN); - p.expr0(x.X, depth-1, multiLine); // parentheses undo one level of depth - p.print(x.Rparen, token.RPAREN); + p.print(token.LPAREN) + p.expr0(x.X, depth-1, multiLine) // parentheses undo one level of depth + p.print(x.Rparen, token.RPAREN) case *ast.SelectorExpr: - p.expr1(x.X, token.HighestPrec, depth, 0, multiLine); - p.print(token.PERIOD); - p.expr1(x.Sel, token.HighestPrec, depth, 0, multiLine); + p.expr1(x.X, token.HighestPrec, depth, 0, multiLine) + p.print(token.PERIOD) + p.expr1(x.Sel, token.HighestPrec, depth, 0, multiLine) case *ast.TypeAssertExpr: - p.expr1(x.X, token.HighestPrec, depth, 0, multiLine); - p.print(token.PERIOD, token.LPAREN); + p.expr1(x.X, token.HighestPrec, depth, 0, multiLine) + p.print(token.PERIOD, token.LPAREN) if x.Type != nil { p.expr(x.Type, multiLine) } else { p.print(token.TYPE) } - p.print(token.RPAREN); + p.print(token.RPAREN) case *ast.IndexExpr: // TODO(gri): should treat[] like parentheses and undo one level of depth - p.expr1(x.X, token.HighestPrec, 1, 0, multiLine); - p.print(token.LBRACK); - p.expr0(x.Index, depth+1, multiLine); - p.print(token.RBRACK); + p.expr1(x.X, token.HighestPrec, 1, 0, multiLine) + p.print(token.LBRACK) + p.expr0(x.Index, depth+1, multiLine) + p.print(token.RBRACK) case *ast.SliceExpr: // TODO(gri): should treat[] like parentheses and undo one level of depth - p.expr1(x.X, token.HighestPrec, 1, 0, multiLine); - p.print(token.LBRACK); - p.expr0(x.Index, depth+1, multiLine); + p.expr1(x.X, token.HighestPrec, 1, 0, multiLine) + p.print(token.LBRACK) + p.expr0(x.Index, depth+1, multiLine) // blanks around ":" if both sides exist and either side is a binary expression if depth <= 1 && x.End != nil && (isBinary(x.Index) || isBinary(x.End)) { p.print(blank, token.COLON, blank) @@ -735,24 +735,24 @@ func (p *printer) expr1(expr ast.Expr, prec1, depth int, ctxt exprContext, multi if x.End != nil { p.expr0(x.End, depth+1, multiLine) } - p.print(token.RBRACK); + p.print(token.RBRACK) case *ast.CallExpr: if len(x.Args) > 1 { depth++ } - p.expr1(x.Fun, token.HighestPrec, depth, 0, multiLine); - p.print(x.Lparen, token.LPAREN); - p.exprList(x.Lparen, x.Args, depth, commaSep, multiLine); - p.print(x.Rparen, token.RPAREN); + p.expr1(x.Fun, token.HighestPrec, depth, 0, multiLine) + p.print(x.Lparen, token.LPAREN) + p.exprList(x.Lparen, x.Args, depth, commaSep, multiLine) + p.print(x.Rparen, token.RPAREN) case *ast.CompositeLit: - p.expr1(x.Type, token.HighestPrec, depth, compositeLit, multiLine); - mode := commaSep | commaTerm; + p.expr1(x.Type, token.HighestPrec, depth, compositeLit, multiLine) + mode := commaSep | commaTerm if compositeLitBlank { // add blank padding around composite literal // contents for a less dense look - mode |= blankStart | blankEnd; + mode |= blankStart | blankEnd if x.Lbrace.Line < x.Rbrace.Line { // add a blank before the opening { for multi-line composites // TODO(gri): for now this decision is made by looking at the @@ -761,40 +761,40 @@ func (p *printer) expr1(expr ast.Expr, prec1, depth int, ctxt exprContext, multi p.print(blank) } } - p.print(x.Lbrace, token.LBRACE); - p.exprList(x.Lbrace, x.Elts, 1, mode, multiLine); - p.print(x.Rbrace, token.RBRACE); + p.print(x.Lbrace, token.LBRACE) + p.exprList(x.Lbrace, x.Elts, 1, mode, multiLine) + p.print(x.Rbrace, token.RBRACE) case *ast.Ellipsis: p.print(token.ELLIPSIS) case *ast.ArrayType: - p.print(token.LBRACK); + p.print(token.LBRACK) if x.Len != nil { p.expr(x.Len, multiLine) } - p.print(token.RBRACK); - optSemi = p.expr(x.Elt, multiLine); + p.print(token.RBRACK) + optSemi = p.expr(x.Elt, multiLine) case *ast.StructType: - p.print(token.STRUCT); - p.fieldList(x.Lbrace, x.Fields, x.Rbrace, x.Incomplete, ctxt|structType); - optSemi = true; + p.print(token.STRUCT) + p.fieldList(x.Lbrace, x.Fields, x.Rbrace, x.Incomplete, ctxt|structType) + optSemi = true case *ast.FuncType: - p.print(token.FUNC); - optSemi = p.signature(x.Params, x.Results, multiLine); + p.print(token.FUNC) + optSemi = p.signature(x.Params, x.Results, multiLine) case *ast.InterfaceType: - p.print(token.INTERFACE); - p.fieldList(x.Lbrace, x.Methods, x.Rbrace, x.Incomplete, ctxt); - optSemi = true; + p.print(token.INTERFACE) + p.fieldList(x.Lbrace, x.Methods, x.Rbrace, x.Incomplete, ctxt) + optSemi = true case *ast.MapType: - p.print(token.MAP, token.LBRACK); - p.expr(x.Key, multiLine); - p.print(token.RBRACK); - optSemi = p.expr(x.Value, multiLine); + p.print(token.MAP, token.LBRACK) + p.expr(x.Key, multiLine) + p.print(token.RBRACK) + optSemi = p.expr(x.Value, multiLine) case *ast.ChanType: switch x.Dir { @@ -805,14 +805,14 @@ func (p *printer) expr1(expr ast.Expr, prec1, depth int, ctxt exprContext, multi case ast.SEND: p.print(token.CHAN, token.ARROW) } - p.print(blank); - optSemi = p.expr(x.Value, multiLine); + p.print(blank) + optSemi = p.expr(x.Value, multiLine) default: panic("unreachable") } - return; + return } @@ -824,15 +824,15 @@ func (p *printer) expr0(x ast.Expr, depth int, multiLine *bool) (optSemi bool) { // Returns true if a separating semicolon is optional. // Sets multiLine to true if the expression spans multiple lines. func (p *printer) expr(x ast.Expr, multiLine *bool) (optSemi bool) { - const depth = 1; - return p.expr1(x, token.LowestPrec, depth, 0, multiLine); + const depth = 1 + return p.expr1(x, token.LowestPrec, depth, 0, multiLine) } // ---------------------------------------------------------------------------- // Statements -const maxStmtNewlines = 2 // maximum number of newlines between statements +const maxStmtNewlines = 2 // maximum number of newlines between statements // Print the statement list indented, but without a newline after the last statement. // Extra line breaks between statements in the source are respected but at most one @@ -842,12 +842,12 @@ func (p *printer) stmtList(list []ast.Stmt, _indent int) { if _indent > 0 { p.print(indent) } - var multiLine bool; + var multiLine bool for i, s := range list { // _indent == 0 only for lists of switch/select case clauses; // in those cases each clause is a new section - p.linebreak(s.Pos().Line, 1, maxStmtNewlines, ignore, i == 0 || _indent == 0 || multiLine); - multiLine = false; + p.linebreak(s.Pos().Line, 1, maxStmtNewlines, ignore, i == 0 || _indent == 0 || multiLine) + multiLine = false if !p.stmt(s, &multiLine) && len(list) > 1 && p.Mode&NoSemis == 0 { p.print(token.SEMICOLON) } @@ -876,10 +876,10 @@ func (p *printer) block(s *ast.BlockStmt, indent int, moveComments bool) { } else { p.print(s.Pos()) } - p.print(token.LBRACE); - p.stmtList(s.List, indent); - p.linebreak(s.Rbrace.Line, 1, maxStmtNewlines, ignore, true); - p.print(s.Rbrace, token.RBRACE); + p.print(token.LBRACE) + p.stmtList(s.List, indent) + p.linebreak(s.Rbrace.Line, 1, maxStmtNewlines, ignore, true) + p.print(s.Rbrace, token.RBRACE) } @@ -890,18 +890,18 @@ func stripParens(x ast.Expr) ast.Expr { if px, hasParens := x.(*ast.ParenExpr); hasParens { return stripParens(px.X) } - return x; + return x } func (p *printer) controlClause(isForStmt bool, init ast.Stmt, expr ast.Expr, post ast.Stmt) { - p.print(blank); - needsBlank := false; + p.print(blank) + needsBlank := false if init == nil && post == nil { // no semicolons required if expr != nil { - p.expr(stripParens(expr), ignoreMultiLine); - needsBlank = true; + p.expr(stripParens(expr), ignoreMultiLine) + needsBlank = true } } else { // all semicolons required @@ -909,17 +909,17 @@ func (p *printer) controlClause(isForStmt bool, init ast.Stmt, expr ast.Expr, po if init != nil { p.stmt(init, ignoreMultiLine) } - p.print(token.SEMICOLON, blank); + p.print(token.SEMICOLON, blank) if expr != nil { - p.expr(stripParens(expr), ignoreMultiLine); - needsBlank = true; + p.expr(stripParens(expr), ignoreMultiLine) + needsBlank = true } if isForStmt { - p.print(token.SEMICOLON, blank); - needsBlank = false; + p.print(token.SEMICOLON, blank) + needsBlank = false if post != nil { - p.stmt(post, ignoreMultiLine); - needsBlank = true; + p.stmt(post, ignoreMultiLine) + needsBlank = true } } } @@ -932,15 +932,15 @@ func (p *printer) controlClause(isForStmt bool, init ast.Stmt, expr ast.Expr, po // Returns true if a separating semicolon is optional. // Sets multiLine to true if the statements spans multiple lines. func (p *printer) stmt(stmt ast.Stmt, multiLine *bool) (optSemi bool) { - p.print(stmt.Pos()); + p.print(stmt.Pos()) switch s := stmt.(type) { case *ast.BadStmt: p.print("BadStmt") case *ast.DeclStmt: - p.decl(s.Decl, inStmtList, multiLine); - optSemi = true; // decl prints terminating semicolon if necessary + p.decl(s.Decl, inStmtList, multiLine) + optSemi = true // decl prints terminating semicolon if necessary case *ast.EmptyStmt: // nothing to do @@ -949,164 +949,164 @@ func (p *printer) stmt(stmt ast.Stmt, multiLine *bool) (optSemi bool) { // a "correcting" unindent immediately following a line break // is applied before the line break if there is no comment // between (see writeWhitespace) - p.print(unindent); - p.expr(s.Label, multiLine); - p.print(token.COLON, vtab, indent); - p.linebreak(s.Stmt.Pos().Line, 0, 1, ignore, true); - optSemi = p.stmt(s.Stmt, multiLine); + p.print(unindent) + p.expr(s.Label, multiLine) + p.print(token.COLON, vtab, indent) + p.linebreak(s.Stmt.Pos().Line, 0, 1, ignore, true) + optSemi = p.stmt(s.Stmt, multiLine) case *ast.ExprStmt: - const depth = 1; - p.expr0(s.X, depth, multiLine); + const depth = 1 + p.expr0(s.X, depth, multiLine) case *ast.IncDecStmt: - const depth = 1; - p.expr0(s.X, depth+1, multiLine); - p.print(s.Tok); + const depth = 1 + p.expr0(s.X, depth+1, multiLine) + p.print(s.Tok) case *ast.AssignStmt: - var depth = 1; + var depth = 1 if len(s.Lhs) > 1 && len(s.Rhs) > 1 { depth++ } - p.exprList(s.Pos(), s.Lhs, depth, commaSep, multiLine); - p.print(blank, s.TokPos, s.Tok); - p.exprList(s.TokPos, s.Rhs, depth, blankStart|commaSep, multiLine); + p.exprList(s.Pos(), s.Lhs, depth, commaSep, multiLine) + p.print(blank, s.TokPos, s.Tok) + p.exprList(s.TokPos, s.Rhs, depth, blankStart|commaSep, multiLine) case *ast.GoStmt: - p.print(token.GO, blank); - p.expr(s.Call, multiLine); + p.print(token.GO, blank) + p.expr(s.Call, multiLine) case *ast.DeferStmt: - p.print(token.DEFER, blank); - p.expr(s.Call, multiLine); + p.print(token.DEFER, blank) + p.expr(s.Call, multiLine) case *ast.ReturnStmt: - p.print(token.RETURN); + p.print(token.RETURN) if s.Results != nil { p.exprList(s.Pos(), s.Results, 1, blankStart|commaSep, multiLine) } case *ast.BranchStmt: - p.print(s.Tok); + p.print(s.Tok) if s.Label != nil { - p.print(blank); - p.expr(s.Label, multiLine); + p.print(blank) + p.expr(s.Label, multiLine) } case *ast.BlockStmt: - p.block(s, 1, false); - *multiLine = true; - optSemi = true; + p.block(s, 1, false) + *multiLine = true + optSemi = true case *ast.IfStmt: - p.print(token.IF); - p.controlClause(false, s.Init, s.Cond, nil); - p.block(s.Body, 1, true); - *multiLine = true; - optSemi = true; + p.print(token.IF) + p.controlClause(false, s.Init, s.Cond, nil) + p.block(s.Body, 1, true) + *multiLine = true + optSemi = true if s.Else != nil { - p.print(blank, token.ELSE, blank); + p.print(blank, token.ELSE, blank) switch s.Else.(type) { case *ast.BlockStmt, *ast.IfStmt: optSemi = p.stmt(s.Else, ignoreMultiLine) default: - p.print(token.LBRACE, indent, formfeed); - p.stmt(s.Else, ignoreMultiLine); - p.print(unindent, formfeed, token.RBRACE); + p.print(token.LBRACE, indent, formfeed) + p.stmt(s.Else, ignoreMultiLine) + p.print(unindent, formfeed, token.RBRACE) } } case *ast.CaseClause: if s.Values != nil { - p.print(token.CASE); - p.exprList(s.Pos(), s.Values, 1, blankStart|commaSep, multiLine); + p.print(token.CASE) + p.exprList(s.Pos(), s.Values, 1, blankStart|commaSep, multiLine) } else { p.print(token.DEFAULT) } - p.print(s.Colon, token.COLON); - p.stmtList(s.Body, 1); - optSemi = true; // "block" without {}'s + p.print(s.Colon, token.COLON) + p.stmtList(s.Body, 1) + optSemi = true // "block" without {}'s case *ast.SwitchStmt: - p.print(token.SWITCH); - p.controlClause(false, s.Init, s.Tag, nil); - p.block(s.Body, 0, true); - *multiLine = true; - optSemi = true; + p.print(token.SWITCH) + p.controlClause(false, s.Init, s.Tag, nil) + p.block(s.Body, 0, true) + *multiLine = true + optSemi = true case *ast.TypeCaseClause: if s.Types != nil { - p.print(token.CASE); - p.exprList(s.Pos(), s.Types, 1, blankStart|commaSep, multiLine); + p.print(token.CASE) + p.exprList(s.Pos(), s.Types, 1, blankStart|commaSep, multiLine) } else { p.print(token.DEFAULT) } - p.print(s.Colon, token.COLON); - p.stmtList(s.Body, 1); - optSemi = true; // "block" without {}'s + p.print(s.Colon, token.COLON) + p.stmtList(s.Body, 1) + optSemi = true // "block" without {}'s case *ast.TypeSwitchStmt: - p.print(token.SWITCH); + p.print(token.SWITCH) if s.Init != nil { - p.print(blank); - p.stmt(s.Init, ignoreMultiLine); - p.print(token.SEMICOLON); + p.print(blank) + p.stmt(s.Init, ignoreMultiLine) + p.print(token.SEMICOLON) } - p.print(blank); - p.stmt(s.Assign, ignoreMultiLine); - p.print(blank); - p.block(s.Body, 0, true); - *multiLine = true; - optSemi = true; + p.print(blank) + p.stmt(s.Assign, ignoreMultiLine) + p.print(blank) + p.block(s.Body, 0, true) + *multiLine = true + optSemi = true case *ast.CommClause: if s.Rhs != nil { - p.print(token.CASE, blank); + p.print(token.CASE, blank) if s.Lhs != nil { - p.expr(s.Lhs, multiLine); - p.print(blank, s.Tok, blank); + p.expr(s.Lhs, multiLine) + p.print(blank, s.Tok, blank) } - p.expr(s.Rhs, multiLine); + p.expr(s.Rhs, multiLine) } else { p.print(token.DEFAULT) } - p.print(s.Colon, token.COLON); - p.stmtList(s.Body, 1); - optSemi = true; // "block" without {}'s + p.print(s.Colon, token.COLON) + p.stmtList(s.Body, 1) + optSemi = true // "block" without {}'s case *ast.SelectStmt: - p.print(token.SELECT, blank); - p.block(s.Body, 0, false); - *multiLine = true; - optSemi = true; + p.print(token.SELECT, blank) + p.block(s.Body, 0, false) + *multiLine = true + optSemi = true case *ast.ForStmt: - p.print(token.FOR); - p.controlClause(true, s.Init, s.Cond, s.Post); - p.block(s.Body, 1, true); - *multiLine = true; - optSemi = true; + p.print(token.FOR) + p.controlClause(true, s.Init, s.Cond, s.Post) + p.block(s.Body, 1, true) + *multiLine = true + optSemi = true case *ast.RangeStmt: - p.print(token.FOR, blank); - p.expr(s.Key, multiLine); + p.print(token.FOR, blank) + p.expr(s.Key, multiLine) if s.Value != nil { - p.print(token.COMMA, blank); - p.expr(s.Value, multiLine); + p.print(token.COMMA, blank) + p.expr(s.Value, multiLine) } - p.print(blank, s.TokPos, s.Tok, blank, token.RANGE, blank); - p.expr(s.X, multiLine); - p.print(blank); - p.block(s.Body, 1, true); - *multiLine = true; - optSemi = true; + p.print(blank, s.TokPos, s.Tok, blank, token.RANGE, blank) + p.expr(s.X, multiLine) + p.print(blank) + p.block(s.Body, 1, true) + *multiLine = true + optSemi = true default: panic("unreachable") } - return; + return } @@ -1116,9 +1116,9 @@ func (p *printer) stmt(stmt ast.Stmt, multiLine *bool) (optSemi bool) { type declContext uint const ( - atTop declContext = iota; - inGroup; - inStmtList; + atTop declContext = iota + inGroup + inStmtList ) // The parameter n is the number of specs in the group; context specifies @@ -1128,25 +1128,25 @@ const ( // func (p *printer) spec(spec ast.Spec, n int, context declContext, multiLine *bool) { var ( - optSemi bool; // true if a semicolon is optional - comment *ast.CommentGroup; // a line comment, if any - extraTabs int; // number of extra tabs before comment, if any + optSemi bool // true if a semicolon is optional + comment *ast.CommentGroup // a line comment, if any + extraTabs int // number of extra tabs before comment, if any ) switch s := spec.(type) { case *ast.ImportSpec: - p.leadComment(s.Doc); + p.leadComment(s.Doc) if s.Name != nil { - p.expr(s.Name, multiLine); - p.print(blank); - p.moveCommentsAfter(s.Path[0].Pos()); + p.expr(s.Name, multiLine) + p.print(blank) + p.moveCommentsAfter(s.Path[0].Pos()) } - p.expr(&ast.StringList{s.Path}, multiLine); - comment = s.Comment; + p.expr(&ast.StringList{s.Path}, multiLine) + comment = s.Comment case *ast.ValueSpec: - p.leadComment(s.Doc); - p.identList(s.Names, multiLine); // always present + p.leadComment(s.Doc) + p.identList(s.Names, multiLine) // always present if s.Values != nil { p.moveCommentsAfter(s.Values[0].Pos()) } else if s.Type != nil { @@ -1154,44 +1154,44 @@ func (p *printer) spec(spec ast.Spec, n int, context declContext, multiLine *boo } if n == 1 { if s.Type != nil { - p.print(blank); - optSemi = p.expr(s.Type, multiLine); + p.print(blank) + optSemi = p.expr(s.Type, multiLine) } if s.Values != nil { - p.print(blank, token.ASSIGN); - p.exprList(noPos, s.Values, 1, blankStart|commaSep, multiLine); - optSemi = false; + p.print(blank, token.ASSIGN) + p.exprList(noPos, s.Values, 1, blankStart|commaSep, multiLine) + optSemi = false } } else { - extraTabs = 2; + extraTabs = 2 if s.Type != nil || s.Values != nil { p.print(vtab) } if s.Type != nil { - optSemi = p.expr(s.Type, multiLine); - extraTabs = 1; + optSemi = p.expr(s.Type, multiLine) + extraTabs = 1 } if s.Values != nil { - p.print(vtab); - p.print(token.ASSIGN); - p.exprList(noPos, s.Values, 1, blankStart|commaSep, multiLine); - optSemi = false; - extraTabs = 0; + p.print(vtab) + p.print(token.ASSIGN) + p.exprList(noPos, s.Values, 1, blankStart|commaSep, multiLine) + optSemi = false + extraTabs = 0 } } - comment = s.Comment; + comment = s.Comment case *ast.TypeSpec: - p.leadComment(s.Doc); - p.expr(s.Name, multiLine); - p.moveCommentsAfter(s.Type.Pos()); + p.leadComment(s.Doc) + p.expr(s.Name, multiLine) + p.moveCommentsAfter(s.Type.Pos()) if n == 1 { p.print(blank) } else { p.print(vtab) } - optSemi = p.expr(s.Type, multiLine); - comment = s.Comment; + optSemi = p.expr(s.Type, multiLine) + comment = s.Comment default: panic("unreachable") @@ -1205,33 +1205,33 @@ func (p *printer) spec(spec ast.Spec, n int, context declContext, multiLine *boo for ; extraTabs > 0; extraTabs-- { p.print(vtab) } - p.lineComment(comment); + p.lineComment(comment) } } // Sets multiLine to true if the declaration spans multiple lines. func (p *printer) genDecl(d *ast.GenDecl, context declContext, multiLine *bool) { - p.leadComment(d.Doc); - p.print(d.Pos(), d.Tok, blank); + p.leadComment(d.Doc) + p.print(d.Pos(), d.Tok, blank) if d.Lparen.IsValid() { // group of parenthesized declarations - p.print(d.Lparen, token.LPAREN); + p.print(d.Lparen, token.LPAREN) if len(d.Specs) > 0 { - p.print(indent, formfeed); - var ml bool; + p.print(indent, formfeed) + var ml bool for i, s := range d.Specs { if i > 0 { p.linebreak(s.Pos().Line, 1, 2, ignore, ml) } - ml = false; - p.spec(s, len(d.Specs), inGroup, &ml); + ml = false + p.spec(s, len(d.Specs), inGroup, &ml) } - p.print(unindent, formfeed); - *multiLine = true; + p.print(unindent, formfeed) + *multiLine = true } - p.print(d.Rparen, token.RPAREN); + p.print(d.Rparen, token.RPAREN) } else { // single declaration @@ -1246,12 +1246,12 @@ func (p *printer) genDecl(d *ast.GenDecl, context declContext, multiLine *bool) // any control chars. Otherwise, the result is > maxSize. // func (p *printer) nodeSize(n ast.Node, maxSize int) (size int) { - size = maxSize + 1; // assume n doesn't fit + size = maxSize + 1 // assume n doesn't fit // nodeSize computation must be indendent of particular // style so that we always get the same decision; print // in RawFormat - cfg := Config{Mode: RawFormat}; - var buf bytes.Buffer; + cfg := Config{Mode: RawFormat} + var buf bytes.Buffer if _, err := cfg.Fprint(&buf, n); err != nil { return } @@ -1261,23 +1261,23 @@ func (p *printer) nodeSize(n ast.Node, maxSize int) (size int) { return } } - size = buf.Len(); // n fits + size = buf.Len() // n fits } - return; + return } func (p *printer) isOneLineFunc(b *ast.BlockStmt, headerSize int) bool { - const maxSize = 90; // adjust as appropriate, this is an approximate value - bodySize := 0; + const maxSize = 90 // adjust as appropriate, this is an approximate value + bodySize := 0 switch { case len(b.List) > 1 || p.commentBefore(b.Rbrace): - return false // too many statements or there is a comment - all bets are off + return false // too many statements or there is a comment - all bets are off case len(b.List) == 1: bodySize = p.nodeSize(b.List[0], maxSize) } // require both headers and overall size to be not "too large" - return headerSize <= maxSize/2 && headerSize+bodySize <= maxSize; + return headerSize <= maxSize/2 && headerSize+bodySize <= maxSize } @@ -1288,23 +1288,23 @@ func (p *printer) funcBody(b *ast.BlockStmt, headerSize int, isLit bool, multiLi } if p.isOneLineFunc(b, headerSize) { - sep := vtab; + sep := vtab if isLit { sep = blank } if len(b.List) > 0 { - p.print(sep, b.Pos(), token.LBRACE, blank); - p.stmt(b.List[0], ignoreMultiLine); - p.print(blank, b.Rbrace, token.RBRACE); + p.print(sep, b.Pos(), token.LBRACE, blank) + p.stmt(b.List[0], ignoreMultiLine) + p.print(blank, b.Rbrace, token.RBRACE) } else { p.print(sep, b.Pos(), token.LBRACE, b.Rbrace, token.RBRACE) } - return; + return } - p.print(blank); - p.block(b, 1, true); - *multiLine = true; + p.print(blank) + p.block(b, 1, true) + *multiLine = true } @@ -1315,27 +1315,27 @@ func distance(from, to token.Position) int { if from.IsValid() && to.IsValid() && from.Line == to.Line { return to.Column - from.Column } - return 1 << 30; + return 1 << 30 } // Sets multiLine to true if the declaration spans multiple lines. func (p *printer) funcDecl(d *ast.FuncDecl, multiLine *bool) { - p.leadComment(d.Doc); - p.print(d.Pos(), token.FUNC, blank); + p.leadComment(d.Doc) + p.print(d.Pos(), token.FUNC, blank) if recv := d.Recv; recv != nil { // method: print receiver - p.print(token.LPAREN); + p.print(token.LPAREN) if len(recv.Names) > 0 { - p.expr(recv.Names[0], multiLine); - p.print(blank); + p.expr(recv.Names[0], multiLine) + p.print(blank) } - p.expr(recv.Type, multiLine); - p.print(token.RPAREN, blank); + p.expr(recv.Type, multiLine) + p.print(token.RPAREN, blank) } - p.expr(d.Name, multiLine); - p.signature(d.Type.Params, d.Type.Results, multiLine); - p.funcBody(d.Body, distance(d.Pos(), p.pos), false, multiLine); + p.expr(d.Name, multiLine) + p.signature(d.Type.Params, d.Type.Results, multiLine) + p.funcBody(d.Body, distance(d.Pos(), p.pos), false, multiLine) } @@ -1357,40 +1357,40 @@ func (p *printer) decl(decl ast.Decl, context declContext, multiLine *bool) { // ---------------------------------------------------------------------------- // Files -const maxDeclNewlines = 3 // maximum number of newlines between declarations +const maxDeclNewlines = 3 // maximum number of newlines between declarations func declToken(decl ast.Decl) (tok token.Token) { - tok = token.ILLEGAL; + tok = token.ILLEGAL switch d := decl.(type) { case *ast.GenDecl: tok = d.Tok case *ast.FuncDecl: tok = token.FUNC } - return; + return } func (p *printer) file(src *ast.File) { - p.leadComment(src.Doc); - p.print(src.Pos(), token.PACKAGE, blank); - p.expr(src.Name, ignoreMultiLine); + p.leadComment(src.Doc) + p.print(src.Pos(), token.PACKAGE, blank) + p.expr(src.Name, ignoreMultiLine) if len(src.Decls) > 0 { - tok := token.ILLEGAL; + tok := token.ILLEGAL for _, d := range src.Decls { - prev := tok; - tok = declToken(d); + prev := tok + tok = declToken(d) // if the declaration token changed (e.g., from CONST to TYPE) // print an empty line between top-level declarations - min := 1; + min := 1 if prev != tok { min = 2 } - p.linebreak(d.Pos().Line, min, maxDeclNewlines, ignore, false); - p.decl(d, atTop, ignoreMultiLine); + p.linebreak(d.Pos().Line, min, maxDeclNewlines, ignore, false) + p.decl(d, atTop, ignoreMultiLine) } } - p.print(newline); + p.print(newline) } diff --git a/src/pkg/go/printer/printer.go b/src/pkg/go/printer/printer.go index 50f0007a6..994dabaa8 100644 --- a/src/pkg/go/printer/printer.go +++ b/src/pkg/go/printer/printer.go @@ -6,50 +6,50 @@ package printer import ( - "bytes"; - "fmt"; - "go/ast"; - "go/token"; - "io"; - "os"; - "reflect"; - "runtime"; - "strings"; - "tabwriter"; + "bytes" + "fmt" + "go/ast" + "go/token" + "io" + "os" + "reflect" + "runtime" + "strings" + "tabwriter" ) const ( - debug = false; // enable for debugging - maxNewlines = 3; // maximum vertical white space + debug = false // enable for debugging + maxNewlines = 3 // maximum vertical white space ) type whiteSpace int const ( - ignore = whiteSpace(0); - blank = whiteSpace(' '); - vtab = whiteSpace('\v'); - newline = whiteSpace('\n'); - formfeed = whiteSpace('\f'); - indent = whiteSpace('>'); - unindent = whiteSpace('<'); + ignore = whiteSpace(0) + blank = whiteSpace(' ') + vtab = whiteSpace('\v') + newline = whiteSpace('\n') + formfeed = whiteSpace('\f') + indent = whiteSpace('>') + unindent = whiteSpace('<') ) var ( - esc = []byte{tabwriter.Escape}; - htab = []byte{'\t'}; - htabs = [...]byte{'\t', '\t', '\t', '\t', '\t', '\t', '\t', '\t'}; - newlines = [...]byte{'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'}; // more than maxNewlines - formfeeds = [...]byte{'\f', '\f', '\f', '\f', '\f', '\f', '\f', '\f'}; // more than maxNewlines - - esc_quot = strings.Bytes("""); // shorter than """ - esc_apos = strings.Bytes("'"); // shorter than "'" - esc_amp = strings.Bytes("&"); - esc_lt = strings.Bytes("<"); - esc_gt = strings.Bytes(">"); + esc = []byte{tabwriter.Escape} + htab = []byte{'\t'} + htabs = [...]byte{'\t', '\t', '\t', '\t', '\t', '\t', '\t', '\t'} + newlines = [...]byte{'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'} // more than maxNewlines + formfeeds = [...]byte{'\f', '\f', '\f', '\f', '\f', '\f', '\f', '\f'} // more than maxNewlines + + esc_quot = strings.Bytes(""") // shorter than """ + esc_apos = strings.Bytes("'") // shorter than "'" + esc_amp = strings.Bytes("&") + esc_lt = strings.Bytes("<") + esc_gt = strings.Bytes(">") ) @@ -63,49 +63,49 @@ var ignoreMultiLine = new(bool) type printer struct { // Configuration (does not change after initialization) - output io.Writer; - Config; - errors chan os.Error; + output io.Writer + Config + errors chan os.Error // Current state - written int; // number of bytes written - indent int; // current indentation - escape bool; // true if in escape sequence + written int // number of bytes written + indent int // current indentation + escape bool // true if in escape sequence // Buffered whitespace - buffer []whiteSpace; + buffer []whiteSpace // The (possibly estimated) position in the generated output; // in AST space (i.e., pos is set whenever a token position is // known accurately, and updated dependending on what has been // written) - pos token.Position; + pos token.Position // The value of pos immediately after the last item has been // written using writeItem. - last token.Position; + last token.Position // HTML support - lastTaggedLine int; // last line for which a line tag was written + lastTaggedLine int // last line for which a line tag was written // The list of comments; or nil. - comment *ast.CommentGroup; + comment *ast.CommentGroup } func (p *printer) init(output io.Writer, cfg *Config) { - p.output = output; - p.Config = *cfg; - p.errors = make(chan os.Error); - p.buffer = make([]whiteSpace, 0, 16); // whitespace sequences are short + p.output = output + p.Config = *cfg + p.errors = make(chan os.Error) + p.buffer = make([]whiteSpace, 0, 16) // whitespace sequences are short } func (p *printer) internalError(msg ...) { if debug { - fmt.Print(p.pos.String() + ": "); - fmt.Println(msg); - panic(); + fmt.Print(p.pos.String() + ": ") + fmt.Println(msg) + panic() } } @@ -114,11 +114,11 @@ func (p *printer) internalError(msg ...) { // write0 does not indent after newlines, and does not HTML-escape or update p.pos. // func (p *printer) write0(data []byte) { - n, err := p.output.Write(data); - p.written += n; + n, err := p.output.Write(data) + p.written += n if err != nil { - p.errors <- err; - runtime.Goexit(); + p.errors <- err + runtime.Goexit() } } @@ -128,43 +128,43 @@ func (p *printer) write0(data []byte) { // escapes characters if GenHTML is set. It updates p.pos as a side-effect. // func (p *printer) write(data []byte) { - i0 := 0; + i0 := 0 for i, b := range data { switch b { case '\n', '\f': // write segment ending in b - p.write0(data[i0 : i+1]); + p.write0(data[i0 : i+1]) // update p.pos - p.pos.Offset += i + 1 - i0; - p.pos.Line++; - p.pos.Column = 1; + p.pos.Offset += i + 1 - i0 + p.pos.Line++ + p.pos.Column = 1 if !p.escape { // write indentation // use "hard" htabs - indentation columns // must not be discarded by the tabwriter - j := p.indent; + j := p.indent for ; j > len(htabs); j -= len(htabs) { p.write0(&htabs) } - p.write0(htabs[0:j]); + p.write0(htabs[0:j]) // update p.pos - p.pos.Offset += p.indent; - p.pos.Column += p.indent; + p.pos.Offset += p.indent + p.pos.Column += p.indent } // next segment start - i0 = i + 1; + i0 = i + 1 case '"', '\'', '&', '<', '>': if p.Mode&GenHTML != 0 { // write segment ending in b - p.write0(data[i0:i]); + p.write0(data[i0:i]) // write HTML-escaped b - var esc []byte; + var esc []byte switch b { case '"': esc = esc_quot @@ -177,15 +177,15 @@ func (p *printer) write(data []byte) { case '>': esc = esc_gt } - p.write0(esc); + p.write0(esc) // update p.pos - d := i + 1 - i0; - p.pos.Offset += d; - p.pos.Column += d; + d := i + 1 - i0 + p.pos.Offset += d + p.pos.Column += d // next segment start - i0 = i + 1; + i0 = i + 1 } case tabwriter.Escape: @@ -194,12 +194,12 @@ func (p *printer) write(data []byte) { } // write remaining segment - p.write0(data[i0:]); + p.write0(data[i0:]) // update p.pos - d := len(data) - i0; - p.pos.Offset += d; - p.pos.Column += d; + d := len(data) - i0 + p.pos.Offset += d + p.pos.Column += d } @@ -208,7 +208,7 @@ func (p *printer) writeNewlines(n int) { if n > maxNewlines { n = maxNewlines } - p.write(newlines[0:n]); + p.write(newlines[0:n]) } } @@ -218,7 +218,7 @@ func (p *printer) writeFormfeeds(n int) { if n > maxNewlines { n = maxNewlines } - p.write(formfeeds[0:n]); + p.write(formfeeds[0:n]) } } @@ -229,7 +229,7 @@ func (p *printer) writeTaggedItem(data []byte, tag HTMLTag) { if tag.Start != "" { p.write0(strings.Bytes(tag.Start)) } - p.write(data); + p.write(data) // write end tag, if any if tag.End != "" { p.write0(strings.Bytes(tag.End)) @@ -245,7 +245,7 @@ func (p *printer) writeTaggedItem(data []byte, tag HTMLTag) { // immediately following the data. // func (p *printer) writeItem(pos token.Position, data []byte, tag HTMLTag) { - p.pos = pos; + p.pos = pos if debug { // do not update p.pos - use write0 p.write0(strings.Bytes(fmt.Sprintf("[%d:%d]", pos.Line, pos.Column))) @@ -255,14 +255,14 @@ func (p *printer) writeItem(pos token.Position, data []byte, tag HTMLTag) { // TODO(gri): should write line tags on each line at the start // will be more useful (e.g. to show line numbers) if p.Styler != nil && pos.Line > p.lastTaggedLine { - p.writeTaggedItem(p.Styler.LineTag(pos.Line)); - p.lastTaggedLine = pos.Line; + p.writeTaggedItem(p.Styler.LineTag(pos.Line)) + p.lastTaggedLine = pos.Line } - p.writeTaggedItem(data, tag); + p.writeTaggedItem(data, tag) } else { p.write(data) } - p.last = p.pos; + p.last = p.pos } @@ -284,28 +284,28 @@ func (p *printer) writeCommentPrefix(pos, next token.Position, isFirst, isKeywor if pos.Line == p.last.Line { // comment on the same line as last item: // separate with at least one separator - hasSep := false; + hasSep := false if isFirst { - j := 0; + j := 0 for i, ch := range p.buffer { switch ch { case blank: // ignore any blanks before a comment - p.buffer[i] = ignore; - continue; + p.buffer[i] = ignore + continue case vtab: // respect existing tabs - important // for proper formatting of commented structs - hasSep = true; - continue; + hasSep = true + continue case indent: // apply pending indentation continue } - j = i; - break; + j = i + break } - p.writeWhitespace(j); + p.writeWhitespace(j) } // make sure there is at least one separator if !hasSep { @@ -323,13 +323,13 @@ func (p *printer) writeCommentPrefix(pos, next token.Position, isFirst, isKeywor // comment on a different line: // separate with at least one line break if isFirst { - j := 0; + j := 0 for i, ch := range p.buffer { switch ch { case blank, vtab: // ignore any horizontal whitespace before line breaks - p.buffer[i] = ignore; - continue; + p.buffer[i] = ignore + continue case indent: // apply pending indentation continue @@ -347,31 +347,31 @@ func (p *printer) writeCommentPrefix(pos, next token.Position, isFirst, isKeywor // TODO(gri): may want to keep formfeed info in some cases p.buffer[i] = ignore } - j = i; - break; + j = i + break } - p.writeWhitespace(j); + p.writeWhitespace(j) } // use formfeeds to break columns before a comment; // this is analogous to using formfeeds to separate // individual lines of /*-style comments - p.writeFormfeeds(pos.Line - p.last.Line); + p.writeFormfeeds(pos.Line - p.last.Line) } } func (p *printer) writeCommentLine(comment *ast.Comment, pos token.Position, line []byte) { // line must pass through unchanged, bracket it with tabwriter.Escape - esc := []byte{tabwriter.Escape}; - line = bytes.Join([][]byte{esc, line, esc}, nil); + esc := []byte{tabwriter.Escape} + line = bytes.Join([][]byte{esc, line, esc}, nil) // apply styler, if any - var tag HTMLTag; + var tag HTMLTag if p.Styler != nil { line, tag = p.Styler.Comment(comment, line) } - p.writeItem(pos, line, tag); + p.writeItem(pos, line, tag) } @@ -382,7 +382,7 @@ func (p *printer) writeCommentLine(comment *ast.Comment, pos token.Position, lin // Split comment text into lines func split(text []byte) [][]byte { // count lines (comment text never ends in a newline) - n := 1; + n := 1 for _, c := range text { if c == '\n' { n++ @@ -390,19 +390,19 @@ func split(text []byte) [][]byte { } // split - lines := make([][]byte, n); - n = 0; - i := 0; + lines := make([][]byte, n) + n = 0 + i := 0 for j, c := range text { if c == '\n' { - lines[n] = text[i:j]; // exclude newline - i = j + 1; // discard newline - n++; + lines[n] = text[i:j] // exclude newline + i = j + 1 // discard newline + n++ } } - lines[n] = text[i:]; + lines[n] = text[i:] - return lines; + return lines } @@ -412,22 +412,22 @@ func isBlank(s []byte) bool { return false } } - return true; + return true } func commonPrefix(a, b []byte) []byte { - i := 0; + i := 0 for i < len(a) && i < len(b) && a[i] == b[i] && (a[i] <= ' ' || a[i] == '*') { i++ } - return a[0:i]; + return a[0:i] } func stripCommonPrefix(lines [][]byte) { if len(lines) < 2 { - return // at most one line - nothing to do + return // at most one line - nothing to do } // The heuristic in this function tries to handle a few @@ -441,7 +441,7 @@ func stripCommonPrefix(lines [][]byte) { // Compute maximum common white prefix of all but the first, // last, and blank lines, and replace blank lines with empty // lines (the first line starts with /* and has no prefix). - var prefix []byte; + var prefix []byte for i, line := range lines { switch { case i == 0 || i == len(lines)-1: @@ -458,14 +458,14 @@ func stripCommonPrefix(lines [][]byte) { /* * Check for vertical "line of stars" and correct prefix accordingly. */ - lineOfStars := false; + lineOfStars := false if i := bytes.Index(prefix, []byte{'*'}); i >= 0 { // Line of stars present. if i > 0 && prefix[i-1] == ' ' { - i-- // remove trailing blank from prefix so stars remain aligned + i-- // remove trailing blank from prefix so stars remain aligned } - prefix = prefix[0:i]; - lineOfStars = true; + prefix = prefix[0:i] + lineOfStars = true } else { // No line of stars present. // Determine the white space on the first line after the /* @@ -474,36 +474,36 @@ func stripCommonPrefix(lines [][]byte) { // the /* is a tab. If the first comment line is empty but // for the opening /*, assume up to 3 blanks or a tab. This // whitespace may be found as suffix in the common prefix. - first := lines[0]; + first := lines[0] if isBlank(first[2:]) { // no comment text on the first line: // reduce prefix by up to 3 blanks or a tab // if present - this keeps comment text indented // relative to the /* and */'s if it was indented // in the first place - i := len(prefix); + i := len(prefix) for n := 0; n < 3 && i > 0 && prefix[i-1] == ' '; n++ { i-- } if i == len(prefix) && i > 0 && prefix[i-1] == '\t' { i-- } - prefix = prefix[0:i]; + prefix = prefix[0:i] } else { // comment text on the first line - suffix := make([]byte, len(first)); - n := 2; + suffix := make([]byte, len(first)) + n := 2 for n < len(first) && first[n] <= ' ' { - suffix[n] = first[n]; - n++; + suffix[n] = first[n] + n++ } if n > 2 && suffix[2] == '\t' { // assume the '\t' compensates for the /* suffix = suffix[2:n] } else { // otherwise assume two blanks - suffix[0], suffix[1] = ' ', ' '; - suffix = suffix[0:n]; + suffix[0], suffix[1] = ' ', ' ' + suffix = suffix[0:n] } // Shorten the computed common prefix by the length of // suffix, if it is found as suffix of the prefix. @@ -516,17 +516,17 @@ func stripCommonPrefix(lines [][]byte) { // Handle last line: If it only contains a closing */, align it // with the opening /*, otherwise align the text with the other // lines. - last := lines[len(lines)-1]; - closing := []byte{'*', '/'}; - i := bytes.Index(last, closing); + last := lines[len(lines)-1] + closing := []byte{'*', '/'} + i := bytes.Index(last, closing) if isBlank(last[0:i]) { // last line only contains closing */ - var sep []byte; + var sep []byte if lineOfStars { // insert an aligning blank sep = []byte{' '} } - lines[len(lines)-1] = bytes.Join([][]byte{prefix, closing}, sep); + lines[len(lines)-1] = bytes.Join([][]byte{prefix, closing}, sep) } else { // last line contains more comment text - assume // it is aligned like the other lines @@ -543,27 +543,27 @@ func stripCommonPrefix(lines [][]byte) { func (p *printer) writeComment(comment *ast.Comment) { - text := comment.Text; + text := comment.Text // shortcut common case of //-style comments if text[1] == '/' { - p.writeCommentLine(comment, comment.Pos(), text); - return; + p.writeCommentLine(comment, comment.Pos(), text) + return } // for /*-style comments, print line by line and let the // write function take care of the proper indentation - lines := split(text); - stripCommonPrefix(lines); + lines := split(text) + stripCommonPrefix(lines) // write comment lines, separated by formfeed, // without a line break after the last line - linebreak := formfeeds[0:1]; - pos := comment.Pos(); + linebreak := formfeeds[0:1] + pos := comment.Pos() for i, line := range lines { if i > 0 { - p.write(linebreak); - pos = p.pos; + p.write(linebreak) + pos = p.pos } if len(line) > 0 { p.writeCommentLine(comment, pos, line) @@ -594,7 +594,7 @@ func (p *printer) writeCommentSuffix(needsLinebreak bool) { } } } - p.writeWhitespace(len(p.buffer)); + p.writeWhitespace(len(p.buffer)) // make sure we have a line break if needsLinebreak { @@ -610,16 +610,16 @@ func (p *printer) writeCommentSuffix(needsLinebreak bool) { // token is a keyword or not. // func (p *printer) intersperseComments(next token.Position, isKeyword bool) { - isFirst := true; - needsLinebreak := false; - var last *ast.Comment; + isFirst := true + needsLinebreak := false + var last *ast.Comment for ; p.commentBefore(next); p.comment = p.comment.Next { for _, c := range p.comment.List { - p.writeCommentPrefix(c.Pos(), next, isFirst, isKeyword); - isFirst = false; - p.writeComment(c); - needsLinebreak = c.Text[1] == '/'; - last = c; + p.writeCommentPrefix(c.Pos(), next, isFirst, isKeyword) + isFirst = false + p.writeComment(c) + needsLinebreak = c.Text[1] == '/' + last = c } } if last != nil && !needsLinebreak && last.Pos().Line == next.Line { @@ -627,14 +627,14 @@ func (p *printer) intersperseComments(next token.Position, isKeyword bool) { // follows on the same line: separate with an extra blank p.write([]byte{' '}) } - p.writeCommentSuffix(needsLinebreak); + p.writeCommentSuffix(needsLinebreak) } // whiteWhitespace writes the first n whitespace entries. func (p *printer) writeWhitespace(n int) { // write entries - var data [1]byte; + var data [1]byte for i := 0; i < n; i++ { switch ch := p.buffer[i]; ch { case ignore: @@ -642,10 +642,10 @@ func (p *printer) writeWhitespace(n int) { case indent: p.indent++ case unindent: - p.indent--; + p.indent-- if p.indent < 0 { - p.internalError("negative indentation:", p.indent); - p.indent = 0; + p.internalError("negative indentation:", p.indent) + p.indent = 0 } case newline, formfeed: // A line break immediately followed by a "correcting" @@ -660,24 +660,24 @@ func (p *printer) writeWhitespace(n int) { // to a wide column may increase the indentation column // of lines before the label; effectively leading to wrong // indentation. - p.buffer[i], p.buffer[i+1] = unindent, formfeed; - i--; // do it again - continue; + p.buffer[i], p.buffer[i+1] = unindent, formfeed + i-- // do it again + continue } - fallthrough; + fallthrough default: - data[0] = byte(ch); - p.write(&data); + data[0] = byte(ch) + p.write(&data) } } // shift remaining entries down - i := 0; + i := 0 for ; n < len(p.buffer); n++ { - p.buffer[i] = p.buffer[n]; - i++; + p.buffer[i] = p.buffer[n] + i++ } - p.buffer = p.buffer[0:i]; + p.buffer = p.buffer[0:i] } @@ -696,14 +696,14 @@ func (p *printer) writeWhitespace(n int) { // printed, followed by the actual token. // func (p *printer) print(args ...) { - v := reflect.NewValue(args).(*reflect.StructValue); + v := reflect.NewValue(args).(*reflect.StructValue) for i := 0; i < v.NumField(); i++ { - f := v.Field(i); + f := v.Field(i) - next := p.pos; // estimated position of next item - var data []byte; - var tag HTMLTag; - isKeyword := false; + next := p.pos // estimated position of next item + var data []byte + var tag HTMLTag + isKeyword := false switch x := f.Interface().(type) { case whiteSpace: if x == ignore { @@ -712,16 +712,16 @@ func (p *printer) print(args ...) { // LabeledStmt) break } - i := len(p.buffer); + i := len(p.buffer) if i == cap(p.buffer) { // Whitespace sequences are very short so this should // never happen. Handle gracefully (but possibly with // bad comment placement) if it does happen. - p.writeWhitespace(i); - i = 0; + p.writeWhitespace(i) + i = 0 } - p.buffer = p.buffer[0 : i+1]; - p.buffer[i] = x; + p.buffer = p.buffer[0 : i+1] + p.buffer[i] = x case []byte: // TODO(gri): remove this case once commentList // handles comments correctly @@ -746,32 +746,32 @@ func (p *printer) print(args ...) { // (note that valid Go programs cannot contain esc ('\xff') // bytes since they do not appear in legal UTF-8 sequences) // TODO(gri): this this more efficiently. - data = strings.Bytes("\xff" + string(data) + "\xff"); + data = strings.Bytes("\xff" + string(data) + "\xff") case token.Token: if p.Styler != nil { data, tag = p.Styler.Token(x) } else { data = strings.Bytes(x.String()) } - isKeyword = x.IsKeyword(); + isKeyword = x.IsKeyword() case token.Position: if x.IsValid() { - next = x // accurate position of next item + next = x // accurate position of next item } default: panicln("print: unsupported argument type", f.Type().String()) } - p.pos = next; + p.pos = next if data != nil { - p.flush(next, isKeyword); + p.flush(next, isKeyword) // intersperse extra newlines if present in the source // (don't do this in flush as it will cause extra newlines // at the end of a file) - p.writeNewlines(next.Line - p.pos.Line); + p.writeNewlines(next.Line - p.pos.Line) - p.writeItem(next, data, tag); + p.writeItem(next, data, tag) } } } @@ -794,7 +794,7 @@ func (p *printer) flush(next token.Position, isKeyword bool) { p.intersperseComments(next, isKeyword) } // write any leftover whitespace - p.writeWhitespace(len(p.buffer)); + p.writeWhitespace(len(p.buffer)) } @@ -807,8 +807,8 @@ func (p *printer) flush(next token.Position, isKeyword bool) { // is used). // type trimmer struct { - output io.Writer; - buf bytes.Buffer; + output io.Writer + buf bytes.Buffer } @@ -821,12 +821,12 @@ type trimmer struct { func (p *trimmer) Write(data []byte) (n int, err os.Error) { // m < 0: no unwritten data except for whitespace // m >= 0: data[m:n] unwritten and no whitespace - m := 0; + m := 0 if p.buf.Len() > 0 { m = -1 } - var b byte; + var b byte for n, b = range data { switch b { default: @@ -835,13 +835,13 @@ func (p *trimmer) Write(data []byte) (n int, err os.Error) { if _, err = p.output.Write(p.buf.Bytes()); err != nil { return } - p.buf.Reset(); - m = n; + p.buf.Reset() + m = n } case '\v': - b = '\t'; // convert to htab - fallthrough; + b = '\t' // convert to htab + fallthrough case '\t', ' ', tabwriter.Escape: // write any pending (non-whitespace) data @@ -849,22 +849,22 @@ func (p *trimmer) Write(data []byte) (n int, err os.Error) { if _, err = p.output.Write(data[m:n]); err != nil { return } - m = -1; + m = -1 } // collect whitespace but discard tabrwiter.Escapes. if b != tabwriter.Escape { - p.buf.WriteByte(b) // WriteByte returns no errors + p.buf.WriteByte(b) // WriteByte returns no errors } case '\f', '\n': // discard whitespace - p.buf.Reset(); + p.buf.Reset() // write any pending (non-whitespace) data if m >= 0 { if _, err = p.output.Write(data[m:n]); err != nil { return } - m = -1; + m = -1 } // convert formfeed into newline if _, err = p.output.Write(newlines[0:1]); err != nil { @@ -872,7 +872,7 @@ func (p *trimmer) Write(data []byte) (n int, err os.Error) { } } } - n = len(data); + n = len(data) // write any pending non-whitespace if m >= 0 { @@ -881,7 +881,7 @@ func (p *trimmer) Write(data []byte) (n int, err os.Error) { } } - return; + return } @@ -890,17 +890,17 @@ func (p *trimmer) Write(data []byte) (n int, err os.Error) { // General printing is controlled with these Config.Mode flags. const ( - GenHTML uint = 1 << iota; // generate HTML - RawFormat; // do not use a tabwriter; if set, UseSpaces is ignored - TabIndent; // use tabs for indentation independent of UseSpaces - UseSpaces; // use spaces instead of tabs for alignment - NoSemis; // don't print semicolons at the end of a line + GenHTML uint = 1 << iota // generate HTML + RawFormat // do not use a tabwriter; if set, UseSpaces is ignored + TabIndent // use tabs for indentation independent of UseSpaces + UseSpaces // use spaces instead of tabs for alignment + NoSemis // don't print semicolons at the end of a line ) // An HTMLTag specifies a start and end tag. type HTMLTag struct { - Start, End string; // empty if tags are absent + Start, End string // empty if tags are absent } @@ -908,19 +908,19 @@ type HTMLTag struct { // A format consists of text and a (possibly empty) surrounding HTML tag. // type Styler interface { - LineTag(line int) ([]byte, HTMLTag); - Comment(c *ast.Comment, line []byte) ([]byte, HTMLTag); - BasicLit(x *ast.BasicLit) ([]byte, HTMLTag); - Ident(id *ast.Ident) ([]byte, HTMLTag); - Token(tok token.Token) ([]byte, HTMLTag); + LineTag(line int) ([]byte, HTMLTag) + Comment(c *ast.Comment, line []byte) ([]byte, HTMLTag) + BasicLit(x *ast.BasicLit) ([]byte, HTMLTag) + Ident(id *ast.Ident) ([]byte, HTMLTag) + Token(tok token.Token) ([]byte, HTMLTag) } // A Config node controls the output of Fprint. type Config struct { - Mode uint; // default: 0 - Tabwidth int; // default: 8 - Styler Styler; // default: nil + Mode uint // default: 0 + Tabwidth int // default: 8 + Styler Styler // default: nil } @@ -934,34 +934,34 @@ func (cfg *Config) Fprint(output io.Writer, node interface{}) (int, os.Error) { // (Input to a tabwriter must be untrimmed since trailing tabs provide // formatting information. The tabwriter could provide trimming // functionality but no tabwriter is used when RawFormat is set.) - output = &trimmer{output: output}; + output = &trimmer{output: output} // setup tabwriter if needed and redirect output - var tw *tabwriter.Writer; + var tw *tabwriter.Writer if cfg.Mode&RawFormat == 0 { - minwidth := cfg.Tabwidth; + minwidth := cfg.Tabwidth - padchar := byte('\t'); + padchar := byte('\t') if cfg.Mode&UseSpaces != 0 { padchar = ' ' } - twmode := tabwriter.DiscardEmptyColumns; + twmode := tabwriter.DiscardEmptyColumns if cfg.Mode&GenHTML != 0 { twmode |= tabwriter.FilterHTML } if cfg.Mode&TabIndent != 0 { - minwidth = 0; - twmode |= tabwriter.TabIndent; + minwidth = 0 + twmode |= tabwriter.TabIndent } - tw = tabwriter.NewWriter(output, minwidth, cfg.Tabwidth, 1, padchar, twmode); - output = tw; + tw = tabwriter.NewWriter(output, minwidth, cfg.Tabwidth, 1, padchar, twmode) + output = tw } // setup printer and print node - var p printer; - p.init(output, cfg); + var p printer + p.init(output, cfg) go func() { switch n := node.(type) { case ast.Expr: @@ -971,23 +971,23 @@ func (cfg *Config) Fprint(output io.Writer, node interface{}) (int, os.Error) { case ast.Decl: p.decl(n, atTop, ignoreMultiLine) case *ast.File: - p.comment = n.Comments; - p.file(n); + p.comment = n.Comments + p.file(n) default: - p.errors <- os.NewError(fmt.Sprintf("printer.Fprint: unsupported node type %T", n)); - runtime.Goexit(); + p.errors <- os.NewError(fmt.Sprintf("printer.Fprint: unsupported node type %T", n)) + runtime.Goexit() } - p.flush(token.Position{Offset: 1 << 30, Line: 1 << 30}, false); // flush to "infinity" - p.errors <- nil; // no errors - }(); - err := <-p.errors; // wait for completion of goroutine + p.flush(token.Position{Offset: 1 << 30, Line: 1 << 30}, false) // flush to "infinity" + p.errors <- nil // no errors + }() + err := <-p.errors // wait for completion of goroutine // flush tabwriter, if any if tw != nil { - tw.Flush() // ignore errors + tw.Flush() // ignore errors } - return p.written, err; + return p.written, err } @@ -995,6 +995,6 @@ func (cfg *Config) Fprint(output io.Writer, node interface{}) (int, os.Error) { // It calls Config.Fprint with default settings. // func Fprint(output io.Writer, node interface{}) os.Error { - _, err := (&Config{Tabwidth: 8}).Fprint(output, node); // don't care about number of bytes written - return err; + _, err := (&Config{Tabwidth: 8}).Fprint(output, node) // don't care about number of bytes written + return err } diff --git a/src/pkg/go/printer/printer_test.go b/src/pkg/go/printer/printer_test.go index 823f61740..b733e359b 100644 --- a/src/pkg/go/printer/printer_test.go +++ b/src/pkg/go/printer/printer_test.go @@ -5,21 +5,21 @@ package printer import ( - "bytes"; - oldParser "exp/parser"; - "flag"; - "io/ioutil"; - "go/ast"; - "go/parser"; - "os"; - "path"; - "testing"; + "bytes" + oldParser "exp/parser" + "flag" + "io/ioutil" + "go/ast" + "go/parser" + "os" + "path" + "testing" ) const ( - dataDir = "testdata"; - tabwidth = 8; + dataDir = "testdata" + tabwidth = 8 ) @@ -27,69 +27,69 @@ var update = flag.Bool("update", false, "update golden files") func lineString(text []byte, i int) string { - i0 := i; + i0 := i for i < len(text) && text[i] != '\n' { i++ } - return string(text[i0:i]); + return string(text[i0:i]) } type checkMode uint const ( - export checkMode = 1 << iota; - rawFormat; - oldSyntax; + export checkMode = 1 << iota + rawFormat + oldSyntax ) func check(t *testing.T, source, golden string, mode checkMode) { // parse source - var prog *ast.File; - var err os.Error; + var prog *ast.File + var err os.Error if mode&oldSyntax != 0 { prog, err = oldParser.ParseFile(source, nil, parser.ParseComments) } else { prog, err = parser.ParseFile(source, nil, parser.ParseComments) } if err != nil { - t.Error(err); - return; + t.Error(err) + return } // filter exports if necessary if mode&export != 0 { - ast.FileExports(prog); // ignore result - prog.Comments = nil; // don't print comments that are not in AST + ast.FileExports(prog) // ignore result + prog.Comments = nil // don't print comments that are not in AST } // determine printer configuration - cfg := Config{Tabwidth: tabwidth}; + cfg := Config{Tabwidth: tabwidth} if mode&rawFormat != 0 { cfg.Mode |= RawFormat } // format source - var buf bytes.Buffer; + var buf bytes.Buffer if _, err := cfg.Fprint(&buf, prog); err != nil { t.Error(err) } - res := buf.Bytes(); + res := buf.Bytes() // update golden files if necessary if *update { if err := ioutil.WriteFile(golden, res, 0644); err != nil { t.Error(err) } - return; + return } // get golden - gld, err := ioutil.ReadFile(golden); + gld, err := ioutil.ReadFile(golden) if err != nil { - t.Error(err); - return; + t.Error(err) + return } // compare lengths @@ -99,24 +99,24 @@ func check(t *testing.T, source, golden string, mode checkMode) { // compare contents for i, line, offs := 0, 1, 0; i < len(res) && i < len(gld); i++ { - ch := res[i]; + ch := res[i] if ch != gld[i] { - t.Errorf("%s:%d:%d: %s", source, line, i-offs+1, lineString(res, offs)); - t.Errorf("%s:%d:%d: %s", golden, line, i-offs+1, lineString(gld, offs)); - t.Error(); - return; + t.Errorf("%s:%d:%d: %s", source, line, i-offs+1, lineString(res, offs)) + t.Errorf("%s:%d:%d: %s", golden, line, i-offs+1, lineString(gld, offs)) + t.Error() + return } if ch == '\n' { - line++; - offs = i + 1; + line++ + offs = i + 1 } } } type entry struct { - source, golden string; - mode checkMode; + source, golden string + mode checkMode } // Use gotest -update to create/update the respective golden files. @@ -134,9 +134,9 @@ var data = []entry{ func Test(t *testing.T) { for _, e := range data { - source := path.Join(dataDir, e.source); - golden := path.Join(dataDir, e.golden); - check(t, source, golden, e.mode|oldSyntax); + source := path.Join(dataDir, e.source) + golden := path.Join(dataDir, e.golden) + check(t, source, golden, e.mode|oldSyntax) // TODO(gri) check that golden is idempotent //check(t, golden, golden, e.mode); } diff --git a/src/pkg/go/scanner/errors.go b/src/pkg/go/scanner/errors.go index 12c1c852f..d1fdf2dcf 100644 --- a/src/pkg/go/scanner/errors.go +++ b/src/pkg/go/scanner/errors.go @@ -5,12 +5,12 @@ package scanner import ( - "container/vector"; - "fmt"; - "go/token"; - "io"; - "os"; - "sort"; + "container/vector" + "fmt" + "go/token" + "io" + "os" + "sort" ) @@ -20,7 +20,7 @@ import ( // to the beginning of the offending token. // type ErrorHandler interface { - Error(pos token.Position, msg string); + Error(pos token.Position, msg string) } @@ -34,16 +34,16 @@ type ErrorHandler interface { // error handling is obtained. // type ErrorVector struct { - errors vector.Vector; + errors vector.Vector } // Reset resets an ErrorVector to no errors. -func (h *ErrorVector) Reset() { h.errors.Resize(0, 0) } +func (h *ErrorVector) Reset() { h.errors.Resize(0, 0) } // ErrorCount returns the number of errors collected. -func (h *ErrorVector) ErrorCount() int { return h.errors.Len() } +func (h *ErrorVector) ErrorCount() int { return h.errors.Len() } // Within ErrorVector, an error is represented by an Error node. The @@ -51,8 +51,8 @@ func (h *ErrorVector) ErrorCount() int { return h.errors.Len() } // token, and the error condition is described by Msg. // type Error struct { - Pos token.Position; - Msg string; + Pos token.Position + Msg string } @@ -62,7 +62,7 @@ func (e *Error) String() string { // TODO(gri) reconsider the semantics of Position.IsValid return e.Pos.String() + ": " + e.Msg } - return e.Msg; + return e.Msg } @@ -71,13 +71,13 @@ type ErrorList []*Error // ErrorList implements the sort Interface. -func (p ErrorList) Len() int { return len(p) } -func (p ErrorList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } +func (p ErrorList) Len() int { return len(p) } +func (p ErrorList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p ErrorList) Less(i, j int) bool { - e := &p[i].Pos; - f := &p[j].Pos; + e := &p[i].Pos + f := &p[j].Pos // Note that it is not sufficient to simply compare file offsets because // the offsets do not reflect modified line information (through //line // comments). @@ -92,7 +92,7 @@ func (p ErrorList) Less(i, j int) bool { return e.Column < f.Column } } - return false; + return false } @@ -103,7 +103,7 @@ func (p ErrorList) String() string { case 1: return p[0].String() } - return fmt.Sprintf("%s (and %d more errors)", p[0].String(), len(p)-1); + return fmt.Sprintf("%s (and %d more errors)", p[0].String(), len(p)-1) } @@ -111,9 +111,9 @@ func (p ErrorList) String() string { // returned by GetErrors. // const ( - Raw = iota; // leave error list unchanged - Sorted; // sort error list by file, line, and column number - NoMultiples; // sort error list and leave only the first error per line + Raw = iota // leave error list unchanged + Sorted // sort error list by file, line, and column number + NoMultiples // sort error list and leave only the first error per line ) @@ -126,7 +126,7 @@ func (h *ErrorVector) GetErrorList(mode int) ErrorList { return nil } - list := make(ErrorList, h.errors.Len()); + list := make(ErrorList, h.errors.Len()) for i := 0; i < h.errors.Len(); i++ { list[i] = h.errors.At(i).(*Error) } @@ -136,19 +136,19 @@ func (h *ErrorVector) GetErrorList(mode int) ErrorList { } if mode >= NoMultiples { - var last token.Position; // initial last.Line is != any legal error line - i := 0; + var last token.Position // initial last.Line is != any legal error line + i := 0 for _, e := range list { if e.Pos.Filename != last.Filename || e.Pos.Line != last.Line { - last = e.Pos; - list[i] = e; - i++; + last = e.Pos + list[i] = e + i++ } } - list = list[0:i]; + list = list[0:i] } - return list; + return list } @@ -161,7 +161,7 @@ func (h *ErrorVector) GetError(mode int) os.Error { return nil } - return h.GetErrorList(mode); + return h.GetErrorList(mode) } diff --git a/src/pkg/go/scanner/scanner.go b/src/pkg/go/scanner/scanner.go index 026ae9976..fad3c0f75 100644 --- a/src/pkg/go/scanner/scanner.go +++ b/src/pkg/go/scanner/scanner.go @@ -9,11 +9,11 @@ package scanner import ( - "bytes"; - "go/token"; - "strconv"; - "unicode"; - "utf8"; + "bytes" + "go/token" + "strconv" + "unicode" + "utf8" ) @@ -24,18 +24,18 @@ import ( // type Scanner struct { // immutable state - src []byte; // source - err ErrorHandler; // error reporting; or nil - mode uint; // scanning mode + src []byte // source + err ErrorHandler // error reporting; or nil + mode uint // scanning mode // scanning state - pos token.Position; // previous reading position (position before ch) - offset int; // current reading offset (position after ch) - ch int; // one char look-ahead - insertSemi bool; // insert a semicolon before next newline + pos token.Position // previous reading position (position before ch) + offset int // current reading offset (position after ch) + ch int // one char look-ahead + insertSemi bool // insert a semicolon before next newline // public state - ok to modify - ErrorCount int; // number of errors encountered + ErrorCount int // number of errors encountered } @@ -44,22 +44,22 @@ type Scanner struct { // func (S *Scanner) next() { if S.offset < len(S.src) { - S.pos.Offset = S.offset; - S.pos.Column++; - r, w := int(S.src[S.offset]), 1; + S.pos.Offset = S.offset + S.pos.Column++ + r, w := int(S.src[S.offset]), 1 switch { case r == '\n': - S.pos.Line++; - S.pos.Column = 0; + S.pos.Line++ + S.pos.Column = 0 case r >= 0x80: // not ASCII r, w = utf8.DecodeRune(S.src[S.offset:]) } - S.offset += w; - S.ch = r; + S.offset += w + S.ch = r } else { - S.pos.Offset = len(S.src); - S.ch = -1; // eof + S.pos.Offset = len(S.src) + S.ch = -1 // eof } } @@ -68,9 +68,9 @@ func (S *Scanner) next() { // They control scanner behavior. // const ( - ScanComments = 1 << iota; // return comments as COMMENT tokens - AllowIllegalChars; // do not report an error for illegal chars - InsertSemis; // automatically insert semicolons + ScanComments = 1 << iota // return comments as COMMENT tokens + AllowIllegalChars // do not report an error for illegal chars + InsertSemis // automatically insert semicolons ) @@ -84,18 +84,18 @@ const ( // func (S *Scanner) Init(filename string, src []byte, err ErrorHandler, mode uint) { // Explicitly initialize all fields since a scanner may be reused. - S.src = src; - S.err = err; - S.mode = mode; - S.pos = token.Position{filename, 0, 1, 0}; - S.offset = 0; - S.ErrorCount = 0; - S.next(); + S.src = src + S.err = err + S.mode = mode + S.pos = token.Position{filename, 0, 1, 0} + S.offset = 0 + S.ErrorCount = 0 + S.next() } func charString(ch int) string { - var s string; + var s string switch ch { case -1: return `EOF` @@ -120,7 +120,7 @@ func charString(ch int) string { default: s = string(ch) } - return "'" + s + "' (U+" + strconv.Itob(ch, 16) + ")"; + return "'" + s + "' (U+" + strconv.Itob(ch, 16) + ")" } @@ -128,7 +128,7 @@ func (S *Scanner) error(pos token.Position, msg string) { if S.err != nil { S.err.Error(pos, msg) } - S.ErrorCount++; + S.ErrorCount++ } @@ -136,11 +136,11 @@ func (S *Scanner) expect(ch int) { if S.ch != ch { S.error(S.pos, "expected "+charString(ch)+", found "+charString(S.ch)) } - S.next(); // always make progress + S.next() // always make progress } -var prefix = []byte{'l', 'i', 'n', 'e', ' '} // "line " +var prefix = []byte{'l', 'i', 'n', 'e', ' '} // "line " func (S *Scanner) scanComment(pos token.Position) { // first '/' already consumed @@ -148,44 +148,44 @@ func (S *Scanner) scanComment(pos token.Position) { if S.ch == '/' { //-style comment for S.ch >= 0 { - S.next(); + S.next() if S.ch == '\n' { // '\n' is not part of the comment for purposes of scanning // (the comment ends on the same line where it started) if pos.Column == 1 { - text := S.src[pos.Offset+2 : S.pos.Offset]; + text := S.src[pos.Offset+2 : S.pos.Offset] if bytes.HasPrefix(text, prefix) { // comment starts at beginning of line with "//line "; // get filename and line number, if any - i := bytes.Index(text, []byte{':'}); + i := bytes.Index(text, []byte{':'}) if i >= 0 { if line, err := strconv.Atoi(string(text[i+1:])); err == nil && line > 0 { // valid //line filename:line comment; // update scanner position - S.pos.Filename = string(text[len(prefix):i]); - S.pos.Line = line; + S.pos.Filename = string(text[len(prefix):i]) + S.pos.Line = line } } } } - return; + return } } } else { /*-style comment */ - S.expect('*'); + S.expect('*') for S.ch >= 0 { - ch := S.ch; - S.next(); + ch := S.ch + S.next() if ch == '*' && S.ch == '/' { - S.next(); - return; + S.next() + return } } } - S.error(pos, "comment not terminated"); + S.error(pos, "comment not terminated") } @@ -193,30 +193,30 @@ func (S *Scanner) findNewline(pos token.Position) bool { // first '/' already consumed; assume S.ch == '/' || S.ch == '*' // read ahead until a newline or non-comment token is found - newline := false; + newline := false for pos1 := pos; S.ch >= 0; { if S.ch == '/' { //-style comment always contains a newline - newline = true; - break; + newline = true + break } - S.scanComment(pos1); + S.scanComment(pos1) if pos1.Line < S.pos.Line { /*-style comment contained a newline */ - newline = true; - break; + newline = true + break } - S.skipWhitespace(); + S.skipWhitespace() if S.ch == '\n' { - newline = true; - break; + newline = true + break } if S.ch != '/' { // non-comment token break } - pos1 = S.pos; - S.next(); + pos1 = S.pos + S.next() if S.ch != '/' && S.ch != '*' { // non-comment token break @@ -224,11 +224,11 @@ func (S *Scanner) findNewline(pos token.Position) bool { } // reset position - S.pos = pos; - S.offset = pos.Offset + 1; - S.ch = '/'; + S.pos = pos + S.offset = pos.Offset + 1 + S.ch = '/' - return newline; + return newline } @@ -243,11 +243,11 @@ func isDigit(ch int) bool { func (S *Scanner) scanIdentifier() token.Token { - pos := S.pos.Offset; + pos := S.pos.Offset for isLetter(S.ch) || isDigit(S.ch) { S.next() } - return token.Lookup(S.src[pos:S.pos.Offset]); + return token.Lookup(S.src[pos:S.pos.Offset]) } @@ -260,7 +260,7 @@ func digitVal(ch int) int { case 'A' <= ch && ch <= 'F': return ch - 'A' + 10 } - return 16; // larger than any legal digit val + return 16 // larger than any legal digit val } @@ -272,65 +272,65 @@ func (S *Scanner) scanMantissa(base int) { func (S *Scanner) scanNumber(seen_decimal_point bool) token.Token { - tok := token.INT; + tok := token.INT if seen_decimal_point { - tok = token.FLOAT; - S.scanMantissa(10); - goto exponent; + tok = token.FLOAT + S.scanMantissa(10) + goto exponent } if S.ch == '0' { // int or float - S.next(); + S.next() if S.ch == 'x' || S.ch == 'X' { // hexadecimal int - S.next(); - S.scanMantissa(16); + S.next() + S.scanMantissa(16) } else { // octal int or float - S.scanMantissa(8); + S.scanMantissa(8) if digitVal(S.ch) < 10 || S.ch == '.' || S.ch == 'e' || S.ch == 'E' { // float - tok = token.FLOAT; - goto mantissa; + tok = token.FLOAT + goto mantissa } // octal int } - goto exit; + goto exit } mantissa: // decimal int or float - S.scanMantissa(10); + S.scanMantissa(10) if S.ch == '.' { // float - tok = token.FLOAT; - S.next(); - S.scanMantissa(10); + tok = token.FLOAT + S.next() + S.scanMantissa(10) } exponent: if S.ch == 'e' || S.ch == 'E' { // float - tok = token.FLOAT; - S.next(); + tok = token.FLOAT + S.next() if S.ch == '-' || S.ch == '+' { S.next() } - S.scanMantissa(10); + S.scanMantissa(10) } exit: - return tok; + return tok } func (S *Scanner) scanDigits(base, length int) { for length > 0 && digitVal(S.ch) < base { - S.next(); - length--; + S.next() + length-- } if length > 0 { S.error(S.pos, "illegal char escape") @@ -339,14 +339,14 @@ func (S *Scanner) scanDigits(base, length int) { func (S *Scanner) scanEscape(quote int) { - pos := S.pos; - ch := S.ch; - S.next(); + pos := S.pos + ch := S.ch + S.next() switch ch { case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', quote: // nothing to do case '0', '1', '2', '3', '4', '5', '6', '7': - S.scanDigits(8, 3-1) // 1 char read already + S.scanDigits(8, 3-1) // 1 char read already case 'x': S.scanDigits(16, 2) case 'u': @@ -362,22 +362,22 @@ func (S *Scanner) scanEscape(quote int) { func (S *Scanner) scanChar(pos token.Position) { // '\'' already consumed - n := 0; + n := 0 for S.ch != '\'' { - ch := S.ch; - n++; - S.next(); + ch := S.ch + n++ + S.next() if ch == '\n' || ch < 0 { - S.error(pos, "character literal not terminated"); - n = 1; - break; + S.error(pos, "character literal not terminated") + n = 1 + break } if ch == '\\' { S.scanEscape('\'') } } - S.next(); + S.next() if n != 1 { S.error(pos, "illegal character literal") @@ -389,18 +389,18 @@ func (S *Scanner) scanString(pos token.Position) { // '"' already consumed for S.ch != '"' { - ch := S.ch; - S.next(); + ch := S.ch + S.next() if ch == '\n' || ch < 0 { - S.error(pos, "string not terminated"); - break; + S.error(pos, "string not terminated") + break } if ch == '\\' { S.scanEscape('"') } } - S.next(); + S.next() } @@ -408,15 +408,15 @@ func (S *Scanner) scanRawString(pos token.Position) { // '`' already consumed for S.ch != '`' { - ch := S.ch; - S.next(); + ch := S.ch + S.next() if ch < 0 { - S.error(pos, "string not terminated"); - break; + S.error(pos, "string not terminated") + break } } - S.next(); + S.next() } @@ -435,40 +435,40 @@ func (S *Scanner) skipWhitespace() { func (S *Scanner) switch2(tok0, tok1 token.Token) token.Token { if S.ch == '=' { - S.next(); - return tok1; + S.next() + return tok1 } - return tok0; + return tok0 } func (S *Scanner) switch3(tok0, tok1 token.Token, ch2 int, tok2 token.Token) token.Token { if S.ch == '=' { - S.next(); - return tok1; + S.next() + return tok1 } if S.ch == ch2 { - S.next(); - return tok2; + S.next() + return tok2 } - return tok0; + return tok0 } func (S *Scanner) switch4(tok0, tok1 token.Token, ch2 int, tok2, tok3 token.Token) token.Token { if S.ch == '=' { - S.next(); - return tok1; + S.next() + return tok1 } if S.ch == ch2 { - S.next(); + S.next() if S.ch == '=' { - S.next(); - return tok3; + S.next() + return tok3 } - return tok2; + return tok2 } - return tok0; + return tok0 } @@ -487,25 +487,25 @@ var semicolon = []byte{';'} // func (S *Scanner) Scan() (pos token.Position, tok token.Token, lit []byte) { scanAgain: - S.skipWhitespace(); + S.skipWhitespace() // current token start - insertSemi := false; - pos, tok = S.pos, token.ILLEGAL; + insertSemi := false + pos, tok = S.pos, token.ILLEGAL // determine token value switch ch := S.ch; { case isLetter(ch): - tok = S.scanIdentifier(); + tok = S.scanIdentifier() switch tok { case token.IDENT, token.BREAK, token.CONTINUE, token.FALLTHROUGH, token.RETURN: insertSemi = true } case digitVal(ch) < 10: - insertSemi = true; - tok = S.scanNumber(false); + insertSemi = true + tok = S.scanNumber(false) default: - S.next(); // always make progress + S.next() // always make progress switch ch { case -1: tok = token.EOF @@ -513,31 +513,31 @@ scanAgain: // we only reach here of S.insertSemi was // set in the first place and exited early // from S.skipWhitespace() - S.insertSemi = false; // newline consumed - return pos, token.SEMICOLON, semicolon; + S.insertSemi = false // newline consumed + return pos, token.SEMICOLON, semicolon case '"': - insertSemi = true; - tok = token.STRING; - S.scanString(pos); + insertSemi = true + tok = token.STRING + S.scanString(pos) case '\'': - insertSemi = true; - tok = token.CHAR; - S.scanChar(pos); + insertSemi = true + tok = token.CHAR + S.scanChar(pos) case '`': - insertSemi = true; - tok = token.STRING; - S.scanRawString(pos); + insertSemi = true + tok = token.STRING + S.scanRawString(pos) case ':': tok = S.switch2(token.COLON, token.DEFINE) case '.': if digitVal(S.ch) < 10 { - insertSemi = true; - tok = S.scanNumber(true); + insertSemi = true + tok = S.scanNumber(true) } else if S.ch == '.' { - S.next(); + S.next() if S.ch == '.' { - S.next(); - tok = token.ELLIPSIS; + S.next() + tok = token.ELLIPSIS } } else { tok = token.PERIOD @@ -549,25 +549,25 @@ scanAgain: case '(': tok = token.LPAREN case ')': - insertSemi = true; - tok = token.RPAREN; + insertSemi = true + tok = token.RPAREN case '[': tok = token.LBRACK case ']': - insertSemi = true; - tok = token.RBRACK; + insertSemi = true + tok = token.RBRACK case '{': tok = token.LBRACE case '}': - insertSemi = true; - tok = token.RBRACE; + insertSemi = true + tok = token.RBRACE case '+': - tok = S.switch3(token.ADD, token.ADD_ASSIGN, '+', token.INC); + tok = S.switch3(token.ADD, token.ADD_ASSIGN, '+', token.INC) if tok == token.INC { insertSemi = true } case '-': - tok = S.switch3(token.SUB, token.SUB_ASSIGN, '-', token.DEC); + tok = S.switch3(token.SUB, token.SUB_ASSIGN, '-', token.DEC) if tok == token.DEC { insertSemi = true } @@ -577,16 +577,16 @@ scanAgain: if S.ch == '/' || S.ch == '*' { // comment if S.insertSemi && S.findNewline(pos) { - S.insertSemi = false; // newline consumed - return pos, token.SEMICOLON, semicolon; + S.insertSemi = false // newline consumed + return pos, token.SEMICOLON, semicolon } - S.scanComment(pos); + S.scanComment(pos) if S.mode&ScanComments == 0 { // skip comment - S.insertSemi = false; // newline consumed - goto scanAgain; + S.insertSemi = false // newline consumed + goto scanAgain } - tok = token.COMMENT; + tok = token.COMMENT } else { tok = S.switch2(token.QUO, token.QUO_ASSIGN) } @@ -596,8 +596,8 @@ scanAgain: tok = S.switch2(token.XOR, token.XOR_ASSIGN) case '<': if S.ch == '-' { - S.next(); - tok = token.ARROW; + S.next() + tok = token.ARROW } else { tok = S.switch4(token.LSS, token.LEQ, '<', token.SHL, token.SHL_ASSIGN) } @@ -609,8 +609,8 @@ scanAgain: tok = S.switch2(token.NOT, token.NEQ) case '&': if S.ch == '^' { - S.next(); - tok = S.switch2(token.AND_NOT, token.AND_NOT_ASSIGN); + S.next() + tok = S.switch2(token.AND_NOT, token.AND_NOT_ASSIGN) } else { tok = S.switch3(token.AND, token.AND_ASSIGN, '&', token.LAND) } @@ -620,14 +620,14 @@ scanAgain: if S.mode&AllowIllegalChars == 0 { S.error(pos, "illegal character "+charString(ch)) } - insertSemi = S.insertSemi; // preserve insertSemi info + insertSemi = S.insertSemi // preserve insertSemi info } } if S.mode&InsertSemis != 0 { S.insertSemi = insertSemi } - return pos, tok, S.src[pos.Offset:S.pos.Offset]; + return pos, tok, S.src[pos.Offset:S.pos.Offset] } @@ -638,10 +638,10 @@ scanAgain: // of errors encountered. // func Tokenize(filename string, src []byte, err ErrorHandler, mode uint, f func(pos token.Position, tok token.Token, lit []byte) bool) int { - var s Scanner; - s.Init(filename, src, err, mode); + var s Scanner + s.Init(filename, src, err, mode) for f(s.Scan()) { // action happens in f } - return s.ErrorCount; + return s.ErrorCount } diff --git a/src/pkg/go/scanner/scanner_test.go b/src/pkg/go/scanner/scanner_test.go index b6d7e99ca..6ea4b2d58 100644 --- a/src/pkg/go/scanner/scanner_test.go +++ b/src/pkg/go/scanner/scanner_test.go @@ -5,18 +5,18 @@ package scanner import ( - "go/token"; - "os"; - "strings"; - "testing"; + "go/token" + "os" + "strings" + "testing" ) const /* class */ ( - special = iota; - literal; - operator; - keyword; + special = iota + literal + operator + keyword ) @@ -29,14 +29,14 @@ func tokenclass(tok token.Token) int { case tok.IsKeyword(): return keyword } - return special; + return special } type elt struct { - tok token.Token; - lit string; - class int; + tok token.Token + lit string + class int } @@ -162,10 +162,10 @@ var tokens = [...]elt{ } -const whitespace = " \t \n\n\n" // to separate tokens +const whitespace = " \t \n\n\n" // to separate tokens type TestErrorHandler struct { - t *testing.T; + t *testing.T } func (h *TestErrorHandler) Error(pos token.Position, msg string) { @@ -174,13 +174,13 @@ func (h *TestErrorHandler) Error(pos token.Position, msg string) { func NewlineCount(s string) int { - n := 0; + n := 0 for i := 0; i < len(s); i++ { if s[i] == '\n' { n++ } } - return n; + return n } @@ -203,27 +203,27 @@ func checkPos(t *testing.T, lit string, pos, expected token.Position) { // Verify that calling Scan() provides the correct results. func TestScan(t *testing.T) { // make source - var src string; + var src string for _, e := range tokens { src += e.lit + whitespace } - whitespace_linecount := NewlineCount(whitespace); + whitespace_linecount := NewlineCount(whitespace) // verify scan - index := 0; - epos := token.Position{"", 0, 1, 1}; + index := 0 + epos := token.Position{"", 0, 1, 1} nerrors := Tokenize("", strings.Bytes(src), &TestErrorHandler{t}, ScanComments, func(pos token.Position, tok token.Token, litb []byte) bool { - e := elt{token.EOF, "", special}; + e := elt{token.EOF, "", special} if index < len(tokens) { e = tokens[index] } - lit := string(litb); + lit := string(litb) if tok == token.EOF { - lit = "<EOF>"; - epos.Column = 0; + lit = "<EOF>" + epos.Column = 0 } - checkPos(t, lit, pos, epos); + checkPos(t, lit, pos, epos) if tok != e.tok { t.Errorf("bad token for %q: got %s, expected %s", lit, tok.String(), e.tok.String()) } @@ -233,16 +233,16 @@ func TestScan(t *testing.T) { if tokenclass(tok) != e.class { t.Errorf("bad class for %q: got %d, expected %d", lit, tokenclass(tok), e.class) } - epos.Offset += len(lit) + len(whitespace); - epos.Line += NewlineCount(lit) + whitespace_linecount; + epos.Offset += len(lit) + len(whitespace) + epos.Line += NewlineCount(lit) + whitespace_linecount if tok == token.COMMENT && litb[1] == '/' { // correct for unaccounted '/n' in //-style comment - epos.Offset++; - epos.Line++; + epos.Offset++ + epos.Line++ } - index++; - return tok != token.EOF; - }); + index++ + return tok != token.EOF + }) if nerrors != 0 { t.Errorf("found %d errors", nerrors) } @@ -255,14 +255,14 @@ func getTok(_ token.Position, tok token.Token, _ []byte) token.Token { func checkSemi(t *testing.T, line string, mode uint) { - var S Scanner; - S.Init("TestSemis", strings.Bytes(line), nil, mode); - pos, tok, lit := S.Scan(); + var S Scanner + S.Init("TestSemis", strings.Bytes(line), nil, mode) + pos, tok, lit := S.Scan() for tok != token.EOF { if tok == token.ILLEGAL { // next token must be a semicolon - offs := pos.Offset + 1; - pos, tok, lit = S.Scan(); + offs := pos.Offset + 1 + pos, tok, lit = S.Scan() if tok == token.SEMICOLON { if pos.Offset != offs { t.Errorf("bad offset for %q: got %d, expected %d", line, pos.Offset, offs) @@ -276,7 +276,7 @@ func checkSemi(t *testing.T, line string, mode uint) { } else if tok == token.SEMICOLON { t.Errorf("bad token for %q: got ;, expected no ;", line) } - pos, tok, lit = S.Scan(); + pos, tok, lit = S.Scan() } } @@ -406,9 +406,9 @@ func TestSemis(t *testing.T) { type seg struct { - srcline string; // a line of source text - filename string; // filename for current token - line int; // line number for current token + srcline string // a line of source text + filename string // filename for current token + line int // line number for current token } @@ -416,15 +416,15 @@ var segments = []seg{ // exactly one token per line since the test consumes one token per segment seg{" line1", "TestLineComments", 1}, seg{"\nline2", "TestLineComments", 2}, - seg{"\nline3 //line File1.go:100", "TestLineComments", 3}, // bad line comment, ignored + seg{"\nline3 //line File1.go:100", "TestLineComments", 3}, // bad line comment, ignored seg{"\nline4", "TestLineComments", 4}, seg{"\n//line File1.go:100\n line100", "File1.go", 100}, seg{"\n//line File2.go:200\n line200", "File2.go", 200}, seg{"\n//line :1\n line1", "", 1}, seg{"\n//line foo:42\n line42", "foo", 42}, - seg{"\n //line foo:42\n line44", "foo", 44}, // bad line comment, ignored - seg{"\n//line foo 42\n line46", "foo", 46}, // bad line comment, ignored - seg{"\n//line foo:42 extra text\n line48", "foo", 48}, // bad line comment, ignored + seg{"\n //line foo:42\n line44", "foo", 44}, // bad line comment, ignored + seg{"\n//line foo 42\n line46", "foo", 46}, // bad line comment, ignored + seg{"\n//line foo:42 extra text\n line48", "foo", 48}, // bad line comment, ignored seg{"\n//line foo:42\n line42", "foo", 42}, seg{"\n//line foo:42\n line42", "foo", 42}, seg{"\n//line File1.go:100\n line100", "File1.go", 100}, @@ -434,17 +434,17 @@ var segments = []seg{ // Verify that comments of the form "//line filename:line" are interpreted correctly. func TestLineComments(t *testing.T) { // make source - var src string; + var src string for _, e := range segments { src += e.srcline } // verify scan - var S Scanner; - S.Init("TestLineComments", strings.Bytes(src), nil, 0); + var S Scanner + S.Init("TestLineComments", strings.Bytes(src), nil, 0) for _, s := range segments { - pos, _, lit := S.Scan(); - checkPos(t, string(lit), pos, token.Position{s.filename, pos.Offset, s.line, pos.Column}); + pos, _, lit := S.Scan() + checkPos(t, string(lit), pos, token.Position{s.filename, pos.Offset, s.line, pos.Column}) } if S.ErrorCount != 0 { @@ -455,20 +455,20 @@ func TestLineComments(t *testing.T) { // Verify that initializing the same scanner more then once works correctly. func TestInit(t *testing.T) { - var s Scanner; + var s Scanner // 1st init - s.Init("", strings.Bytes("if true { }"), nil, 0); - s.Scan(); // if - s.Scan(); // true - _, tok, _ := s.Scan(); // { + s.Init("", strings.Bytes("if true { }"), nil, 0) + s.Scan() // if + s.Scan() // true + _, tok, _ := s.Scan() // { if tok != token.LBRACE { t.Errorf("bad token: got %s, expected %s", tok.String(), token.LBRACE) } // 2nd init - s.Init("", strings.Bytes("go true { ]"), nil, 0); - _, tok, _ = s.Scan(); // go + s.Init("", strings.Bytes("go true { ]"), nil, 0) + _, tok, _ = s.Scan() // go if tok != token.GO { t.Errorf("bad token: got %s, expected %s", tok.String(), token.GO) } @@ -480,12 +480,12 @@ func TestInit(t *testing.T) { func TestIllegalChars(t *testing.T) { - var s Scanner; + var s Scanner - const src = "*?*$*@*"; - s.Init("", strings.Bytes(src), &TestErrorHandler{t}, AllowIllegalChars); + const src = "*?*$*@*" + s.Init("", strings.Bytes(src), &TestErrorHandler{t}, AllowIllegalChars) for offs, ch := range src { - pos, tok, lit := s.Scan(); + pos, tok, lit := s.Scan() if pos.Offset != offs { t.Errorf("bad position for %s: got %d, expected %d", string(lit), pos.Offset, offs) } @@ -501,37 +501,37 @@ func TestIllegalChars(t *testing.T) { func TestStdErrorHander(t *testing.T) { - const src = "@\n" + // illegal character, cause an error - "@ @\n" + // two errors on the same line + const src = "@\n" + // illegal character, cause an error + "@ @\n" + // two errors on the same line "//line File2:20\n" + - "@\n" + // different file, but same line + "@\n" + // different file, but same line "//line File2:1\n" + - "@ @\n" + // same file, decreasing line number + "@ @\n" + // same file, decreasing line number "//line File1:1\n" + - "@ @ @"; // original file, line 1 again + "@ @ @" // original file, line 1 again - v := new(ErrorVector); + v := new(ErrorVector) nerrors := Tokenize("File1", strings.Bytes(src), v, 0, func(pos token.Position, tok token.Token, litb []byte) bool { return tok != token.EOF - }); + }) - list := v.GetErrorList(Raw); + list := v.GetErrorList(Raw) if len(list) != 9 { - t.Errorf("found %d raw errors, expected 9", len(list)); - PrintError(os.Stderr, list); + t.Errorf("found %d raw errors, expected 9", len(list)) + PrintError(os.Stderr, list) } - list = v.GetErrorList(Sorted); + list = v.GetErrorList(Sorted) if len(list) != 9 { - t.Errorf("found %d sorted errors, expected 9", len(list)); - PrintError(os.Stderr, list); + t.Errorf("found %d sorted errors, expected 9", len(list)) + PrintError(os.Stderr, list) } - list = v.GetErrorList(NoMultiples); + list = v.GetErrorList(NoMultiples) if len(list) != 4 { - t.Errorf("found %d one-per-line errors, expected 4", len(list)); - PrintError(os.Stderr, list); + t.Errorf("found %d one-per-line errors, expected 4", len(list)) + PrintError(os.Stderr, list) } if v.ErrorCount() != nerrors { diff --git a/src/pkg/go/token/token.go b/src/pkg/go/token/token.go index 10097efbd..95a35fed0 100644 --- a/src/pkg/go/token/token.go +++ b/src/pkg/go/token/token.go @@ -9,8 +9,8 @@ package token import ( - "fmt"; - "strconv"; + "fmt" + "strconv" ) @@ -20,111 +20,111 @@ type Token int // The list of tokens. const ( // Special tokens - ILLEGAL Token = iota; - EOF; - COMMENT; + ILLEGAL Token = iota + EOF + COMMENT - literal_beg; + literal_beg // Identifiers and basic type literals // (these tokens stand for classes of literals) - IDENT; // main - INT; // 12345 - FLOAT; // 123.45 - CHAR; // 'a' - STRING; // "abc" - literal_end; - - operator_beg; + IDENT // main + INT // 12345 + FLOAT // 123.45 + CHAR // 'a' + STRING // "abc" + literal_end + + operator_beg // Operators and delimiters - ADD; // + - SUB; // - - MUL; // * - QUO; // / - REM; // % - - AND; // & - OR; // | - XOR; // ^ - SHL; // << - SHR; // >> - AND_NOT; // &^ - - ADD_ASSIGN; // += - SUB_ASSIGN; // -= - MUL_ASSIGN; // *= - QUO_ASSIGN; // /= - REM_ASSIGN; // %= - - AND_ASSIGN; // &= - OR_ASSIGN; // |= - XOR_ASSIGN; // ^= - SHL_ASSIGN; // <<= - SHR_ASSIGN; // >>= - AND_NOT_ASSIGN; // &^= - - LAND; // && - LOR; // || - ARROW; // <- - INC; // ++ - DEC; // -- - - EQL; // == - LSS; // < - GTR; // > - ASSIGN; // = - NOT; // ! - - NEQ; // != - LEQ; // <= - GEQ; // >= - DEFINE; // := - ELLIPSIS; // ... - - LPAREN; // ( - LBRACK; // [ - LBRACE; // { - COMMA; // , - PERIOD; // . - - RPAREN; // ) - RBRACK; // ] - RBRACE; // } - SEMICOLON; // ; - COLON; // : - operator_end; - - keyword_beg; + ADD // + + SUB // - + MUL // * + QUO // / + REM // % + + AND // & + OR // | + XOR // ^ + SHL // << + SHR // >> + AND_NOT // &^ + + ADD_ASSIGN // += + SUB_ASSIGN // -= + MUL_ASSIGN // *= + QUO_ASSIGN // /= + REM_ASSIGN // %= + + AND_ASSIGN // &= + OR_ASSIGN // |= + XOR_ASSIGN // ^= + SHL_ASSIGN // <<= + SHR_ASSIGN // >>= + AND_NOT_ASSIGN // &^= + + LAND // && + LOR // || + ARROW // <- + INC // ++ + DEC // -- + + EQL // == + LSS // < + GTR // > + ASSIGN // = + NOT // ! + + NEQ // != + LEQ // <= + GEQ // >= + DEFINE // := + ELLIPSIS // ... + + LPAREN // ( + LBRACK // [ + LBRACE // { + COMMA // , + PERIOD // . + + RPAREN // ) + RBRACK // ] + RBRACE // } + SEMICOLON // ; + COLON // : + operator_end + + keyword_beg // Keywords - BREAK; - CASE; - CHAN; - CONST; - CONTINUE; - - DEFAULT; - DEFER; - ELSE; - FALLTHROUGH; - FOR; - - FUNC; - GO; - GOTO; - IF; - IMPORT; - - INTERFACE; - MAP; - PACKAGE; - RANGE; - RETURN; - - SELECT; - STRUCT; - SWITCH; - TYPE; - VAR; - keyword_end; + BREAK + CASE + CHAN + CONST + CONTINUE + + DEFAULT + DEFER + ELSE + FALLTHROUGH + FOR + + FUNC + GO + GOTO + IF + IMPORT + + INTERFACE + MAP + PACKAGE + RANGE + RETURN + + SELECT + STRUCT + SWITCH + TYPE + VAR + keyword_end ) @@ -241,7 +241,7 @@ func (tok Token) String() string { if str, exists := tokens[tok]; exists { return str } - return "token(" + strconv.Itoa(int(tok)) + ")"; + return "token(" + strconv.Itoa(int(tok)) + ")" } @@ -252,9 +252,9 @@ func (tok Token) String() string { // selector, indexing, and other operator and delimiter tokens. // const ( - LowestPrec = 0; // non-operators - UnaryPrec = 7; - HighestPrec = 8; + LowestPrec = 0 // non-operators + UnaryPrec = 7 + HighestPrec = 8 ) @@ -277,14 +277,14 @@ func (op Token) Precedence() int { case MUL, QUO, REM, SHL, SHR, AND, AND_NOT: return 6 } - return LowestPrec; + return LowestPrec } var keywords map[string]Token func init() { - keywords = make(map[string]Token); + keywords = make(map[string]Token) for i := keyword_beg + 1; i < keyword_end; i++ { keywords[tokens[i]] = i } @@ -299,7 +299,7 @@ func Lookup(ident []byte) Token { if tok, is_keyword := keywords[string(ident)]; is_keyword { return tok } - return IDENT; + return IDENT } @@ -308,50 +308,50 @@ func Lookup(ident []byte) Token { // IsLiteral returns true for tokens corresponding to identifiers // and basic type literals; returns false otherwise. // -func (tok Token) IsLiteral() bool { return literal_beg < tok && tok < literal_end } +func (tok Token) IsLiteral() bool { return literal_beg < tok && tok < literal_end } // IsOperator returns true for tokens corresponding to operators and // delimiters; returns false otherwise. // -func (tok Token) IsOperator() bool { return operator_beg < tok && tok < operator_end } +func (tok Token) IsOperator() bool { return operator_beg < tok && tok < operator_end } // IsKeyword returns true for tokens corresponding to keywords; // returns false otherwise. // -func (tok Token) IsKeyword() bool { return keyword_beg < tok && tok < keyword_end } +func (tok Token) IsKeyword() bool { return keyword_beg < tok && tok < keyword_end } // Token source positions are represented by a Position value. // A Position is valid if the line number is > 0. // type Position struct { - Filename string; // filename, if any - Offset int; // byte offset, starting at 0 - Line int; // line number, starting at 1 - Column int; // column number, starting at 1 (character count) + Filename string // filename, if any + Offset int // byte offset, starting at 0 + Line int // line number, starting at 1 + Column int // column number, starting at 1 (character count) } // Pos is an accessor method for anonymous Position fields. // It returns its receiver. // -func (pos *Position) Pos() Position { return *pos } +func (pos *Position) Pos() Position { return *pos } // IsValid returns true if the position is valid. -func (pos *Position) IsValid() bool { return pos.Line > 0 } +func (pos *Position) IsValid() bool { return pos.Line > 0 } func (pos Position) String() string { - s := pos.Filename; + s := pos.Filename if pos.IsValid() { if s != "" { s += ":" } - s += fmt.Sprintf("%d:%d", pos.Line, pos.Column); + s += fmt.Sprintf("%d:%d", pos.Line, pos.Column) } if s == "" { s = "???" } - return s; + return s } diff --git a/src/pkg/gob/codec_test.go b/src/pkg/gob/codec_test.go index c5d070155..1c4fe1fc7 100644 --- a/src/pkg/gob/codec_test.go +++ b/src/pkg/gob/codec_test.go @@ -5,19 +5,19 @@ package gob import ( - "bytes"; - "math"; - "os"; - "reflect"; - "strings"; - "testing"; - "unsafe"; + "bytes" + "math" + "os" + "reflect" + "strings" + "testing" + "unsafe" ) // Guarantee encoding format by comparing some encodings to hand-written values type EncodeT struct { - x uint64; - b []byte; + x uint64 + b []byte } var encodeT = []EncodeT{ @@ -39,12 +39,12 @@ var encodeT = []EncodeT{ // Test basic encode/decode routines for unsigned integers func TestUintCodec(t *testing.T) { - b := new(bytes.Buffer); - encState := new(encoderState); - encState.b = b; + b := new(bytes.Buffer) + encState := new(encoderState) + encState.b = b for _, tt := range encodeT { - b.Reset(); - encodeUint(encState, tt.x); + b.Reset() + encodeUint(encState, tt.x) if encState.err != nil { t.Error("encodeUint:", tt.x, encState.err) } @@ -52,14 +52,14 @@ func TestUintCodec(t *testing.T) { t.Errorf("encodeUint: %#x encode: expected % x got % x", tt.x, tt.b, b.Bytes()) } } - decState := newDecodeState(b); + decState := newDecodeState(b) for u := uint64(0); ; u = (u + 1) * 7 { - b.Reset(); - encodeUint(encState, u); + b.Reset() + encodeUint(encState, u) if encState.err != nil { t.Error("encodeUint:", u, encState.err) } - v := decodeUint(decState); + v := decodeUint(decState) if decState.err != nil { t.Error("DecodeUint:", u, decState.err) } @@ -73,16 +73,16 @@ func TestUintCodec(t *testing.T) { } func verifyInt(i int64, t *testing.T) { - var b = new(bytes.Buffer); - encState := new(encoderState); - encState.b = b; - encodeInt(encState, i); + var b = new(bytes.Buffer) + encState := new(encoderState) + encState.b = b + encodeInt(encState, i) if encState.err != nil { t.Error("encodeInt:", i, encState.err) } - decState := newDecodeState(b); - decState.buf = make([]byte, 8); - j := decodeInt(decState); + decState := newDecodeState(b) + decState.buf = make([]byte, 8) + j := decodeInt(decState) if decState.err != nil { t.Error("DecodeInt:", i, decState.err) } @@ -95,15 +95,15 @@ func verifyInt(i int64, t *testing.T) { func TestIntCodec(t *testing.T) { for u := uint64(0); ; u = (u + 1) * 7 { // Do positive and negative values - i := int64(u); - verifyInt(i, t); - verifyInt(-i, t); - verifyInt(^i, t); + i := int64(u) + verifyInt(i, t) + verifyInt(-i, t) + verifyInt(^i, t) if u&(1<<63) != 0 { break } } - verifyInt(-1<<63, t); // a tricky case + verifyInt(-1<<63, t) // a tricky case } // The result of encoding a true boolean with field number 7 @@ -116,24 +116,24 @@ var floatResult = []byte{0x07, 0xFE, 0x31, 0x40} var bytesResult = []byte{0x07, 0x05, 'h', 'e', 'l', 'l', 'o'} func newencoderState(b *bytes.Buffer) *encoderState { - b.Reset(); - state := new(encoderState); - state.b = b; - state.fieldnum = -1; - return state; + b.Reset() + state := new(encoderState) + state.b = b + state.fieldnum = -1 + return state } // Test instruction execution for encoding. // Do not run the machine yet; instead do individual instructions crafted by hand. func TestScalarEncInstructions(t *testing.T) { - var b = new(bytes.Buffer); + var b = new(bytes.Buffer) // bool { - data := struct{ a bool }{true}; - instr := &encInstr{encBool, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + data := struct{ a bool }{true} + instr := &encInstr{encBool, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(boolResult, b.Bytes()) { t.Errorf("bool enc instructions: expected % x got % x", boolResult, b.Bytes()) } @@ -141,11 +141,11 @@ func TestScalarEncInstructions(t *testing.T) { // int { - b.Reset(); - data := struct{ a int }{17}; - instr := &encInstr{encInt, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a int }{17} + instr := &encInstr{encInt, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(signedResult, b.Bytes()) { t.Errorf("int enc instructions: expected % x got % x", signedResult, b.Bytes()) } @@ -153,11 +153,11 @@ func TestScalarEncInstructions(t *testing.T) { // uint { - b.Reset(); - data := struct{ a uint }{17}; - instr := &encInstr{encUint, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a uint }{17} + instr := &encInstr{encUint, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(unsignedResult, b.Bytes()) { t.Errorf("uint enc instructions: expected % x got % x", unsignedResult, b.Bytes()) } @@ -165,11 +165,11 @@ func TestScalarEncInstructions(t *testing.T) { // int8 { - b.Reset(); - data := struct{ a int8 }{17}; - instr := &encInstr{encInt8, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a int8 }{17} + instr := &encInstr{encInt8, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(signedResult, b.Bytes()) { t.Errorf("int8 enc instructions: expected % x got % x", signedResult, b.Bytes()) } @@ -177,11 +177,11 @@ func TestScalarEncInstructions(t *testing.T) { // uint8 { - b.Reset(); - data := struct{ a uint8 }{17}; - instr := &encInstr{encUint8, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a uint8 }{17} + instr := &encInstr{encUint8, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(unsignedResult, b.Bytes()) { t.Errorf("uint8 enc instructions: expected % x got % x", unsignedResult, b.Bytes()) } @@ -189,11 +189,11 @@ func TestScalarEncInstructions(t *testing.T) { // int16 { - b.Reset(); - data := struct{ a int16 }{17}; - instr := &encInstr{encInt16, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a int16 }{17} + instr := &encInstr{encInt16, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(signedResult, b.Bytes()) { t.Errorf("int16 enc instructions: expected % x got % x", signedResult, b.Bytes()) } @@ -201,11 +201,11 @@ func TestScalarEncInstructions(t *testing.T) { // uint16 { - b.Reset(); - data := struct{ a uint16 }{17}; - instr := &encInstr{encUint16, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a uint16 }{17} + instr := &encInstr{encUint16, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(unsignedResult, b.Bytes()) { t.Errorf("uint16 enc instructions: expected % x got % x", unsignedResult, b.Bytes()) } @@ -213,11 +213,11 @@ func TestScalarEncInstructions(t *testing.T) { // int32 { - b.Reset(); - data := struct{ a int32 }{17}; - instr := &encInstr{encInt32, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a int32 }{17} + instr := &encInstr{encInt32, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(signedResult, b.Bytes()) { t.Errorf("int32 enc instructions: expected % x got % x", signedResult, b.Bytes()) } @@ -225,11 +225,11 @@ func TestScalarEncInstructions(t *testing.T) { // uint32 { - b.Reset(); - data := struct{ a uint32 }{17}; - instr := &encInstr{encUint32, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a uint32 }{17} + instr := &encInstr{encUint32, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(unsignedResult, b.Bytes()) { t.Errorf("uint32 enc instructions: expected % x got % x", unsignedResult, b.Bytes()) } @@ -237,11 +237,11 @@ func TestScalarEncInstructions(t *testing.T) { // int64 { - b.Reset(); - data := struct{ a int64 }{17}; - instr := &encInstr{encInt64, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a int64 }{17} + instr := &encInstr{encInt64, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(signedResult, b.Bytes()) { t.Errorf("int64 enc instructions: expected % x got % x", signedResult, b.Bytes()) } @@ -249,11 +249,11 @@ func TestScalarEncInstructions(t *testing.T) { // uint64 { - b.Reset(); - data := struct{ a uint64 }{17}; - instr := &encInstr{encUint64, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a uint64 }{17} + instr := &encInstr{encUint64, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(unsignedResult, b.Bytes()) { t.Errorf("uint64 enc instructions: expected % x got % x", unsignedResult, b.Bytes()) } @@ -261,11 +261,11 @@ func TestScalarEncInstructions(t *testing.T) { // float { - b.Reset(); - data := struct{ a float }{17}; - instr := &encInstr{encFloat, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a float }{17} + instr := &encInstr{encFloat, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(floatResult, b.Bytes()) { t.Errorf("float enc instructions: expected % x got % x", floatResult, b.Bytes()) } @@ -273,11 +273,11 @@ func TestScalarEncInstructions(t *testing.T) { // float32 { - b.Reset(); - data := struct{ a float32 }{17}; - instr := &encInstr{encFloat32, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a float32 }{17} + instr := &encInstr{encFloat32, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(floatResult, b.Bytes()) { t.Errorf("float32 enc instructions: expected % x got % x", floatResult, b.Bytes()) } @@ -285,11 +285,11 @@ func TestScalarEncInstructions(t *testing.T) { // float64 { - b.Reset(); - data := struct{ a float64 }{17}; - instr := &encInstr{encFloat64, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a float64 }{17} + instr := &encInstr{encFloat64, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(floatResult, b.Bytes()) { t.Errorf("float64 enc instructions: expected % x got % x", floatResult, b.Bytes()) } @@ -297,11 +297,11 @@ func TestScalarEncInstructions(t *testing.T) { // bytes == []uint8 { - b.Reset(); - data := struct{ a []byte }{strings.Bytes("hello")}; - instr := &encInstr{encUint8Array, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a []byte }{strings.Bytes("hello")} + instr := &encInstr{encUint8Array, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(bytesResult, b.Bytes()) { t.Errorf("bytes enc instructions: expected % x got % x", bytesResult, b.Bytes()) } @@ -309,11 +309,11 @@ func TestScalarEncInstructions(t *testing.T) { // string { - b.Reset(); - data := struct{ a string }{"hello"}; - instr := &encInstr{encString, 6, 0, 0}; - state := newencoderState(b); - instr.op(instr, state, unsafe.Pointer(&data)); + b.Reset() + data := struct{ a string }{"hello"} + instr := &encInstr{encString, 6, 0, 0} + state := newencoderState(b) + instr.op(instr, state, unsafe.Pointer(&data)) if !bytes.Equal(bytesResult, b.Bytes()) { t.Errorf("string enc instructions: expected % x got % x", bytesResult, b.Bytes()) } @@ -321,36 +321,36 @@ func TestScalarEncInstructions(t *testing.T) { } func execDec(typ string, instr *decInstr, state *decodeState, t *testing.T, p unsafe.Pointer) { - v := int(decodeUint(state)); + v := int(decodeUint(state)) if state.err != nil { t.Fatalf("decoding %s field: %v", typ, state.err) } if v+state.fieldnum != 6 { t.Fatalf("decoding field number %d, got %d", 6, v+state.fieldnum) } - instr.op(instr, state, decIndirect(p, instr.indir)); - state.fieldnum = 6; + instr.op(instr, state, decIndirect(p, instr.indir)) + state.fieldnum = 6 } func newDecodeStateFromData(data []byte) *decodeState { - state := newDecodeState(bytes.NewBuffer(data)); - state.fieldnum = -1; - return state; + state := newDecodeState(bytes.NewBuffer(data)) + state.fieldnum = -1 + return state } // Test instruction execution for decoding. // Do not run the machine yet; instead do individual instructions crafted by hand. func TestScalarDecInstructions(t *testing.T) { - ovfl := os.ErrorString("overflow"); + ovfl := os.ErrorString("overflow") // bool { var data struct { - a bool; + a bool } - instr := &decInstr{decBool, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(boolResult); - execDec("bool", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decBool, 6, 0, 0, ovfl} + state := newDecodeStateFromData(boolResult) + execDec("bool", instr, state, t, unsafe.Pointer(&data)) if data.a != true { t.Errorf("bool a = %v not true", data.a) } @@ -358,11 +358,11 @@ func TestScalarDecInstructions(t *testing.T) { // int { var data struct { - a int; + a int } - instr := &decInstr{decOpMap[valueKind(data.a)], 6, 0, 0, ovfl}; - state := newDecodeStateFromData(signedResult); - execDec("int", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decOpMap[valueKind(data.a)], 6, 0, 0, ovfl} + state := newDecodeStateFromData(signedResult) + execDec("int", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("int a = %v not 17", data.a) } @@ -371,11 +371,11 @@ func TestScalarDecInstructions(t *testing.T) { // uint { var data struct { - a uint; + a uint } - instr := &decInstr{decOpMap[valueKind(data.a)], 6, 0, 0, ovfl}; - state := newDecodeStateFromData(unsignedResult); - execDec("uint", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decOpMap[valueKind(data.a)], 6, 0, 0, ovfl} + state := newDecodeStateFromData(unsignedResult) + execDec("uint", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("uint a = %v not 17", data.a) } @@ -384,11 +384,11 @@ func TestScalarDecInstructions(t *testing.T) { // int8 { var data struct { - a int8; + a int8 } - instr := &decInstr{decInt8, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(signedResult); - execDec("int8", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decInt8, 6, 0, 0, ovfl} + state := newDecodeStateFromData(signedResult) + execDec("int8", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("int8 a = %v not 17", data.a) } @@ -397,11 +397,11 @@ func TestScalarDecInstructions(t *testing.T) { // uint8 { var data struct { - a uint8; + a uint8 } - instr := &decInstr{decUint8, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(unsignedResult); - execDec("uint8", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decUint8, 6, 0, 0, ovfl} + state := newDecodeStateFromData(unsignedResult) + execDec("uint8", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("uint8 a = %v not 17", data.a) } @@ -410,11 +410,11 @@ func TestScalarDecInstructions(t *testing.T) { // int16 { var data struct { - a int16; + a int16 } - instr := &decInstr{decInt16, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(signedResult); - execDec("int16", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decInt16, 6, 0, 0, ovfl} + state := newDecodeStateFromData(signedResult) + execDec("int16", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("int16 a = %v not 17", data.a) } @@ -423,11 +423,11 @@ func TestScalarDecInstructions(t *testing.T) { // uint16 { var data struct { - a uint16; + a uint16 } - instr := &decInstr{decUint16, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(unsignedResult); - execDec("uint16", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decUint16, 6, 0, 0, ovfl} + state := newDecodeStateFromData(unsignedResult) + execDec("uint16", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("uint16 a = %v not 17", data.a) } @@ -436,11 +436,11 @@ func TestScalarDecInstructions(t *testing.T) { // int32 { var data struct { - a int32; + a int32 } - instr := &decInstr{decInt32, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(signedResult); - execDec("int32", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decInt32, 6, 0, 0, ovfl} + state := newDecodeStateFromData(signedResult) + execDec("int32", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("int32 a = %v not 17", data.a) } @@ -449,11 +449,11 @@ func TestScalarDecInstructions(t *testing.T) { // uint32 { var data struct { - a uint32; + a uint32 } - instr := &decInstr{decUint32, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(unsignedResult); - execDec("uint32", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decUint32, 6, 0, 0, ovfl} + state := newDecodeStateFromData(unsignedResult) + execDec("uint32", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("uint32 a = %v not 17", data.a) } @@ -462,11 +462,11 @@ func TestScalarDecInstructions(t *testing.T) { // uintptr { var data struct { - a uintptr; + a uintptr } - instr := &decInstr{decOpMap[valueKind(data.a)], 6, 0, 0, ovfl}; - state := newDecodeStateFromData(unsignedResult); - execDec("uintptr", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decOpMap[valueKind(data.a)], 6, 0, 0, ovfl} + state := newDecodeStateFromData(unsignedResult) + execDec("uintptr", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("uintptr a = %v not 17", data.a) } @@ -475,11 +475,11 @@ func TestScalarDecInstructions(t *testing.T) { // int64 { var data struct { - a int64; + a int64 } - instr := &decInstr{decInt64, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(signedResult); - execDec("int64", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decInt64, 6, 0, 0, ovfl} + state := newDecodeStateFromData(signedResult) + execDec("int64", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("int64 a = %v not 17", data.a) } @@ -488,11 +488,11 @@ func TestScalarDecInstructions(t *testing.T) { // uint64 { var data struct { - a uint64; + a uint64 } - instr := &decInstr{decUint64, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(unsignedResult); - execDec("uint64", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decUint64, 6, 0, 0, ovfl} + state := newDecodeStateFromData(unsignedResult) + execDec("uint64", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("uint64 a = %v not 17", data.a) } @@ -501,11 +501,11 @@ func TestScalarDecInstructions(t *testing.T) { // float { var data struct { - a float; + a float } - instr := &decInstr{decOpMap[valueKind(data.a)], 6, 0, 0, ovfl}; - state := newDecodeStateFromData(floatResult); - execDec("float", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decOpMap[valueKind(data.a)], 6, 0, 0, ovfl} + state := newDecodeStateFromData(floatResult) + execDec("float", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("float a = %v not 17", data.a) } @@ -514,11 +514,11 @@ func TestScalarDecInstructions(t *testing.T) { // float32 { var data struct { - a float32; + a float32 } - instr := &decInstr{decFloat32, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(floatResult); - execDec("float32", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decFloat32, 6, 0, 0, ovfl} + state := newDecodeStateFromData(floatResult) + execDec("float32", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("float32 a = %v not 17", data.a) } @@ -527,11 +527,11 @@ func TestScalarDecInstructions(t *testing.T) { // float64 { var data struct { - a float64; + a float64 } - instr := &decInstr{decFloat64, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(floatResult); - execDec("float64", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decFloat64, 6, 0, 0, ovfl} + state := newDecodeStateFromData(floatResult) + execDec("float64", instr, state, t, unsafe.Pointer(&data)) if data.a != 17 { t.Errorf("float64 a = %v not 17", data.a) } @@ -540,11 +540,11 @@ func TestScalarDecInstructions(t *testing.T) { // bytes == []uint8 { var data struct { - a []byte; + a []byte } - instr := &decInstr{decUint8Array, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(bytesResult); - execDec("bytes", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decUint8Array, 6, 0, 0, ovfl} + state := newDecodeStateFromData(bytesResult) + execDec("bytes", instr, state, t, unsafe.Pointer(&data)) if string(data.a) != "hello" { t.Errorf(`bytes a = %q not "hello"`, string(data.a)) } @@ -553,11 +553,11 @@ func TestScalarDecInstructions(t *testing.T) { // string { var data struct { - a string; + a string } - instr := &decInstr{decString, 6, 0, 0, ovfl}; - state := newDecodeStateFromData(bytesResult); - execDec("bytes", instr, state, t, unsafe.Pointer(&data)); + instr := &decInstr{decString, 6, 0, 0, ovfl} + state := newDecodeStateFromData(bytesResult) + execDec("bytes", instr, state, t, unsafe.Pointer(&data)) if data.a != "hello" { t.Errorf(`bytes a = %q not "hello"`, data.a) } @@ -566,18 +566,18 @@ func TestScalarDecInstructions(t *testing.T) { func TestEndToEnd(t *testing.T) { type T2 struct { - t string; + t string } - s1 := "string1"; - s2 := "string2"; + s1 := "string1" + s2 := "string2" type T1 struct { - a, b, c int; - n *[3]float; - strs *[2]string; - int64s *[]int64; - s string; - y []byte; - t *T2; + a, b, c int + n *[3]float + strs *[2]string + int64s *[]int64 + s string + y []byte + t *T2 } t1 := &T1{ a: 17, @@ -589,14 +589,14 @@ func TestEndToEnd(t *testing.T) { s: "Now is the time", y: strings.Bytes("hello, sailor"), t: &T2{"this is T2"}, - }; - b := new(bytes.Buffer); - err := NewEncoder(b).Encode(t1); + } + b := new(bytes.Buffer) + err := NewEncoder(b).Encode(t1) if err != nil { t.Error("encode:", err) } - var _t1 T1; - err = NewDecoder(b).Decode(&_t1); + var _t1 T1 + err = NewDecoder(b).Decode(&_t1) if err != nil { t.Fatal("decode:", err) } @@ -607,150 +607,150 @@ func TestEndToEnd(t *testing.T) { func TestOverflow(t *testing.T) { type inputT struct { - maxi int64; - mini int64; - maxu uint64; - maxf float64; - minf float64; - } - var it inputT; - var err os.Error; - b := new(bytes.Buffer); - enc := NewEncoder(b); - dec := NewDecoder(b); + maxi int64 + mini int64 + maxu uint64 + maxf float64 + minf float64 + } + var it inputT + var err os.Error + b := new(bytes.Buffer) + enc := NewEncoder(b) + dec := NewDecoder(b) // int8 - b.Reset(); + b.Reset() it = inputT{ maxi: math.MaxInt8 + 1, - }; + } type outi8 struct { - maxi int8; - mini int8; + maxi int8 + mini int8 } - var o1 outi8; - enc.Encode(it); - err = dec.Decode(&o1); + var o1 outi8 + enc.Encode(it) + err = dec.Decode(&o1) if err == nil || err.String() != `value for "maxi" out of range` { t.Error("wrong overflow error for int8:", err) } it = inputT{ mini: math.MinInt8 - 1, - }; - b.Reset(); - enc.Encode(it); - err = dec.Decode(&o1); + } + b.Reset() + enc.Encode(it) + err = dec.Decode(&o1) if err == nil || err.String() != `value for "mini" out of range` { t.Error("wrong underflow error for int8:", err) } // int16 - b.Reset(); + b.Reset() it = inputT{ maxi: math.MaxInt16 + 1, - }; + } type outi16 struct { - maxi int16; - mini int16; + maxi int16 + mini int16 } - var o2 outi16; - enc.Encode(it); - err = dec.Decode(&o2); + var o2 outi16 + enc.Encode(it) + err = dec.Decode(&o2) if err == nil || err.String() != `value for "maxi" out of range` { t.Error("wrong overflow error for int16:", err) } it = inputT{ mini: math.MinInt16 - 1, - }; - b.Reset(); - enc.Encode(it); - err = dec.Decode(&o2); + } + b.Reset() + enc.Encode(it) + err = dec.Decode(&o2) if err == nil || err.String() != `value for "mini" out of range` { t.Error("wrong underflow error for int16:", err) } // int32 - b.Reset(); + b.Reset() it = inputT{ maxi: math.MaxInt32 + 1, - }; + } type outi32 struct { - maxi int32; - mini int32; + maxi int32 + mini int32 } - var o3 outi32; - enc.Encode(it); - err = dec.Decode(&o3); + var o3 outi32 + enc.Encode(it) + err = dec.Decode(&o3) if err == nil || err.String() != `value for "maxi" out of range` { t.Error("wrong overflow error for int32:", err) } it = inputT{ mini: math.MinInt32 - 1, - }; - b.Reset(); - enc.Encode(it); - err = dec.Decode(&o3); + } + b.Reset() + enc.Encode(it) + err = dec.Decode(&o3) if err == nil || err.String() != `value for "mini" out of range` { t.Error("wrong underflow error for int32:", err) } // uint8 - b.Reset(); + b.Reset() it = inputT{ maxu: math.MaxUint8 + 1, - }; + } type outu8 struct { - maxu uint8; + maxu uint8 } - var o4 outu8; - enc.Encode(it); - err = dec.Decode(&o4); + var o4 outu8 + enc.Encode(it) + err = dec.Decode(&o4) if err == nil || err.String() != `value for "maxu" out of range` { t.Error("wrong overflow error for uint8:", err) } // uint16 - b.Reset(); + b.Reset() it = inputT{ maxu: math.MaxUint16 + 1, - }; + } type outu16 struct { - maxu uint16; + maxu uint16 } - var o5 outu16; - enc.Encode(it); - err = dec.Decode(&o5); + var o5 outu16 + enc.Encode(it) + err = dec.Decode(&o5) if err == nil || err.String() != `value for "maxu" out of range` { t.Error("wrong overflow error for uint16:", err) } // uint32 - b.Reset(); + b.Reset() it = inputT{ maxu: math.MaxUint32 + 1, - }; + } type outu32 struct { - maxu uint32; + maxu uint32 } - var o6 outu32; - enc.Encode(it); - err = dec.Decode(&o6); + var o6 outu32 + enc.Encode(it) + err = dec.Decode(&o6) if err == nil || err.String() != `value for "maxu" out of range` { t.Error("wrong overflow error for uint32:", err) } // float32 - b.Reset(); + b.Reset() it = inputT{ maxf: math.MaxFloat32 * 2, - }; + } type outf32 struct { - maxf float32; - minf float32; + maxf float32 + minf float32 } - var o7 outf32; - enc.Encode(it); - err = dec.Decode(&o7); + var o7 outf32 + enc.Encode(it) + err = dec.Decode(&o7) if err == nil || err.String() != `value for "maxf" out of range` { t.Error("wrong overflow error for float32:", err) } @@ -759,18 +759,18 @@ func TestOverflow(t *testing.T) { func TestNesting(t *testing.T) { type RT struct { - a string; - next *RT; - } - rt := new(RT); - rt.a = "level1"; - rt.next = new(RT); - rt.next.a = "level2"; - b := new(bytes.Buffer); - NewEncoder(b).Encode(rt); - var drt RT; - dec := NewDecoder(b); - err := dec.Decode(&drt); + a string + next *RT + } + rt := new(RT) + rt.a = "level1" + rt.next = new(RT) + rt.next.a = "level2" + b := new(bytes.Buffer) + NewEncoder(b).Encode(rt) + var drt RT + dec := NewDecoder(b) + err := dec.Decode(&drt) if err != nil { t.Errorf("decoder error:", err) } @@ -787,122 +787,122 @@ func TestNesting(t *testing.T) { // These three structures have the same data with different indirections type T0 struct { - a int; - b int; - c int; - d int; + a int + b int + c int + d int } type T1 struct { - a int; - b *int; - c **int; - d ***int; + a int + b *int + c **int + d ***int } type T2 struct { - a ***int; - b **int; - c *int; - d int; + a ***int + b **int + c *int + d int } func TestAutoIndirection(t *testing.T) { // First transfer t1 into t0 - var t1 T1; - t1.a = 17; - t1.b = new(int); - *t1.b = 177; - t1.c = new(*int); - *t1.c = new(int); - **t1.c = 1777; - t1.d = new(**int); - *t1.d = new(*int); - **t1.d = new(int); - ***t1.d = 17777; - b := new(bytes.Buffer); - enc := NewEncoder(b); - enc.Encode(t1); - dec := NewDecoder(b); - var t0 T0; - dec.Decode(&t0); + var t1 T1 + t1.a = 17 + t1.b = new(int) + *t1.b = 177 + t1.c = new(*int) + *t1.c = new(int) + **t1.c = 1777 + t1.d = new(**int) + *t1.d = new(*int) + **t1.d = new(int) + ***t1.d = 17777 + b := new(bytes.Buffer) + enc := NewEncoder(b) + enc.Encode(t1) + dec := NewDecoder(b) + var t0 T0 + dec.Decode(&t0) if t0.a != 17 || t0.b != 177 || t0.c != 1777 || t0.d != 17777 { t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0) } // Now transfer t2 into t0 - var t2 T2; - t2.d = 17777; - t2.c = new(int); - *t2.c = 1777; - t2.b = new(*int); - *t2.b = new(int); - **t2.b = 177; - t2.a = new(**int); - *t2.a = new(*int); - **t2.a = new(int); - ***t2.a = 17; - b.Reset(); - enc.Encode(t2); - t0 = T0{}; - dec.Decode(&t0); + var t2 T2 + t2.d = 17777 + t2.c = new(int) + *t2.c = 1777 + t2.b = new(*int) + *t2.b = new(int) + **t2.b = 177 + t2.a = new(**int) + *t2.a = new(*int) + **t2.a = new(int) + ***t2.a = 17 + b.Reset() + enc.Encode(t2) + t0 = T0{} + dec.Decode(&t0) if t0.a != 17 || t0.b != 177 || t0.c != 1777 || t0.d != 17777 { t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0) } // Now transfer t0 into t1 - t0 = T0{17, 177, 1777, 17777}; - b.Reset(); - enc.Encode(t0); - t1 = T1{}; - dec.Decode(&t1); + t0 = T0{17, 177, 1777, 17777} + b.Reset() + enc.Encode(t0) + t1 = T1{} + dec.Decode(&t1) if t1.a != 17 || *t1.b != 177 || **t1.c != 1777 || ***t1.d != 17777 { t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.a, *t1.b, **t1.c, ***t1.d) } // Now transfer t0 into t2 - b.Reset(); - enc.Encode(t0); - t2 = T2{}; - dec.Decode(&t2); + b.Reset() + enc.Encode(t0) + t2 = T2{} + dec.Decode(&t2) if ***t2.a != 17 || **t2.b != 177 || *t2.c != 1777 || t2.d != 17777 { t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.a, **t2.b, *t2.c, t2.d) } // Now do t2 again but without pre-allocated pointers. - b.Reset(); - enc.Encode(t0); - ***t2.a = 0; - **t2.b = 0; - *t2.c = 0; - t2.d = 0; - dec.Decode(&t2); + b.Reset() + enc.Encode(t0) + ***t2.a = 0 + **t2.b = 0 + *t2.c = 0 + t2.d = 0 + dec.Decode(&t2) if ***t2.a != 17 || **t2.b != 177 || *t2.c != 1777 || t2.d != 17777 { t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.a, **t2.b, *t2.c, t2.d) } } type RT0 struct { - a int; - b string; - c float; + a int + b string + c float } type RT1 struct { - c float; - b string; - a int; - notSet string; + c float + b string + a int + notSet string } func TestReorderedFields(t *testing.T) { - var rt0 RT0; - rt0.a = 17; - rt0.b = "hello"; - rt0.c = 3.14159; - b := new(bytes.Buffer); - NewEncoder(b).Encode(rt0); - dec := NewDecoder(b); - var rt1 RT1; + var rt0 RT0 + rt0.a = 17 + rt0.b = "hello" + rt0.c = 3.14159 + b := new(bytes.Buffer) + NewEncoder(b).Encode(rt0) + dec := NewDecoder(b) + var rt1 RT1 // Wire type is RT0, local type is RT1. - err := dec.Decode(&rt1); + err := dec.Decode(&rt1) if err != nil { t.Error("decode error:", err) } @@ -913,37 +913,37 @@ func TestReorderedFields(t *testing.T) { // Like an RT0 but with fields we'll ignore on the decode side. type IT0 struct { - a int64; - b string; - ignore_d []int; - ignore_e [3]float; - ignore_f bool; - ignore_g string; - ignore_h []byte; - ignore_i *RT1; - c float; + a int64 + b string + ignore_d []int + ignore_e [3]float + ignore_f bool + ignore_g string + ignore_h []byte + ignore_i *RT1 + c float } func TestIgnoredFields(t *testing.T) { - var it0 IT0; - it0.a = 17; - it0.b = "hello"; - it0.c = 3.14159; - it0.ignore_d = []int{1, 2, 3}; - it0.ignore_e[0] = 1.0; - it0.ignore_e[1] = 2.0; - it0.ignore_e[2] = 3.0; - it0.ignore_f = true; - it0.ignore_g = "pay no attention"; - it0.ignore_h = strings.Bytes("to the curtain"); - it0.ignore_i = &RT1{3.1, "hi", 7, "hello"}; - - b := new(bytes.Buffer); - NewEncoder(b).Encode(it0); - dec := NewDecoder(b); - var rt1 RT1; + var it0 IT0 + it0.a = 17 + it0.b = "hello" + it0.c = 3.14159 + it0.ignore_d = []int{1, 2, 3} + it0.ignore_e[0] = 1.0 + it0.ignore_e[1] = 2.0 + it0.ignore_e[2] = 3.0 + it0.ignore_f = true + it0.ignore_g = "pay no attention" + it0.ignore_h = strings.Bytes("to the curtain") + it0.ignore_i = &RT1{3.1, "hi", 7, "hello"} + + b := new(bytes.Buffer) + NewEncoder(b).Encode(it0) + dec := NewDecoder(b) + var rt1 RT1 // Wire type is IT0, local type is RT1. - err := dec.Decode(&rt1); + err := dec.Decode(&rt1) if err != nil { t.Error("error: ", err) } @@ -953,15 +953,15 @@ func TestIgnoredFields(t *testing.T) { } type Bad0 struct { - inter interface{}; - c float; + inter interface{} + c float } func TestInvalidField(t *testing.T) { - var bad0 Bad0; - bad0.inter = 17; - b := new(bytes.Buffer); - err := encode(b, &bad0); + var bad0 Bad0 + bad0.inter = 17 + b := new(bytes.Buffer) + err := encode(b, &bad0) if err == nil { t.Error("expected error; got none") } else if strings.Index(err.String(), "interface") < 0 { diff --git a/src/pkg/gob/decode.go b/src/pkg/gob/decode.go index a3294ac50..c7f314369 100644 --- a/src/pkg/gob/decode.go +++ b/src/pkg/gob/decode.go @@ -8,35 +8,35 @@ package gob // the allocations in this file that use unsafe.Pointer. import ( - "bytes"; - "io"; - "math"; - "os"; - "reflect"; - "runtime"; - "unsafe"; + "bytes" + "io" + "math" + "os" + "reflect" + "runtime" + "unsafe" ) var ( - errBadUint = os.ErrorString("gob: encoded unsigned integer out of range"); - errBadType = os.ErrorString("gob: unknown type id or corrupted data"); - errRange = os.ErrorString("gob: internal error: field numbers out of bounds"); - errNotStruct = os.ErrorString("gob: TODO: can only handle structs"); + errBadUint = os.ErrorString("gob: encoded unsigned integer out of range") + errBadType = os.ErrorString("gob: unknown type id or corrupted data") + errRange = os.ErrorString("gob: internal error: field numbers out of bounds") + errNotStruct = os.ErrorString("gob: TODO: can only handle structs") ) // The global execution state of an instance of the decoder. type decodeState struct { - b *bytes.Buffer; - err os.Error; - fieldnum int; // the last field number read. - buf []byte; + b *bytes.Buffer + err os.Error + fieldnum int // the last field number read. + buf []byte } func newDecodeState(b *bytes.Buffer) *decodeState { - d := new(decodeState); - d.b = b; - d.buf = make([]byte, uint64Size); - return d; + d := new(decodeState) + d.b = b + d.buf = make([]byte, uint64Size) + return d } func overflow(name string) os.ErrorString { @@ -46,33 +46,33 @@ func overflow(name string) os.ErrorString { // decodeUintReader reads an encoded unsigned integer from an io.Reader. // Used only by the Decoder to read the message length. func decodeUintReader(r io.Reader, buf []byte) (x uint64, err os.Error) { - _, err = r.Read(buf[0:1]); + _, err = r.Read(buf[0:1]) if err != nil { return } - b := buf[0]; + b := buf[0] if b <= 0x7f { return uint64(b), nil } - nb := -int(int8(b)); + nb := -int(int8(b)) if nb > uint64Size { - err = errBadUint; - return; + err = errBadUint + return } - var n int; - n, err = io.ReadFull(r, buf[0:nb]); + var n int + n, err = io.ReadFull(r, buf[0:nb]) if err != nil { if err == os.EOF { err = io.ErrUnexpectedEOF } - return; + return } // Could check that the high byte is zero but it's not worth it. for i := 0; i < n; i++ { - x <<= 8; - x |= uint64(buf[i]); + x <<= 8 + x |= uint64(buf[i]) } - return; + return } // decodeUint reads an encoded unsigned integer from state.r. @@ -82,50 +82,50 @@ func decodeUint(state *decodeState) (x uint64) { if state.err != nil { return } - var b uint8; - b, state.err = state.b.ReadByte(); - if b <= 0x7f { // includes state.err != nil + var b uint8 + b, state.err = state.b.ReadByte() + if b <= 0x7f { // includes state.err != nil return uint64(b) } - nb := -int(int8(b)); + nb := -int(int8(b)) if nb > uint64Size { - state.err = errBadUint; - return; + state.err = errBadUint + return } - var n int; - n, state.err = state.b.Read(state.buf[0:nb]); + var n int + n, state.err = state.b.Read(state.buf[0:nb]) // Don't need to check error; it's safe to loop regardless. // Could check that the high byte is zero but it's not worth it. for i := 0; i < n; i++ { - x <<= 8; - x |= uint64(state.buf[i]); + x <<= 8 + x |= uint64(state.buf[i]) } - return x; + return x } // decodeInt reads an encoded signed integer from state.r. // Sets state.err. If state.err is already non-nil, it does nothing. // Does not check for overflow. func decodeInt(state *decodeState) int64 { - x := decodeUint(state); + x := decodeUint(state) if state.err != nil { return 0 } if x&1 != 0 { return ^int64(x >> 1) } - return int64(x >> 1); + return int64(x >> 1) } type decOp func(i *decInstr, state *decodeState, p unsafe.Pointer) // The 'instructions' of the decoding machine type decInstr struct { - op decOp; - field int; // field number of the wire type - indir int; // how many pointer indirections to reach the value in the struct - offset uintptr; // offset in the structure of the field to encode - ovfl os.ErrorString; // error message for overflow/underflow (for arrays, of the elements) + op decOp + field int // field number of the wire type + indir int // how many pointer indirections to reach the value in the struct + offset uintptr // offset in the structure of the field to encode + ovfl os.ErrorString // error message for overflow/underflow (for arrays, of the elements) } // Since the encoder writes no zeros, if we arrive at a decoder we have @@ -142,9 +142,9 @@ func decIndirect(p unsafe.Pointer, indir int) unsafe.Pointer { // Allocation required *(*unsafe.Pointer)(p) = unsafe.Pointer(new(unsafe.Pointer)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - return p; + return p } func ignoreUint(i *decInstr, state *decodeState, p unsafe.Pointer) { @@ -156,9 +156,9 @@ func decBool(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new(bool)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - *(*bool)(p) = decodeInt(state) != 0; + *(*bool)(p) = decodeInt(state) != 0 } func decInt8(i *decInstr, state *decodeState, p unsafe.Pointer) { @@ -166,9 +166,9 @@ func decInt8(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int8)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - v := decodeInt(state); + v := decodeInt(state) if v < math.MinInt8 || math.MaxInt8 < v { state.err = i.ovfl } else { @@ -181,9 +181,9 @@ func decUint8(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint8)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - v := decodeUint(state); + v := decodeUint(state) if math.MaxUint8 < v { state.err = i.ovfl } else { @@ -196,9 +196,9 @@ func decInt16(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int16)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - v := decodeInt(state); + v := decodeInt(state) if v < math.MinInt16 || math.MaxInt16 < v { state.err = i.ovfl } else { @@ -211,9 +211,9 @@ func decUint16(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint16)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - v := decodeUint(state); + v := decodeUint(state) if math.MaxUint16 < v { state.err = i.ovfl } else { @@ -226,9 +226,9 @@ func decInt32(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int32)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - v := decodeInt(state); + v := decodeInt(state) if v < math.MinInt32 || math.MaxInt32 < v { state.err = i.ovfl } else { @@ -241,9 +241,9 @@ func decUint32(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint32)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - v := decodeUint(state); + v := decodeUint(state) if math.MaxUint32 < v { state.err = i.ovfl } else { @@ -256,9 +256,9 @@ func decInt64(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int64)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - *(*int64)(p) = int64(decodeInt(state)); + *(*int64)(p) = int64(decodeInt(state)) } func decUint64(i *decInstr, state *decodeState, p unsafe.Pointer) { @@ -266,9 +266,9 @@ func decUint64(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint64)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - *(*uint64)(p) = uint64(decodeUint(state)); + *(*uint64)(p) = uint64(decodeUint(state)) } // Floating-point numbers are transmitted as uint64s holding the bits @@ -277,13 +277,13 @@ func decUint64(i *decInstr, state *decodeState, p unsafe.Pointer) { // (for example) transmit more compactly. This routine does the // unswizzling. func floatFromBits(u uint64) float64 { - var v uint64; + var v uint64 for i := 0; i < 8; i++ { - v <<= 8; - v |= u & 0xFF; - u >>= 8; + v <<= 8 + v |= u & 0xFF + u >>= 8 } - return math.Float64frombits(v); + return math.Float64frombits(v) } func decFloat32(i *decInstr, state *decodeState, p unsafe.Pointer) { @@ -291,14 +291,14 @@ func decFloat32(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new(float32)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - v := floatFromBits(decodeUint(state)); - av := v; + v := floatFromBits(decodeUint(state)) + av := v if av < 0 { av = -av } - if math.MaxFloat32 < av { // underflow is OK + if math.MaxFloat32 < av { // underflow is OK state.err = i.ovfl } else { *(*float32)(p) = float32(v) @@ -310,9 +310,9 @@ func decFloat64(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new(float64)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - *(*float64)(p) = floatFromBits(uint64(decodeUint(state))); + *(*float64)(p) = floatFromBits(uint64(decodeUint(state))) } // uint8 arrays are encoded as an unsigned count followed by the raw bytes. @@ -321,11 +321,11 @@ func decUint8Array(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new([]uint8)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - b := make([]uint8, decodeUint(state)); - state.b.Read(b); - *(*[]uint8)(p) = b; + b := make([]uint8, decodeUint(state)) + state.b.Read(b) + *(*[]uint8)(p) = b } // Strings are encoded as an unsigned count followed by the raw bytes. @@ -334,16 +334,16 @@ func decString(i *decInstr, state *decodeState, p unsafe.Pointer) { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(new([]byte)) } - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) } - b := make([]byte, decodeUint(state)); - state.b.Read(b); - *(*string)(p) = string(b); + b := make([]byte, decodeUint(state)) + state.b.Read(b) + *(*string)(p) = string(b) } func ignoreUint8Array(i *decInstr, state *decodeState, p unsafe.Pointer) { - b := make([]byte, decodeUint(state)); - state.b.Read(b); + b := make([]byte, decodeUint(state)) + state.b.Read(b) } // Execution engine @@ -351,13 +351,13 @@ func ignoreUint8Array(i *decInstr, state *decodeState, p unsafe.Pointer) { // The encoder engine is an array of instructions indexed by field number of the incoming // decoder. It is executed with random access according to field number. type decEngine struct { - instr []decInstr; - numInstr int; // the number of active instructions + instr []decInstr + numInstr int // the number of active instructions } func decodeStruct(engine *decEngine, rtyp *reflect.StructType, b *bytes.Buffer, p uintptr, indir int) os.Error { if indir > 0 { - up := unsafe.Pointer(p); + up := unsafe.Pointer(p) if indir > 1 { up = decIndirect(up, indir) } @@ -365,120 +365,120 @@ func decodeStruct(engine *decEngine, rtyp *reflect.StructType, b *bytes.Buffer, // Allocate object. *(*unsafe.Pointer)(up) = unsafe.New((*runtime.StructType)(unsafe.Pointer(rtyp))) } - p = *(*uintptr)(up); + p = *(*uintptr)(up) } - state := newDecodeState(b); - state.fieldnum = -1; - basep := p; + state := newDecodeState(b) + state.fieldnum = -1 + basep := p for state.err == nil { - delta := int(decodeUint(state)); + delta := int(decodeUint(state)) if delta < 0 { - state.err = os.ErrorString("gob decode: corrupted data: negative delta"); - break; + state.err = os.ErrorString("gob decode: corrupted data: negative delta") + break } - if state.err != nil || delta == 0 { // struct terminator is zero delta fieldnum + if state.err != nil || delta == 0 { // struct terminator is zero delta fieldnum break } - fieldnum := state.fieldnum + delta; + fieldnum := state.fieldnum + delta if fieldnum >= len(engine.instr) { - state.err = errRange; - break; + state.err = errRange + break } - instr := &engine.instr[fieldnum]; - p := unsafe.Pointer(basep + instr.offset); + instr := &engine.instr[fieldnum] + p := unsafe.Pointer(basep + instr.offset) if instr.indir > 1 { p = decIndirect(p, instr.indir) } - instr.op(instr, state, p); - state.fieldnum = fieldnum; + instr.op(instr, state, p) + state.fieldnum = fieldnum } - return state.err; + return state.err } func ignoreStruct(engine *decEngine, b *bytes.Buffer) os.Error { - state := newDecodeState(b); - state.fieldnum = -1; + state := newDecodeState(b) + state.fieldnum = -1 for state.err == nil { - delta := int(decodeUint(state)); + delta := int(decodeUint(state)) if delta < 0 { - state.err = os.ErrorString("gob ignore decode: corrupted data: negative delta"); - break; + state.err = os.ErrorString("gob ignore decode: corrupted data: negative delta") + break } - if state.err != nil || delta == 0 { // struct terminator is zero delta fieldnum + if state.err != nil || delta == 0 { // struct terminator is zero delta fieldnum break } - fieldnum := state.fieldnum + delta; + fieldnum := state.fieldnum + delta if fieldnum >= len(engine.instr) { - state.err = errRange; - break; + state.err = errRange + break } - instr := &engine.instr[fieldnum]; - instr.op(instr, state, unsafe.Pointer(nil)); - state.fieldnum = fieldnum; + instr := &engine.instr[fieldnum] + instr.op(instr, state, unsafe.Pointer(nil)) + state.fieldnum = fieldnum } - return state.err; + return state.err } func decodeArrayHelper(state *decodeState, p uintptr, elemOp decOp, elemWid uintptr, length, elemIndir int, ovfl os.ErrorString) os.Error { - instr := &decInstr{elemOp, 0, elemIndir, 0, ovfl}; + instr := &decInstr{elemOp, 0, elemIndir, 0, ovfl} for i := 0; i < length && state.err == nil; i++ { - up := unsafe.Pointer(p); + up := unsafe.Pointer(p) if elemIndir > 1 { up = decIndirect(up, elemIndir) } - elemOp(instr, state, up); - p += uintptr(elemWid); + elemOp(instr, state, up) + p += uintptr(elemWid) } - return state.err; + return state.err } func decodeArray(atyp *reflect.ArrayType, state *decodeState, p uintptr, elemOp decOp, elemWid uintptr, length, indir, elemIndir int, ovfl os.ErrorString) os.Error { if indir > 0 { - up := unsafe.Pointer(p); + up := unsafe.Pointer(p) if *(*unsafe.Pointer)(up) == nil { // Allocate object. *(*unsafe.Pointer)(up) = unsafe.New(atyp) } - p = *(*uintptr)(up); + p = *(*uintptr)(up) } if n := decodeUint(state); n != uint64(length) { return os.ErrorString("gob: length mismatch in decodeArray") } - return decodeArrayHelper(state, p, elemOp, elemWid, length, elemIndir, ovfl); + return decodeArrayHelper(state, p, elemOp, elemWid, length, elemIndir, ovfl) } func ignoreArrayHelper(state *decodeState, elemOp decOp, length int) os.Error { - instr := &decInstr{elemOp, 0, 0, 0, os.ErrorString("no error")}; + instr := &decInstr{elemOp, 0, 0, 0, os.ErrorString("no error")} for i := 0; i < length && state.err == nil; i++ { elemOp(instr, state, nil) } - return state.err; + return state.err } func ignoreArray(state *decodeState, elemOp decOp, length int) os.Error { if n := decodeUint(state); n != uint64(length) { return os.ErrorString("gob: length mismatch in ignoreArray") } - return ignoreArrayHelper(state, elemOp, length); + return ignoreArrayHelper(state, elemOp, length) } func decodeSlice(atyp *reflect.SliceType, state *decodeState, p uintptr, elemOp decOp, elemWid uintptr, indir, elemIndir int, ovfl os.ErrorString) os.Error { - n := int(uintptr(decodeUint(state))); + n := int(uintptr(decodeUint(state))) if indir > 0 { - up := unsafe.Pointer(p); + up := unsafe.Pointer(p) if *(*unsafe.Pointer)(up) == nil { // Allocate the slice header. *(*unsafe.Pointer)(up) = unsafe.Pointer(new([]unsafe.Pointer)) } - p = *(*uintptr)(up); + p = *(*uintptr)(up) } // Allocate storage for the slice elements, that is, the underlying array. // Always write a header at p. - hdrp := (*reflect.SliceHeader)(unsafe.Pointer(p)); - hdrp.Data = uintptr(unsafe.NewArray(atyp.Elem(), n)); - hdrp.Len = n; - hdrp.Cap = n; - return decodeArrayHelper(state, hdrp.Data, elemOp, elemWid, n, elemIndir, ovfl); + hdrp := (*reflect.SliceHeader)(unsafe.Pointer(p)) + hdrp.Data = uintptr(unsafe.NewArray(atyp.Elem(), n)) + hdrp.Len = n + hdrp.Cap = n + return decodeArrayHelper(state, hdrp.Data, elemOp, elemWid, n, elemIndir, ovfl) } func ignoreSlice(state *decodeState, elemOp decOp) os.Error { @@ -512,104 +512,104 @@ var decIgnoreOpMap = map[typeId]decOp{ // Return the decoding op for the base type under rt and // the indirection count to reach it. func (dec *Decoder) decOpFor(wireId typeId, rt reflect.Type, name string) (decOp, int, os.Error) { - typ, indir := indirect(rt); - op, ok := decOpMap[reflect.Typeof(typ)]; + typ, indir := indirect(rt) + op, ok := decOpMap[reflect.Typeof(typ)] if !ok { // Special cases switch t := typ.(type) { case *reflect.SliceType: - name = "element of " + name; + name = "element of " + name if _, ok := t.Elem().(*reflect.Uint8Type); ok { - op = decUint8Array; - break; + op = decUint8Array + break } - var elemId typeId; + var elemId typeId if tt, ok := builtinIdToType[wireId]; ok { elemId = tt.(*sliceType).Elem } else { elemId = dec.wireType[wireId].slice.Elem } - elemOp, elemIndir, err := dec.decOpFor(elemId, t.Elem(), name); + elemOp, elemIndir, err := dec.decOpFor(elemId, t.Elem(), name) if err != nil { return nil, 0, err } - ovfl := overflow(name); + ovfl := overflow(name) op = func(i *decInstr, state *decodeState, p unsafe.Pointer) { state.err = decodeSlice(t, state, uintptr(p), elemOp, t.Elem().Size(), i.indir, elemIndir, ovfl) - }; + } case *reflect.ArrayType: - name = "element of " + name; - elemId := wireId.gobType().(*arrayType).Elem; - elemOp, elemIndir, err := dec.decOpFor(elemId, t.Elem(), name); + name = "element of " + name + elemId := wireId.gobType().(*arrayType).Elem + elemOp, elemIndir, err := dec.decOpFor(elemId, t.Elem(), name) if err != nil { return nil, 0, err } - ovfl := overflow(name); + ovfl := overflow(name) op = func(i *decInstr, state *decodeState, p unsafe.Pointer) { state.err = decodeArray(t, state, uintptr(p), elemOp, t.Elem().Size(), t.Len(), i.indir, elemIndir, ovfl) - }; + } case *reflect.StructType: // Generate a closure that calls out to the engine for the nested type. - enginePtr, err := dec.getDecEnginePtr(wireId, typ); + enginePtr, err := dec.getDecEnginePtr(wireId, typ) if err != nil { return nil, 0, err } op = func(i *decInstr, state *decodeState, p unsafe.Pointer) { // indirect through enginePtr to delay evaluation for recursive structs state.err = decodeStruct(*enginePtr, t, state.b, uintptr(p), i.indir) - }; + } } } if op == nil { return nil, 0, os.ErrorString("gob: decode can't handle type " + rt.String()) } - return op, indir, nil; + return op, indir, nil } // Return the decoding op for a field that has no destination. func (dec *Decoder) decIgnoreOpFor(wireId typeId) (decOp, os.Error) { - op, ok := decIgnoreOpMap[wireId]; + op, ok := decIgnoreOpMap[wireId] if !ok { // Special cases switch t := wireId.gobType().(type) { case *sliceType: - elemId := wireId.gobType().(*sliceType).Elem; - elemOp, err := dec.decIgnoreOpFor(elemId); + elemId := wireId.gobType().(*sliceType).Elem + elemOp, err := dec.decIgnoreOpFor(elemId) if err != nil { return nil, err } op = func(i *decInstr, state *decodeState, p unsafe.Pointer) { state.err = ignoreSlice(state, elemOp) - }; + } case *arrayType: - elemId := wireId.gobType().(*arrayType).Elem; - elemOp, err := dec.decIgnoreOpFor(elemId); + elemId := wireId.gobType().(*arrayType).Elem + elemOp, err := dec.decIgnoreOpFor(elemId) if err != nil { return nil, err } op = func(i *decInstr, state *decodeState, p unsafe.Pointer) { state.err = ignoreArray(state, elemOp, t.Len) - }; + } case *structType: // Generate a closure that calls out to the engine for the nested type. - enginePtr, err := dec.getIgnoreEnginePtr(wireId); + enginePtr, err := dec.getIgnoreEnginePtr(wireId) if err != nil { return nil, err } op = func(i *decInstr, state *decodeState, p unsafe.Pointer) { // indirect through enginePtr to delay evaluation for recursive structs state.err = ignoreStruct(*enginePtr, state.b) - }; + } } } if op == nil { return nil, os.ErrorString("ignore can't handle type " + wireId.string()) } - return op, nil; + return op, nil } // Are these two gob Types compatible? @@ -618,10 +618,10 @@ func (dec *Decoder) decIgnoreOpFor(wireId typeId) (decOp, os.Error) { func (dec *Decoder) compatibleType(fr reflect.Type, fw typeId) bool { for { if pt, ok := fr.(*reflect.PtrType); ok { - fr = pt.Elem(); - continue; + fr = pt.Elem() + continue } - break; + break } switch t := fr.(type) { default: @@ -660,89 +660,89 @@ func (dec *Decoder) compatibleType(fr reflect.Type, fw typeId) bool { case *reflect.StringType: return fw == tString case *reflect.ArrayType: - aw, ok := fw.gobType().(*arrayType); - return ok && t.Len() == aw.Len && dec.compatibleType(t.Elem(), aw.Elem); + aw, ok := fw.gobType().(*arrayType) + return ok && t.Len() == aw.Len && dec.compatibleType(t.Elem(), aw.Elem) case *reflect.SliceType: // Is it an array of bytes? - et := t.Elem(); + et := t.Elem() if _, ok := et.(*reflect.Uint8Type); ok { return fw == tBytes } // Extract and compare element types. - var sw *sliceType; + var sw *sliceType if tt, ok := builtinIdToType[fw]; ok { sw = tt.(*sliceType) } else { sw = dec.wireType[fw].slice } - elem, _ := indirect(t.Elem()); - return sw != nil && dec.compatibleType(elem, sw.Elem); + elem, _ := indirect(t.Elem()) + return sw != nil && dec.compatibleType(elem, sw.Elem) case *reflect.StructType: return true } - return true; + return true } func (dec *Decoder) compileDec(remoteId typeId, rt reflect.Type) (engine *decEngine, err os.Error) { - srt, ok1 := rt.(*reflect.StructType); - var wireStruct *structType; + srt, ok1 := rt.(*reflect.StructType) + var wireStruct *structType // Builtin types can come from global pool; the rest must be defined by the decoder if t, ok := builtinIdToType[remoteId]; ok { wireStruct = t.(*structType) } else { - w, ok2 := dec.wireType[remoteId]; + w, ok2 := dec.wireType[remoteId] if !ok1 || !ok2 { return nil, errNotStruct } - wireStruct = w.strct; + wireStruct = w.strct } - engine = new(decEngine); - engine.instr = make([]decInstr, len(wireStruct.field)); + engine = new(decEngine) + engine.instr = make([]decInstr, len(wireStruct.field)) // Loop over the fields of the wire type. for fieldnum := 0; fieldnum < len(wireStruct.field); fieldnum++ { - wireField := wireStruct.field[fieldnum]; + wireField := wireStruct.field[fieldnum] // Find the field of the local type with the same name. - localField, present := srt.FieldByName(wireField.name); - ovfl := overflow(wireField.name); + localField, present := srt.FieldByName(wireField.name) + ovfl := overflow(wireField.name) // TODO(r): anonymous names if !present { - op, err := dec.decIgnoreOpFor(wireField.id); + op, err := dec.decIgnoreOpFor(wireField.id) if err != nil { return nil, err } - engine.instr[fieldnum] = decInstr{op, fieldnum, 0, 0, ovfl}; - continue; + engine.instr[fieldnum] = decInstr{op, fieldnum, 0, 0, ovfl} + continue } if !dec.compatibleType(localField.Type, wireField.id) { - details := " (" + wireField.id.string() + " incompatible with " + localField.Type.String() + ") in type " + remoteId.Name(); - return nil, os.ErrorString("gob: wrong type for field " + wireField.name + details); + details := " (" + wireField.id.string() + " incompatible with " + localField.Type.String() + ") in type " + remoteId.Name() + return nil, os.ErrorString("gob: wrong type for field " + wireField.name + details) } - op, indir, err := dec.decOpFor(wireField.id, localField.Type, localField.Name); + op, indir, err := dec.decOpFor(wireField.id, localField.Type, localField.Name) if err != nil { return nil, err } - engine.instr[fieldnum] = decInstr{op, fieldnum, indir, uintptr(localField.Offset), ovfl}; - engine.numInstr++; + engine.instr[fieldnum] = decInstr{op, fieldnum, indir, uintptr(localField.Offset), ovfl} + engine.numInstr++ } - return; + return } func (dec *Decoder) getDecEnginePtr(remoteId typeId, rt reflect.Type) (enginePtr **decEngine, err os.Error) { - decoderMap, ok := dec.decoderCache[rt]; + decoderMap, ok := dec.decoderCache[rt] if !ok { - decoderMap = make(map[typeId]**decEngine); - dec.decoderCache[rt] = decoderMap; + decoderMap = make(map[typeId]**decEngine) + dec.decoderCache[rt] = decoderMap } if enginePtr, ok = decoderMap[remoteId]; !ok { // To handle recursive types, mark this engine as underway before compiling. - enginePtr = new(*decEngine); - decoderMap[remoteId] = enginePtr; - *enginePtr, err = dec.compileDec(remoteId, rt); + enginePtr = new(*decEngine) + decoderMap[remoteId] = enginePtr + *enginePtr, err = dec.compileDec(remoteId, rt) if err != nil { decoderMap[remoteId] = nil, false } } - return; + return } // When ignoring data, in effect we compile it into this type @@ -751,42 +751,42 @@ type emptyStruct struct{} var emptyStructType = reflect.Typeof(emptyStruct{}) func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err os.Error) { - var ok bool; + var ok bool if enginePtr, ok = dec.ignorerCache[wireId]; !ok { // To handle recursive types, mark this engine as underway before compiling. - enginePtr = new(*decEngine); - dec.ignorerCache[wireId] = enginePtr; - *enginePtr, err = dec.compileDec(wireId, emptyStructType); + enginePtr = new(*decEngine) + dec.ignorerCache[wireId] = enginePtr + *enginePtr, err = dec.compileDec(wireId, emptyStructType) if err != nil { dec.ignorerCache[wireId] = nil, false } } - return; + return } func (dec *Decoder) decode(wireId typeId, e interface{}) os.Error { // Dereference down to the underlying struct type. - rt, indir := indirect(reflect.Typeof(e)); - st, ok := rt.(*reflect.StructType); + rt, indir := indirect(reflect.Typeof(e)) + st, ok := rt.(*reflect.StructType) if !ok { return os.ErrorString("gob: decode can't handle " + rt.String()) } - enginePtr, err := dec.getDecEnginePtr(wireId, rt); + enginePtr, err := dec.getDecEnginePtr(wireId, rt) if err != nil { return err } - engine := *enginePtr; + engine := *enginePtr if engine.numInstr == 0 && st.NumField() > 0 && len(wireId.gobType().(*structType).field) > 0 { - name := rt.Name(); - return os.ErrorString("gob: type mismatch: no fields matched compiling decoder for " + name); + name := rt.Name() + return os.ErrorString("gob: type mismatch: no fields matched compiling decoder for " + name) } - return decodeStruct(engine, st, dec.state.b, uintptr(reflect.NewValue(e).Addr()), indir); + return decodeStruct(engine, st, dec.state.b, uintptr(reflect.NewValue(e).Addr()), indir) } func init() { // We assume that the size of float is sufficient to tell us whether it is // equivalent to float32 or to float64. This is very unlikely to be wrong. - var op decOp; + var op decOp switch unsafe.Sizeof(float(0)) { case unsafe.Sizeof(float32(0)): op = decFloat32 @@ -795,22 +795,22 @@ func init() { default: panic("gob: unknown size of float", unsafe.Sizeof(float(0))) } - decOpMap[valueKind(float(0))] = op; + decOpMap[valueKind(float(0))] = op // A similar assumption about int and uint. Also assume int and uint have the same size. - var uop decOp; + var uop decOp switch unsafe.Sizeof(int(0)) { case unsafe.Sizeof(int32(0)): - op = decInt32; - uop = decUint32; + op = decInt32 + uop = decUint32 case unsafe.Sizeof(int64(0)): - op = decInt64; - uop = decUint64; + op = decInt64 + uop = decUint64 default: panic("gob: unknown size of int/uint", unsafe.Sizeof(int(0))) } - decOpMap[valueKind(int(0))] = op; - decOpMap[valueKind(uint(0))] = uop; + decOpMap[valueKind(int(0))] = op + decOpMap[valueKind(uint(0))] = uop // Finally uintptr switch unsafe.Sizeof(uintptr(0)) { @@ -821,5 +821,5 @@ func init() { default: panic("gob: unknown size of uintptr", unsafe.Sizeof(uintptr(0))) } - decOpMap[valueKind(uintptr(0))] = uop; + decOpMap[valueKind(uintptr(0))] = uop } diff --git a/src/pkg/gob/decoder.go b/src/pkg/gob/decoder.go index 5202c8285..73f0979ed 100644 --- a/src/pkg/gob/decoder.go +++ b/src/pkg/gob/decoder.go @@ -5,51 +5,51 @@ package gob import ( - "bytes"; - "io"; - "os"; - "reflect"; - "sync"; + "bytes" + "io" + "os" + "reflect" + "sync" ) // A Decoder manages the receipt of type and data information read from the // remote side of a connection. type Decoder struct { - mutex sync.Mutex; // each item must be received atomically - r io.Reader; // source of the data - wireType map[typeId]*wireType; // map from remote ID to local description - decoderCache map[reflect.Type]map[typeId]**decEngine; // cache of compiled engines - ignorerCache map[typeId]**decEngine; // ditto for ignored objects - state *decodeState; // reads data from in-memory buffer - countState *decodeState; // reads counts from wire - buf []byte; - countBuf [9]byte; // counts may be uint64s (unlikely!), require 9 bytes + mutex sync.Mutex // each item must be received atomically + r io.Reader // source of the data + wireType map[typeId]*wireType // map from remote ID to local description + decoderCache map[reflect.Type]map[typeId]**decEngine // cache of compiled engines + ignorerCache map[typeId]**decEngine // ditto for ignored objects + state *decodeState // reads data from in-memory buffer + countState *decodeState // reads counts from wire + buf []byte + countBuf [9]byte // counts may be uint64s (unlikely!), require 9 bytes } // NewDecoder returns a new decoder that reads from the io.Reader. func NewDecoder(r io.Reader) *Decoder { - dec := new(Decoder); - dec.r = r; - dec.wireType = make(map[typeId]*wireType); - dec.state = newDecodeState(nil); // buffer set in Decode(); rest is unimportant - dec.decoderCache = make(map[reflect.Type]map[typeId]**decEngine); - dec.ignorerCache = make(map[typeId]**decEngine); + dec := new(Decoder) + dec.r = r + dec.wireType = make(map[typeId]*wireType) + dec.state = newDecodeState(nil) // buffer set in Decode(); rest is unimportant + dec.decoderCache = make(map[reflect.Type]map[typeId]**decEngine) + dec.ignorerCache = make(map[typeId]**decEngine) - return dec; + return dec } func (dec *Decoder) recvType(id typeId) { // Have we already seen this type? That's an error if _, alreadySeen := dec.wireType[id]; alreadySeen { - dec.state.err = os.ErrorString("gob: duplicate type received"); - return; + dec.state.err = os.ErrorString("gob: duplicate type received") + return } // Type: - wire := new(wireType); - dec.state.err = dec.decode(tWireType, wire); + wire := new(wireType) + dec.state.err = dec.decode(tWireType, wire) // Remember we've seen this type. - dec.wireType[id] = wire; + dec.wireType[id] = wire } // Decode reads the next value from the connection and stores @@ -60,19 +60,19 @@ func (dec *Decoder) Decode(e interface{}) os.Error { // If e represents a value, the answer won't get back to the // caller. Make sure it's a pointer. if _, ok := reflect.Typeof(e).(*reflect.PtrType); !ok { - dec.state.err = os.ErrorString("gob: attempt to decode into a non-pointer"); - return dec.state.err; + dec.state.err = os.ErrorString("gob: attempt to decode into a non-pointer") + return dec.state.err } // Make sure we're single-threaded through here. - dec.mutex.Lock(); - defer dec.mutex.Unlock(); + dec.mutex.Lock() + defer dec.mutex.Unlock() - dec.state.err = nil; + dec.state.err = nil for { // Read a count. - var nbytes uint64; - nbytes, dec.state.err = decodeUintReader(dec.r, dec.countBuf[0:]); + var nbytes uint64 + nbytes, dec.state.err = decodeUintReader(dec.r, dec.countBuf[0:]) if dec.state.err != nil { break } @@ -80,42 +80,42 @@ func (dec *Decoder) Decode(e interface{}) os.Error { if nbytes > uint64(len(dec.buf)) { dec.buf = make([]byte, nbytes+1000) } - dec.state.b = bytes.NewBuffer(dec.buf[0:nbytes]); + dec.state.b = bytes.NewBuffer(dec.buf[0:nbytes]) // Read the data - _, dec.state.err = io.ReadFull(dec.r, dec.buf[0:nbytes]); + _, dec.state.err = io.ReadFull(dec.r, dec.buf[0:nbytes]) if dec.state.err != nil { if dec.state.err == os.EOF { dec.state.err = io.ErrUnexpectedEOF } - break; + break } // Receive a type id. - id := typeId(decodeInt(dec.state)); + id := typeId(decodeInt(dec.state)) if dec.state.err != nil { break } // Is it a new type? - if id < 0 { // 0 is the error state, handled above + if id < 0 { // 0 is the error state, handled above // If the id is negative, we have a type. - dec.recvType(-id); + dec.recvType(-id) if dec.state.err != nil { break } - continue; + continue } // No, it's a value. // Make sure the type has been defined already. - _, ok := dec.wireType[id]; + _, ok := dec.wireType[id] if !ok { - dec.state.err = errBadType; - break; + dec.state.err = errBadType + break } - dec.state.err = dec.decode(id, e); - break; + dec.state.err = dec.decode(id, e) + break } - return dec.state.err; + return dec.state.err } diff --git a/src/pkg/gob/encode.go b/src/pkg/gob/encode.go index 36845b87c..fb9710928 100644 --- a/src/pkg/gob/encode.go +++ b/src/pkg/gob/encode.go @@ -5,12 +5,12 @@ package gob import ( - "bytes"; - "io"; - "math"; - "os"; - "reflect"; - "unsafe"; + "bytes" + "io" + "math" + "os" + "reflect" + "unsafe" ) const uint64Size = unsafe.Sizeof(uint64(0)) @@ -20,10 +20,10 @@ const uint64Size = unsafe.Sizeof(uint64(0)) // number is initialized to -1 so 0 comes out as delta(1). A delta of // 0 terminates the structure. type encoderState struct { - b *bytes.Buffer; - err os.Error; // error encountered during encoding; - fieldnum int; // the last field number written. - buf [1 + uint64Size]byte; // buffer used by the encoder; here to avoid allocation. + b *bytes.Buffer + err os.Error // error encountered during encoding; + fieldnum int // the last field number written. + buf [1 + uint64Size]byte // buffer used by the encoder; here to avoid allocation. } // Unsigned integers have a two-state encoding. If the number is less @@ -38,49 +38,49 @@ func encodeUint(state *encoderState, x uint64) { return } if x <= 0x7F { - state.err = state.b.WriteByte(uint8(x)); - return; + state.err = state.b.WriteByte(uint8(x)) + return } - var n, m int; - m = uint64Size; + var n, m int + m = uint64Size for n = 1; x > 0; n++ { - state.buf[m] = uint8(x & 0xFF); - x >>= 8; - m--; + state.buf[m] = uint8(x & 0xFF) + x >>= 8 + m-- } - state.buf[m] = uint8(-(n - 1)); - n, state.err = state.b.Write(state.buf[m : uint64Size+1]); + state.buf[m] = uint8(-(n - 1)) + n, state.err = state.b.Write(state.buf[m : uint64Size+1]) } // encodeInt writes an encoded signed integer to state.w. // The low bit of the encoding says whether to bit complement the (other bits of the) uint to recover the int. // Sets state.err. If state.err is already non-nil, it does nothing. func encodeInt(state *encoderState, i int64) { - var x uint64; + var x uint64 if i < 0 { x = uint64(^i<<1) | 1 } else { x = uint64(i << 1) } - encodeUint(state, uint64(x)); + encodeUint(state, uint64(x)) } type encOp func(i *encInstr, state *encoderState, p unsafe.Pointer) // The 'instructions' of the encoding machine type encInstr struct { - op encOp; - field int; // field number - indir int; // how many pointer indirections to reach the value in the struct - offset uintptr; // offset in the structure of the field to encode + op encOp + field int // field number + indir int // how many pointer indirections to reach the value in the struct + offset uintptr // offset in the structure of the field to encode } // Emit a field number and update the state to record its value for delta encoding. // If the instruction pointer is nil, do nothing func (state *encoderState) update(instr *encInstr) { if instr != nil { - encodeUint(state, uint64(instr.field-state.fieldnum)); - state.fieldnum = instr.field; + encodeUint(state, uint64(instr.field-state.fieldnum)) + state.fieldnum = instr.field } } @@ -92,107 +92,107 @@ func (state *encoderState) update(instr *encInstr) { func encIndirect(p unsafe.Pointer, indir int) unsafe.Pointer { for ; indir > 0; indir-- { - p = *(*unsafe.Pointer)(p); + p = *(*unsafe.Pointer)(p) if p == nil { return unsafe.Pointer(nil) } } - return p; + return p } func encBool(i *encInstr, state *encoderState, p unsafe.Pointer) { - b := *(*bool)(p); + b := *(*bool)(p) if b { - state.update(i); - encodeUint(state, 1); + state.update(i) + encodeUint(state, 1) } } func encInt(i *encInstr, state *encoderState, p unsafe.Pointer) { - v := int64(*(*int)(p)); + v := int64(*(*int)(p)) if v != 0 { - state.update(i); - encodeInt(state, v); + state.update(i) + encodeInt(state, v) } } func encUint(i *encInstr, state *encoderState, p unsafe.Pointer) { - v := uint64(*(*uint)(p)); + v := uint64(*(*uint)(p)) if v != 0 { - state.update(i); - encodeUint(state, v); + state.update(i) + encodeUint(state, v) } } func encInt8(i *encInstr, state *encoderState, p unsafe.Pointer) { - v := int64(*(*int8)(p)); + v := int64(*(*int8)(p)) if v != 0 { - state.update(i); - encodeInt(state, v); + state.update(i) + encodeInt(state, v) } } func encUint8(i *encInstr, state *encoderState, p unsafe.Pointer) { - v := uint64(*(*uint8)(p)); + v := uint64(*(*uint8)(p)) if v != 0 { - state.update(i); - encodeUint(state, v); + state.update(i) + encodeUint(state, v) } } func encInt16(i *encInstr, state *encoderState, p unsafe.Pointer) { - v := int64(*(*int16)(p)); + v := int64(*(*int16)(p)) if v != 0 { - state.update(i); - encodeInt(state, v); + state.update(i) + encodeInt(state, v) } } func encUint16(i *encInstr, state *encoderState, p unsafe.Pointer) { - v := uint64(*(*uint16)(p)); + v := uint64(*(*uint16)(p)) if v != 0 { - state.update(i); - encodeUint(state, v); + state.update(i) + encodeUint(state, v) } } func encInt32(i *encInstr, state *encoderState, p unsafe.Pointer) { - v := int64(*(*int32)(p)); + v := int64(*(*int32)(p)) if v != 0 { - state.update(i); - encodeInt(state, v); + state.update(i) + encodeInt(state, v) } } func encUint32(i *encInstr, state *encoderState, p unsafe.Pointer) { - v := uint64(*(*uint32)(p)); + v := uint64(*(*uint32)(p)) if v != 0 { - state.update(i); - encodeUint(state, v); + state.update(i) + encodeUint(state, v) } } func encInt64(i *encInstr, state *encoderState, p unsafe.Pointer) { - v := *(*int64)(p); + v := *(*int64)(p) if v != 0 { - state.update(i); - encodeInt(state, v); + state.update(i) + encodeInt(state, v) } } func encUint64(i *encInstr, state *encoderState, p unsafe.Pointer) { - v := *(*uint64)(p); + v := *(*uint64)(p) if v != 0 { - state.update(i); - encodeUint(state, v); + state.update(i) + encodeUint(state, v) } } func encUintptr(i *encInstr, state *encoderState, p unsafe.Pointer) { - v := uint64(*(*uintptr)(p)); + v := uint64(*(*uintptr)(p)) if v != 0 { - state.update(i); - encodeUint(state, v); + state.update(i) + encodeUint(state, v) } } @@ -202,60 +202,60 @@ func encUintptr(i *encInstr, state *encoderState, p unsafe.Pointer) { // (for example) transmit more compactly. This routine does the // swizzling. func floatBits(f float64) uint64 { - u := math.Float64bits(f); - var v uint64; + u := math.Float64bits(f) + var v uint64 for i := 0; i < 8; i++ { - v <<= 8; - v |= u & 0xFF; - u >>= 8; + v <<= 8 + v |= u & 0xFF + u >>= 8 } - return v; + return v } func encFloat(i *encInstr, state *encoderState, p unsafe.Pointer) { - f := float(*(*float)(p)); + f := float(*(*float)(p)) if f != 0 { - v := floatBits(float64(f)); - state.update(i); - encodeUint(state, v); + v := floatBits(float64(f)) + state.update(i) + encodeUint(state, v) } } func encFloat32(i *encInstr, state *encoderState, p unsafe.Pointer) { - f := float32(*(*float32)(p)); + f := float32(*(*float32)(p)) if f != 0 { - v := floatBits(float64(f)); - state.update(i); - encodeUint(state, v); + v := floatBits(float64(f)) + state.update(i) + encodeUint(state, v) } } func encFloat64(i *encInstr, state *encoderState, p unsafe.Pointer) { - f := *(*float64)(p); + f := *(*float64)(p) if f != 0 { - state.update(i); - v := floatBits(f); - encodeUint(state, v); + state.update(i) + v := floatBits(f) + encodeUint(state, v) } } // Byte arrays are encoded as an unsigned count followed by the raw bytes. func encUint8Array(i *encInstr, state *encoderState, p unsafe.Pointer) { - b := *(*[]byte)(p); + b := *(*[]byte)(p) if len(b) > 0 { - state.update(i); - encodeUint(state, uint64(len(b))); - state.b.Write(b); + state.update(i) + encodeUint(state, uint64(len(b))) + state.b.Write(b) } } // Strings are encoded as an unsigned count followed by the raw bytes. func encString(i *encInstr, state *encoderState, p unsafe.Pointer) { - s := *(*string)(p); + s := *(*string)(p) if len(s) > 0 { - state.update(i); - encodeUint(state, uint64(len(s))); - io.WriteString(state.b, s); + state.update(i) + encodeUint(state, uint64(len(s))) + io.WriteString(state.b, s) } } @@ -269,48 +269,48 @@ func encStructTerminator(i *encInstr, state *encoderState, p unsafe.Pointer) { // The encoder engine is an array of instructions indexed by field number of the encoding // data, typically a struct. It is executed top to bottom, walking the struct. type encEngine struct { - instr []encInstr; + instr []encInstr } func encodeStruct(engine *encEngine, b *bytes.Buffer, basep uintptr) os.Error { - state := new(encoderState); - state.b = b; - state.fieldnum = -1; + state := new(encoderState) + state.b = b + state.fieldnum = -1 for i := 0; i < len(engine.instr); i++ { - instr := &engine.instr[i]; - p := unsafe.Pointer(basep + instr.offset); + instr := &engine.instr[i] + p := unsafe.Pointer(basep + instr.offset) if instr.indir > 0 { if p = encIndirect(p, instr.indir); p == nil { continue } } - instr.op(instr, state, p); + instr.op(instr, state, p) if state.err != nil { break } } - return state.err; + return state.err } func encodeArray(b *bytes.Buffer, p uintptr, op encOp, elemWid uintptr, length int, elemIndir int) os.Error { - state := new(encoderState); - state.b = b; - state.fieldnum = -1; - encodeUint(state, uint64(length)); + state := new(encoderState) + state.b = b + state.fieldnum = -1 + encodeUint(state, uint64(length)) for i := 0; i < length && state.err == nil; i++ { - elemp := p; - up := unsafe.Pointer(elemp); + elemp := p + up := unsafe.Pointer(elemp) if elemIndir > 0 { if up = encIndirect(up, elemIndir); up == nil { - state.err = os.ErrorString("gob: encodeArray: nil element"); - break; + state.err = os.ErrorString("gob: encodeArray: nil element") + break } - elemp = uintptr(up); + elemp = uintptr(up) } - op(nil, state, unsafe.Pointer(elemp)); - p += uintptr(elemWid); + op(nil, state, unsafe.Pointer(elemp)) + p += uintptr(elemWid) } - return state.err; + return state.err } var encOpMap = map[reflect.Type]encOp{ @@ -335,110 +335,110 @@ var encOpMap = map[reflect.Type]encOp{ // Return the encoding op for the base type under rt and // the indirection count to reach it. func encOpFor(rt reflect.Type) (encOp, int, os.Error) { - typ, indir := indirect(rt); - op, ok := encOpMap[reflect.Typeof(typ)]; + typ, indir := indirect(rt) + op, ok := encOpMap[reflect.Typeof(typ)] if !ok { - typ, _ := indirect(rt); + typ, _ := indirect(rt) // Special cases switch t := typ.(type) { case *reflect.SliceType: if _, ok := t.Elem().(*reflect.Uint8Type); ok { - op = encUint8Array; - break; + op = encUint8Array + break } // Slices have a header; we decode it to find the underlying array. - elemOp, indir, err := encOpFor(t.Elem()); + elemOp, indir, err := encOpFor(t.Elem()) if err != nil { return nil, 0, err } op = func(i *encInstr, state *encoderState, p unsafe.Pointer) { - slice := (*reflect.SliceHeader)(p); + slice := (*reflect.SliceHeader)(p) if slice.Len == 0 { return } - state.update(i); - state.err = encodeArray(state.b, slice.Data, elemOp, t.Elem().Size(), int(slice.Len), indir); - }; + state.update(i) + state.err = encodeArray(state.b, slice.Data, elemOp, t.Elem().Size(), int(slice.Len), indir) + } case *reflect.ArrayType: // True arrays have size in the type. - elemOp, indir, err := encOpFor(t.Elem()); + elemOp, indir, err := encOpFor(t.Elem()) if err != nil { return nil, 0, err } op = func(i *encInstr, state *encoderState, p unsafe.Pointer) { - state.update(i); - state.err = encodeArray(state.b, uintptr(p), elemOp, t.Elem().Size(), t.Len(), indir); - }; + state.update(i) + state.err = encodeArray(state.b, uintptr(p), elemOp, t.Elem().Size(), t.Len(), indir) + } case *reflect.StructType: // Generate a closure that calls out to the engine for the nested type. - _, err := getEncEngine(typ); + _, err := getEncEngine(typ) if err != nil { return nil, 0, err } - info := mustGetTypeInfo(typ); + info := mustGetTypeInfo(typ) op = func(i *encInstr, state *encoderState, p unsafe.Pointer) { - state.update(i); + state.update(i) // indirect through info to delay evaluation for recursive structs - state.err = encodeStruct(info.encoder, state.b, uintptr(p)); - }; + state.err = encodeStruct(info.encoder, state.b, uintptr(p)) + } } } if op == nil { return op, indir, os.ErrorString("gob enc: can't happen: encode type" + rt.String()) } - return op, indir, nil; + return op, indir, nil } // The local Type was compiled from the actual value, so we know it's compatible. func compileEnc(rt reflect.Type) (*encEngine, os.Error) { - srt, ok := rt.(*reflect.StructType); + srt, ok := rt.(*reflect.StructType) if !ok { panicln("can't happen: non-struct") } - engine := new(encEngine); - engine.instr = make([]encInstr, srt.NumField()+1); // +1 for terminator + engine := new(encEngine) + engine.instr = make([]encInstr, srt.NumField()+1) // +1 for terminator for fieldnum := 0; fieldnum < srt.NumField(); fieldnum++ { - f := srt.Field(fieldnum); - op, indir, err := encOpFor(f.Type); + f := srt.Field(fieldnum) + op, indir, err := encOpFor(f.Type) if err != nil { return nil, err } - engine.instr[fieldnum] = encInstr{op, fieldnum, indir, uintptr(f.Offset)}; + engine.instr[fieldnum] = encInstr{op, fieldnum, indir, uintptr(f.Offset)} } - engine.instr[srt.NumField()] = encInstr{encStructTerminator, 0, 0, 0}; - return engine, nil; + engine.instr[srt.NumField()] = encInstr{encStructTerminator, 0, 0, 0} + return engine, nil } // typeLock must be held (or we're in initialization and guaranteed single-threaded). // The reflection type must have all its indirections processed out. func getEncEngine(rt reflect.Type) (*encEngine, os.Error) { - info, err := getTypeInfo(rt); + info, err := getTypeInfo(rt) if err != nil { return nil, err } if info.encoder == nil { // mark this engine as underway before compiling to handle recursive types. - info.encoder = new(encEngine); - info.encoder, err = compileEnc(rt); + info.encoder = new(encEngine) + info.encoder, err = compileEnc(rt) } - return info.encoder, err; + return info.encoder, err } func encode(b *bytes.Buffer, e interface{}) os.Error { // Dereference down to the underlying object. - rt, indir := indirect(reflect.Typeof(e)); - v := reflect.NewValue(e); + rt, indir := indirect(reflect.Typeof(e)) + v := reflect.NewValue(e) for i := 0; i < indir; i++ { v = reflect.Indirect(v) } if _, ok := v.(*reflect.StructValue); !ok { return os.ErrorString("gob: encode can't handle " + v.Type().String()) } - typeLock.Lock(); - engine, err := getEncEngine(rt); - typeLock.Unlock(); + typeLock.Lock() + engine, err := getEncEngine(rt) + typeLock.Unlock() if err != nil { return err } - return encodeStruct(engine, b, v.Addr()); + return encodeStruct(engine, b, v.Addr()) } diff --git a/src/pkg/gob/encoder.go b/src/pkg/gob/encoder.go index 3be455210..cf380cd56 100644 --- a/src/pkg/gob/encoder.go +++ b/src/pkg/gob/encoder.go @@ -182,34 +182,34 @@ package gob import ( - "bytes"; - "io"; - "os"; - "reflect"; - "sync"; + "bytes" + "io" + "os" + "reflect" + "sync" ) // An Encoder manages the transmission of type and data information to the // other side of a connection. type Encoder struct { - mutex sync.Mutex; // each item must be sent atomically - w io.Writer; // where to send the data - sent map[reflect.Type]typeId; // which types we've already sent - state *encoderState; // so we can encode integers, strings directly - countState *encoderState; // stage for writing counts - buf []byte; // for collecting the output. + mutex sync.Mutex // each item must be sent atomically + w io.Writer // where to send the data + sent map[reflect.Type]typeId // which types we've already sent + state *encoderState // so we can encode integers, strings directly + countState *encoderState // stage for writing counts + buf []byte // for collecting the output. } // NewEncoder returns a new encoder that will transmit on the io.Writer. func NewEncoder(w io.Writer) *Encoder { - enc := new(Encoder); - enc.w = w; - enc.sent = make(map[reflect.Type]typeId); - enc.state = new(encoderState); - enc.state.b = new(bytes.Buffer); // the rest isn't important; all we need is buffer and writer - enc.countState = new(encoderState); - enc.countState.b = new(bytes.Buffer); // the rest isn't important; all we need is buffer and writer - return enc; + enc := new(Encoder) + enc.w = w + enc.sent = make(map[reflect.Type]typeId) + enc.state = new(encoderState) + enc.state.b = new(bytes.Buffer) // the rest isn't important; all we need is buffer and writer + enc.countState = new(encoderState) + enc.countState.b = new(bytes.Buffer) // the rest isn't important; all we need is buffer and writer + return enc } func (enc *Encoder) badType(rt reflect.Type) { @@ -217,29 +217,29 @@ func (enc *Encoder) badType(rt reflect.Type) { } func (enc *Encoder) setError(err os.Error) { - if enc.state.err == nil { // remember the first. + if enc.state.err == nil { // remember the first. enc.state.err = err } - enc.state.b.Reset(); + enc.state.b.Reset() } // Send the data item preceded by a unsigned count of its length. func (enc *Encoder) send() { // Encode the length. - encodeUint(enc.countState, uint64(enc.state.b.Len())); + encodeUint(enc.countState, uint64(enc.state.b.Len())) // Build the buffer. - countLen := enc.countState.b.Len(); - total := countLen + enc.state.b.Len(); + countLen := enc.countState.b.Len() + total := countLen + enc.state.b.Len() if total > len(enc.buf) { - enc.buf = make([]byte, total+1000) // extra for growth + enc.buf = make([]byte, total+1000) // extra for growth } // Place the length before the data. // TODO(r): avoid the extra copy here. - enc.countState.b.Read(enc.buf[0:countLen]); + enc.countState.b.Read(enc.buf[0:countLen]) // Now the data. - enc.state.b.Read(enc.buf[countLen:total]); + enc.state.b.Read(enc.buf[countLen:total]) // Write the data. - _, err := enc.w.Write(enc.buf[0:total]); + _, err := enc.w.Write(enc.buf[0:total]) if err != nil { enc.setError(err) } @@ -247,7 +247,7 @@ func (enc *Encoder) send() { func (enc *Encoder) sendType(origt reflect.Type) { // Drill down to the base type. - rt, _ := indirect(origt); + rt, _ := indirect(origt) // We only send structs - everything else is basic or an error switch rt := rt.(type) { @@ -260,14 +260,14 @@ func (enc *Encoder) sendType(origt reflect.Type) { return } // Otherwise we do send. - break; + break // Struct types are not sent, only their element types. case *reflect.StructType: break case *reflect.ChanType, *reflect.FuncType, *reflect.MapType, *reflect.InterfaceType: // Probably a bad field in a struct. - enc.badType(rt); - return; + enc.badType(rt) + return } // Have we already sent this type? This time we ask about the base type. @@ -276,27 +276,27 @@ func (enc *Encoder) sendType(origt reflect.Type) { } // Need to send it. - typeLock.Lock(); - info, err := getTypeInfo(rt); - typeLock.Unlock(); + typeLock.Lock() + info, err := getTypeInfo(rt) + typeLock.Unlock() if err != nil { - enc.setError(err); - return; + enc.setError(err) + return } // Send the pair (-id, type) // Id: - encodeInt(enc.state, -int64(info.id)); + encodeInt(enc.state, -int64(info.id)) // Type: - encode(enc.state.b, info.wire); - enc.send(); + encode(enc.state.b, info.wire) + enc.send() if enc.state.err != nil { return } // Remember we've sent this type. - enc.sent[rt] = info.id; + enc.sent[rt] = info.id // Remember we've sent the top-level, possibly indirect type too. - enc.sent[origt] = info.id; + enc.sent[origt] = info.id // Now send the inner types switch st := rt.(type) { case *reflect.StructType: @@ -306,7 +306,7 @@ func (enc *Encoder) sendType(origt reflect.Type) { case reflect.ArrayOrSliceType: enc.sendType(st.Elem()) } - return; + return } // Encode transmits the data item represented by the empty interface value, @@ -314,40 +314,40 @@ func (enc *Encoder) sendType(origt reflect.Type) { func (enc *Encoder) Encode(e interface{}) os.Error { // Make sure we're single-threaded through here, so multiple // goroutines can share an encoder. - enc.mutex.Lock(); - defer enc.mutex.Unlock(); + enc.mutex.Lock() + defer enc.mutex.Unlock() - enc.state.err = nil; - rt, _ := indirect(reflect.Typeof(e)); + enc.state.err = nil + rt, _ := indirect(reflect.Typeof(e)) // Must be a struct if _, ok := rt.(*reflect.StructType); !ok { - enc.badType(rt); - return enc.state.err; + enc.badType(rt) + return enc.state.err } // Sanity check only: encoder should never come in with data present. if enc.state.b.Len() > 0 || enc.countState.b.Len() > 0 { - enc.state.err = os.ErrorString("encoder: buffer not empty"); - return enc.state.err; + enc.state.err = os.ErrorString("encoder: buffer not empty") + return enc.state.err } // Make sure the type is known to the other side. // First, have we already sent this type? if _, alreadySent := enc.sent[rt]; !alreadySent { // No, so send it. - enc.sendType(rt); + enc.sendType(rt) if enc.state.err != nil { - enc.countState.b.Reset(); - return enc.state.err; + enc.countState.b.Reset() + return enc.state.err } } // Identify the type of this top-level value. - encodeInt(enc.state, int64(enc.sent[rt])); + encodeInt(enc.state, int64(enc.sent[rt])) // Encode the object. - encode(enc.state.b, e); - enc.send(); + encode(enc.state.b, e) + enc.send() - return enc.state.err; + return enc.state.err } diff --git a/src/pkg/gob/encoder_test.go b/src/pkg/gob/encoder_test.go index 3445d0e53..1308b85d4 100644 --- a/src/pkg/gob/encoder_test.go +++ b/src/pkg/gob/encoder_test.go @@ -5,51 +5,51 @@ package gob import ( - "bytes"; - "io"; - "os"; - "reflect"; - "strings"; - "testing"; + "bytes" + "io" + "os" + "reflect" + "strings" + "testing" ) type ET2 struct { - x string; + x string } type ET1 struct { - a int; - et2 *ET2; - next *ET1; + a int + et2 *ET2 + next *ET1 } // Like ET1 but with a different name for a field type ET3 struct { - a int; - et2 *ET2; - differentNext *ET1; + a int + et2 *ET2 + differentNext *ET1 } // Like ET1 but with a different type for a field type ET4 struct { - a int; - et2 float; - next int; + a int + et2 float + next int } func TestEncoderDecoder(t *testing.T) { - b := new(bytes.Buffer); - enc := NewEncoder(b); - et1 := new(ET1); - et1.a = 7; - et1.et2 = new(ET2); - enc.Encode(et1); + b := new(bytes.Buffer) + enc := NewEncoder(b) + et1 := new(ET1) + et1.a = 7 + et1.et2 = new(ET2) + enc.Encode(et1) if enc.state.err != nil { t.Error("encoder fail:", enc.state.err) } - dec := NewDecoder(b); - newEt1 := new(ET1); - dec.Decode(newEt1); + dec := NewDecoder(b) + newEt1 := new(ET1) + dec.Decode(newEt1) if dec.state.err != nil { t.Fatal("error decoding ET1:", dec.state.err) } @@ -61,9 +61,9 @@ func TestEncoderDecoder(t *testing.T) { t.Error("not at eof;", b.Len(), "bytes left") } - enc.Encode(et1); - newEt1 = new(ET1); - dec.Decode(newEt1); + enc.Encode(et1) + newEt1 = new(ET1) + dec.Decode(newEt1) if dec.state.err != nil { t.Fatal("round 2: error decoding ET1:", dec.state.err) } @@ -75,12 +75,12 @@ func TestEncoderDecoder(t *testing.T) { } // Now test with a running encoder/decoder pair that we recognize a type mismatch. - enc.Encode(et1); + enc.Encode(et1) if enc.state.err != nil { t.Error("round 3: encoder fail:", enc.state.err) } - newEt2 := new(ET2); - dec.Decode(newEt2); + newEt2 := new(ET2) + dec.Decode(newEt2) if dec.state.err == nil { t.Fatal("round 3: expected `bad type' error decoding ET2") } @@ -89,17 +89,17 @@ func TestEncoderDecoder(t *testing.T) { // Run one value through the encoder/decoder, but use the wrong type. // Input is always an ET1; we compare it to whatever is under 'e'. func badTypeCheck(e interface{}, shouldFail bool, msg string, t *testing.T) { - b := new(bytes.Buffer); - enc := NewEncoder(b); - et1 := new(ET1); - et1.a = 7; - et1.et2 = new(ET2); - enc.Encode(et1); + b := new(bytes.Buffer) + enc := NewEncoder(b) + et1 := new(ET1) + et1.a = 7 + et1.et2 = new(ET2) + enc.Encode(et1) if enc.state.err != nil { t.Error("encoder fail:", enc.state.err) } - dec := NewDecoder(b); - dec.Decode(e); + dec := NewDecoder(b) + dec.Decode(e) if shouldFail && (dec.state.err == nil) { t.Error("expected error for", msg) } @@ -110,15 +110,15 @@ func badTypeCheck(e interface{}, shouldFail bool, msg string, t *testing.T) { // Test that we recognize a bad type the first time. func TestWrongTypeDecoder(t *testing.T) { - badTypeCheck(new(ET2), true, "no fields in common", t); - badTypeCheck(new(ET3), false, "different name of field", t); - badTypeCheck(new(ET4), true, "different type of field", t); + badTypeCheck(new(ET2), true, "no fields in common", t) + badTypeCheck(new(ET3), false, "different name of field", t) + badTypeCheck(new(ET4), true, "different type of field", t) } func corruptDataCheck(s string, err os.Error, t *testing.T) { - b := bytes.NewBufferString(s); - dec := NewDecoder(b); - dec.Decode(new(ET2)); + b := bytes.NewBufferString(s) + dec := NewDecoder(b) + dec.Decode(new(ET2)) if dec.state.err != err { t.Error("expected error", err, "got", dec.state.err) } @@ -126,9 +126,9 @@ func corruptDataCheck(s string, err os.Error, t *testing.T) { // Check that we survive bad data. func TestBadData(t *testing.T) { - corruptDataCheck("", os.EOF, t); - corruptDataCheck("\x7Fhi", io.ErrUnexpectedEOF, t); - corruptDataCheck("\x03now is the time for all good men", errBadType, t); + corruptDataCheck("", os.EOF, t) + corruptDataCheck("\x7Fhi", io.ErrUnexpectedEOF, t) + corruptDataCheck("\x03now is the time for all good men", errBadType, t) } // Types not supported by the Encoder (only structs work at the top level). @@ -146,10 +146,10 @@ var unsupportedValues = []interface{}{ } func TestUnsupported(t *testing.T) { - var b bytes.Buffer; - enc := NewEncoder(&b); + var b bytes.Buffer + enc := NewEncoder(&b) for _, v := range unsupportedValues { - err := enc.Encode(v); + err := enc.Encode(v) if err == nil { t.Errorf("expected error for %T; got none", v) } @@ -157,27 +157,27 @@ func TestUnsupported(t *testing.T) { } func encAndDec(in, out interface{}) os.Error { - b := new(bytes.Buffer); - enc := NewEncoder(b); - enc.Encode(in); + b := new(bytes.Buffer) + enc := NewEncoder(b) + enc.Encode(in) if enc.state.err != nil { return enc.state.err } - dec := NewDecoder(b); - dec.Decode(out); + dec := NewDecoder(b) + dec.Decode(out) if dec.state.err != nil { return dec.state.err } - return nil; + return nil } func TestTypeToPtrType(t *testing.T) { // Encode a T, decode a *T type Type0 struct { - a int; + a int } - t0 := Type0{7}; - t0p := (*Type0)(nil); + t0 := Type0{7} + t0p := (*Type0)(nil) if err := encAndDec(t0, t0p); err != nil { t.Error(err) } @@ -186,10 +186,10 @@ func TestTypeToPtrType(t *testing.T) { func TestPtrTypeToType(t *testing.T) { // Encode a *T, decode a T type Type1 struct { - a uint; + a uint } - t1p := &Type1{17}; - var t1 Type1; + t1p := &Type1{17} + var t1 Type1 if err := encAndDec(t1, t1p); err != nil { t.Error(err) } @@ -197,15 +197,15 @@ func TestPtrTypeToType(t *testing.T) { func TestTypeToPtrPtrPtrPtrType(t *testing.T) { type Type2 struct { - a ****float; + a ****float } - t2 := Type2{}; - t2.a = new(***float); - *t2.a = new(**float); - **t2.a = new(*float); - ***t2.a = new(float); - ****t2.a = 27.4; - t2pppp := new(***Type2); + t2 := Type2{} + t2.a = new(***float) + *t2.a = new(**float) + **t2.a = new(*float) + ***t2.a = new(float) + ****t2.a = 27.4 + t2pppp := new(***Type2) if err := encAndDec(t2, t2pppp); err != nil { t.Error(err) } @@ -216,10 +216,10 @@ func TestTypeToPtrPtrPtrPtrType(t *testing.T) { func TestSlice(t *testing.T) { type Type3 struct { - a []string; + a []string } - t3p := &Type3{[]string{"hello", "world"}}; - var t3 Type3; + t3p := &Type3{[]string{"hello", "world"}} + var t3 Type3 if err := encAndDec(t3, t3p); err != nil { t.Error(err) } @@ -228,10 +228,10 @@ func TestSlice(t *testing.T) { func TestValueError(t *testing.T) { // Encode a *T, decode a T type Type4 struct { - a int; + a int } - t4p := &Type4{3}; - var t4 Type4; // note: not a pointer. + t4p := &Type4{3} + var t4 Type4 // note: not a pointer. if err := encAndDec(t4p, t4); err == nil || strings.Index(err.String(), "pointer") < 0 { t.Error("expected error about pointer; got", err) } @@ -239,17 +239,17 @@ func TestValueError(t *testing.T) { func TestArray(t *testing.T) { type Type5 struct { - a [3]string; + a [3]string } type Type6 struct { - a [2]string; // can't hold t5.a + a [2]string // can't hold t5.a } - t5 := Type5{[3]string{"hello", ",", "world"}}; - var t5p Type5; + t5 := Type5{[3]string{"hello", ",", "world"}} + var t5p Type5 if err := encAndDec(t5, &t5p); err != nil { t.Error(err) } - var t6 Type6; + var t6 Type6 if err := encAndDec(t5, &t6); err == nil { t.Error("should fail with mismatched array sizes") } diff --git a/src/pkg/gob/type.go b/src/pkg/gob/type.go index 08aaca5dc..58ed96b32 100644 --- a/src/pkg/gob/type.go +++ b/src/pkg/gob/type.go @@ -5,10 +5,10 @@ package gob import ( - "fmt"; - "os"; - "reflect"; - "sync"; + "fmt" + "os" + "reflect" + "sync" ) type kind reflect.Type @@ -25,67 +25,67 @@ type kind reflect.Type // int8, int16, int, uint, float, func, chan, struct, and so on. // That is, all struct types have the same kind, all func types have the same // kind, all int8 types have the same kind, and so on. -func typeKind(typ reflect.Type) kind { return kind(reflect.Typeof(typ)) } +func typeKind(typ reflect.Type) kind { return kind(reflect.Typeof(typ)) } // valueKind returns the kind of the value type // stored inside the interface v. -func valueKind(v interface{}) reflect.Type { return typeKind(reflect.Typeof(v)) } +func valueKind(v interface{}) reflect.Type { return typeKind(reflect.Typeof(v)) } // A typeId represents a gob Type as an integer that can be passed on the wire. // Internally, typeIds are used as keys to a map to recover the underlying type info. type typeId int32 -var nextId typeId // incremented for each new type we build -var typeLock sync.Mutex // set while building a type +var nextId typeId // incremented for each new type we build +var typeLock sync.Mutex // set while building a type type gobType interface { - id() typeId; - setId(id typeId); - Name() string; - string() string; // not public; only for debugging - safeString(seen map[typeId]bool) string; + id() typeId + setId(id typeId) + Name() string + string() string // not public; only for debugging + safeString(seen map[typeId]bool) string } var types = make(map[reflect.Type]gobType) var idToType = make(map[typeId]gobType) -var builtinIdToType map[typeId]gobType // set in init() after builtins are established +var builtinIdToType map[typeId]gobType // set in init() after builtins are established func setTypeId(typ gobType) { - nextId++; - typ.setId(nextId); - idToType[nextId] = typ; + nextId++ + typ.setId(nextId) + idToType[nextId] = typ } func (t typeId) gobType() gobType { if t == 0 { return nil } - return idToType[t]; + return idToType[t] } // string returns the string representation of the type associated with the typeId. -func (t typeId) string() string { return t.gobType().string() } +func (t typeId) string() string { return t.gobType().string() } // Name returns the name of the type associated with the typeId. -func (t typeId) Name() string { return t.gobType().Name() } +func (t typeId) Name() string { return t.gobType().Name() } // Common elements of all types. type commonType struct { - name string; - _id typeId; + name string + _id typeId } -func (t *commonType) id() typeId { return t._id } +func (t *commonType) id() typeId { return t._id } -func (t *commonType) setId(id typeId) { t._id = id } +func (t *commonType) setId(id typeId) { t._id = id } -func (t *commonType) string() string { return t.name } +func (t *commonType) string() string { return t.name } func (t *commonType) safeString(seen map[typeId]bool) string { return t.name } -func (t *commonType) Name() string { return t.name } +func (t *commonType) Name() string { return t.name } // Create and check predefined types // The string for tBytes is "bytes" not "[]byte" to signify its specialness. @@ -101,11 +101,11 @@ var tString = bootstrapType("string", "", 6) var tWireType = mustGetTypeInfo(reflect.Typeof(wireType{})).id func init() { - checkId(7, tWireType); - checkId(9, mustGetTypeInfo(reflect.Typeof(commonType{})).id); - checkId(11, mustGetTypeInfo(reflect.Typeof(structType{})).id); - checkId(12, mustGetTypeInfo(reflect.Typeof(fieldType{})).id); - builtinIdToType = make(map[typeId]gobType); + checkId(7, tWireType) + checkId(9, mustGetTypeInfo(reflect.Typeof(commonType{})).id) + checkId(11, mustGetTypeInfo(reflect.Typeof(structType{})).id) + checkId(12, mustGetTypeInfo(reflect.Typeof(fieldType{})).id) + builtinIdToType = make(map[typeId]gobType) for k, v := range idToType { builtinIdToType[k] = v } @@ -113,58 +113,58 @@ func init() { // Array type type arrayType struct { - commonType; - Elem typeId; - Len int; + commonType + Elem typeId + Len int } func newArrayType(name string, elem gobType, length int) *arrayType { - a := &arrayType{commonType{name: name}, elem.id(), length}; - setTypeId(a); - return a; + a := &arrayType{commonType{name: name}, elem.id(), length} + setTypeId(a) + return a } func (a *arrayType) safeString(seen map[typeId]bool) string { if _, ok := seen[a._id]; ok { return a.name } - seen[a._id] = true; - return fmt.Sprintf("[%d]%s", a.Len, a.Elem.gobType().safeString(seen)); + seen[a._id] = true + return fmt.Sprintf("[%d]%s", a.Len, a.Elem.gobType().safeString(seen)) } -func (a *arrayType) string() string { return a.safeString(make(map[typeId]bool)) } +func (a *arrayType) string() string { return a.safeString(make(map[typeId]bool)) } // Slice type type sliceType struct { - commonType; - Elem typeId; + commonType + Elem typeId } func newSliceType(name string, elem gobType) *sliceType { - s := &sliceType{commonType{name: name}, elem.id()}; - setTypeId(s); - return s; + s := &sliceType{commonType{name: name}, elem.id()} + setTypeId(s) + return s } func (s *sliceType) safeString(seen map[typeId]bool) string { if _, ok := seen[s._id]; ok { return s.name } - seen[s._id] = true; - return fmt.Sprintf("[]%s", s.Elem.gobType().safeString(seen)); + seen[s._id] = true + return fmt.Sprintf("[]%s", s.Elem.gobType().safeString(seen)) } -func (s *sliceType) string() string { return s.safeString(make(map[typeId]bool)) } +func (s *sliceType) string() string { return s.safeString(make(map[typeId]bool)) } // Struct type type fieldType struct { - name string; - id typeId; + name string + id typeId } type structType struct { - commonType; - field []*fieldType; + commonType + field []*fieldType } func (s *structType) safeString(seen map[typeId]bool) string { @@ -174,36 +174,36 @@ func (s *structType) safeString(seen map[typeId]bool) string { if _, ok := seen[s._id]; ok { return s.name } - seen[s._id] = true; - str := s.name + " = struct { "; + seen[s._id] = true + str := s.name + " = struct { " for _, f := range s.field { str += fmt.Sprintf("%s %s; ", f.name, f.id.gobType().safeString(seen)) } - str += "}"; - return str; + str += "}" + return str } -func (s *structType) string() string { return s.safeString(make(map[typeId]bool)) } +func (s *structType) string() string { return s.safeString(make(map[typeId]bool)) } func newStructType(name string) *structType { - s := &structType{commonType{name: name}, nil}; - setTypeId(s); - return s; + s := &structType{commonType{name: name}, nil} + setTypeId(s) + return s } // Step through the indirections on a type to discover the base type. // Return the number of indirections. func indirect(t reflect.Type) (rt reflect.Type, count int) { - rt = t; + rt = t for { - pt, ok := rt.(*reflect.PtrType); + pt, ok := rt.(*reflect.PtrType) if !ok { break } - rt = pt.Elem(); - count++; + rt = pt.Elem() + count++ } - return; + return } func newTypeObject(name string, rt reflect.Type) (gobType, os.Error) { @@ -247,50 +247,50 @@ func newTypeObject(name string, rt reflect.Type) (gobType, os.Error) { return tString.gobType(), nil case *reflect.ArrayType: - gt, err := getType("", t.Elem()); + gt, err := getType("", t.Elem()) if err != nil { return nil, err } - return newArrayType(name, gt, t.Len()), nil; + return newArrayType(name, gt, t.Len()), nil case *reflect.SliceType: // []byte == []uint8 is a special case if _, ok := t.Elem().(*reflect.Uint8Type); ok { return tBytes.gobType(), nil } - gt, err := getType(t.Elem().Name(), t.Elem()); + gt, err := getType(t.Elem().Name(), t.Elem()) if err != nil { return nil, err } - return newSliceType(name, gt), nil; + return newSliceType(name, gt), nil case *reflect.StructType: // Install the struct type itself before the fields so recursive // structures can be constructed safely. - strType := newStructType(name); - types[rt] = strType; - idToType[strType.id()] = strType; - field := make([]*fieldType, t.NumField()); + strType := newStructType(name) + types[rt] = strType + idToType[strType.id()] = strType + field := make([]*fieldType, t.NumField()) for i := 0; i < t.NumField(); i++ { - f := t.Field(i); - typ, _ := indirect(f.Type); - tname := typ.Name(); + f := t.Field(i) + typ, _ := indirect(f.Type) + tname := typ.Name() if tname == "" { tname = f.Type.String() } - gt, err := getType(tname, f.Type); + gt, err := getType(tname, f.Type) if err != nil { return nil, err } - field[i] = &fieldType{f.Name, gt.id()}; + field[i] = &fieldType{f.Name, gt.id()} } - strType.field = field; - return strType, nil; + strType.field = field + return strType, nil default: return nil, os.ErrorString("gob NewTypeObject can't handle type: " + rt.String()) } - return nil, nil; + return nil, nil } // getType returns the Gob type describing the given reflect.Type. @@ -298,21 +298,21 @@ func newTypeObject(name string, rt reflect.Type) (gobType, os.Error) { func getType(name string, rt reflect.Type) (gobType, os.Error) { // Flatten the data structure by collapsing out pointers for { - pt, ok := rt.(*reflect.PtrType); + pt, ok := rt.(*reflect.PtrType) if !ok { break } - rt = pt.Elem(); + rt = pt.Elem() } - typ, present := types[rt]; + typ, present := types[rt] if present { return typ, nil } - typ, err := newTypeObject(name, rt); + typ, err := newTypeObject(name, rt) if err == nil { types[rt] = typ } - return typ, err; + return typ, err } func checkId(want, got typeId) { @@ -323,16 +323,16 @@ func checkId(want, got typeId) { // used for building the basic types; called only from init() func bootstrapType(name string, e interface{}, expect typeId) typeId { - rt := reflect.Typeof(e); - _, present := types[rt]; + rt := reflect.Typeof(e) + _, present := types[rt] if present { panicln("bootstrap type already present:", name) } - typ := &commonType{name: name}; - types[rt] = typ; - setTypeId(typ); - checkId(expect, nextId); - return nextId; + typ := &commonType{name: name} + types[rt] = typ + setTypeId(typ) + checkId(expect, nextId) + return nextId } // Representation of the information we send and receive about this type. @@ -346,25 +346,25 @@ func bootstrapType(name string, e interface{}, expect typeId) typeId { // are built in encode.go's init() function. type wireType struct { - array *arrayType; - slice *sliceType; - strct *structType; + array *arrayType + slice *sliceType + strct *structType } func (w *wireType) name() string { if w.strct != nil { return w.strct.name } - return "unknown"; + return "unknown" } type typeInfo struct { - id typeId; - encoder *encEngine; - wire *wireType; + id typeId + encoder *encEngine + wire *wireType } -var typeInfoMap = make(map[reflect.Type]*typeInfo) // protected by typeLock +var typeInfoMap = make(map[reflect.Type]*typeInfo) // protected by typeLock // The reflection type must have all its indirections processed out. // typeLock must be held. @@ -372,16 +372,16 @@ func getTypeInfo(rt reflect.Type) (*typeInfo, os.Error) { if _, ok := rt.(*reflect.PtrType); ok { panicln("pointer type in getTypeInfo:", rt.String()) } - info, ok := typeInfoMap[rt]; + info, ok := typeInfoMap[rt] if !ok { - info = new(typeInfo); - name := rt.Name(); - gt, err := getType(name, rt); + info = new(typeInfo) + name := rt.Name() + gt, err := getType(name, rt) if err != nil { return nil, err } - info.id = gt.id(); - t := info.id.gobType(); + info.id = gt.id() + t := info.id.gobType() switch typ := rt.(type) { case *reflect.ArrayType: info.wire = &wireType{array: t.(*arrayType)} @@ -393,16 +393,16 @@ func getTypeInfo(rt reflect.Type) (*typeInfo, os.Error) { case *reflect.StructType: info.wire = &wireType{strct: t.(*structType)} } - typeInfoMap[rt] = info; + typeInfoMap[rt] = info } - return info, nil; + return info, nil } // Called only when a panic is acceptable and unexpected. func mustGetTypeInfo(rt reflect.Type) *typeInfo { - t, err := getTypeInfo(rt); + t, err := getTypeInfo(rt) if err != nil { panicln("getTypeInfo:", err.String()) } - return t; + return t } diff --git a/src/pkg/gob/type_test.go b/src/pkg/gob/type_test.go index f1f44bdc2..2c3d0442e 100644 --- a/src/pkg/gob/type_test.go +++ b/src/pkg/gob/type_test.go @@ -5,13 +5,13 @@ package gob import ( - "reflect"; - "testing"; + "reflect" + "testing" ) type typeT struct { - id typeId; - str string; + id typeId + str string } var basicTypes = []typeT{ @@ -24,13 +24,13 @@ var basicTypes = []typeT{ } func getTypeUnlocked(name string, rt reflect.Type) gobType { - typeLock.Lock(); - defer typeLock.Unlock(); - t, err := getType(name, rt); + typeLock.Lock() + defer typeLock.Unlock() + t, err := getType(name, rt) if err != nil { panicln("getTypeUnlocked:", err.String()) } - return t; + return t } // Sanity checks @@ -47,86 +47,86 @@ func TestBasic(t *testing.T) { // Reregister some basic types to check registration is idempotent. func TestReregistration(t *testing.T) { - newtyp := getTypeUnlocked("int", reflect.Typeof(int(0))); + newtyp := getTypeUnlocked("int", reflect.Typeof(int(0))) if newtyp != tInt.gobType() { t.Errorf("reregistration of %s got new type", newtyp.string()) } - newtyp = getTypeUnlocked("uint", reflect.Typeof(uint(0))); + newtyp = getTypeUnlocked("uint", reflect.Typeof(uint(0))) if newtyp != tUint.gobType() { t.Errorf("reregistration of %s got new type", newtyp.string()) } - newtyp = getTypeUnlocked("string", reflect.Typeof("hello")); + newtyp = getTypeUnlocked("string", reflect.Typeof("hello")) if newtyp != tString.gobType() { t.Errorf("reregistration of %s got new type", newtyp.string()) } } func TestArrayType(t *testing.T) { - var a3 [3]int; - a3int := getTypeUnlocked("foo", reflect.Typeof(a3)); - newa3int := getTypeUnlocked("bar", reflect.Typeof(a3)); + var a3 [3]int + a3int := getTypeUnlocked("foo", reflect.Typeof(a3)) + newa3int := getTypeUnlocked("bar", reflect.Typeof(a3)) if a3int != newa3int { t.Errorf("second registration of [3]int creates new type") } - var a4 [4]int; - a4int := getTypeUnlocked("goo", reflect.Typeof(a4)); + var a4 [4]int + a4int := getTypeUnlocked("goo", reflect.Typeof(a4)) if a3int == a4int { t.Errorf("registration of [3]int creates same type as [4]int") } - var b3 [3]bool; - a3bool := getTypeUnlocked("", reflect.Typeof(b3)); + var b3 [3]bool + a3bool := getTypeUnlocked("", reflect.Typeof(b3)) if a3int == a3bool { t.Errorf("registration of [3]bool creates same type as [3]int") } - str := a3bool.string(); - expected := "[3]bool"; + str := a3bool.string() + expected := "[3]bool" if str != expected { t.Errorf("array printed as %q; expected %q", str, expected) } } func TestSliceType(t *testing.T) { - var s []int; - sint := getTypeUnlocked("slice", reflect.Typeof(s)); - var news []int; - newsint := getTypeUnlocked("slice1", reflect.Typeof(news)); + var s []int + sint := getTypeUnlocked("slice", reflect.Typeof(s)) + var news []int + newsint := getTypeUnlocked("slice1", reflect.Typeof(news)) if sint != newsint { t.Errorf("second registration of []int creates new type") } - var b []bool; - sbool := getTypeUnlocked("", reflect.Typeof(b)); + var b []bool + sbool := getTypeUnlocked("", reflect.Typeof(b)) if sbool == sint { t.Errorf("registration of []bool creates same type as []int") } - str := sbool.string(); - expected := "[]bool"; + str := sbool.string() + expected := "[]bool" if str != expected { t.Errorf("slice printed as %q; expected %q", str, expected) } } type Bar struct { - x string; + x string } // This structure has pointers and refers to itself, making it a good test case. type Foo struct { - a int; - b int32; // will become int - c string; - d []byte; - e *float; // will become float - f ****float64; // will become float - g *Bar; - h *Bar; // should not interpolate the definition of Bar again - i *Foo; // will not explode + a int + b int32 // will become int + c string + d []byte + e *float // will become float + f ****float64 // will become float + g *Bar + h *Bar // should not interpolate the definition of Bar again + i *Foo // will not explode } func TestStructType(t *testing.T) { - sstruct := getTypeUnlocked("Foo", reflect.Typeof(Foo{})); - str := sstruct.string(); + sstruct := getTypeUnlocked("Foo", reflect.Typeof(Foo{})) + str := sstruct.string() // If we can print it correctly, we built it correctly. - expected := "Foo = struct { a int; b int; c string; d bytes; e float; f float; g Bar = struct { x string; }; h Bar; i Foo; }"; + expected := "Foo = struct { a int; b int; c string; d bytes; e float; f float; g Bar = struct { x string; }; h Bar; i Foo; }" if str != expected { t.Errorf("struct printed as %q; expected %q", str, expected) } diff --git a/src/pkg/hash/adler32/adler32.go b/src/pkg/hash/adler32/adler32.go index ec7c6dc30..cd0c2599a 100644 --- a/src/pkg/hash/adler32/adler32.go +++ b/src/pkg/hash/adler32/adler32.go @@ -12,12 +12,12 @@ package adler32 import ( - "hash"; - "os"; + "hash" + "os" ) const ( - mod = 65521; + mod = 65521 ) // The size of an Adler-32 checksum in bytes. @@ -27,62 +27,62 @@ const Size = 4 type digest struct { // invariant: (a < mod && b < mod) || a <= b // invariant: a + b + 255 <= 0xffffffff - a, b uint32; + a, b uint32 } -func (d *digest) Reset() { d.a, d.b = 1, 0 } +func (d *digest) Reset() { d.a, d.b = 1, 0 } // New returns a new hash.Hash32 computing the Adler-32 checksum. func New() hash.Hash32 { - d := new(digest); - d.Reset(); - return d; + d := new(digest) + d.Reset() + return d } -func (d *digest) Size() int { return Size } +func (d *digest) Size() int { return Size } // Add p to the running checksum a, b. func update(a, b uint32, p []byte) (aa, bb uint32) { for i := 0; i < len(p); i++ { - a += uint32(p[i]); - b += a; + a += uint32(p[i]) + b += a // invariant: a <= b if b > (0xffffffff-255)/2 { - a %= mod; - b %= mod; + a %= mod + b %= mod // invariant: a < mod && b < mod } else { // invariant: a + b + 255 <= 2 * b + 255 <= 0xffffffff } } - return a, b; + return a, b } // Return the 32-bit checksum corresponding to a, b. func finish(a, b uint32) uint32 { if b >= mod { - a %= mod; - b %= mod; + a %= mod + b %= mod } - return b<<16 | a; + return b<<16 | a } func (d *digest) Write(p []byte) (nn int, err os.Error) { - d.a, d.b = update(d.a, d.b, p); - return len(p), nil; + d.a, d.b = update(d.a, d.b, p) + return len(p), nil } -func (d *digest) Sum32() uint32 { return finish(d.a, d.b) } +func (d *digest) Sum32() uint32 { return finish(d.a, d.b) } func (d *digest) Sum() []byte { - p := make([]byte, 4); - s := d.Sum32(); - p[0] = byte(s >> 24); - p[1] = byte(s >> 16); - p[2] = byte(s >> 8); - p[3] = byte(s); - return p; + p := make([]byte, 4) + s := d.Sum32() + p[0] = byte(s >> 24) + p[1] = byte(s >> 16) + p[2] = byte(s >> 8) + p[3] = byte(s) + return p } // Checksum returns the Adler-32 checksum of data. -func Checksum(data []byte) uint32 { return finish(update(1, 0, data)) } +func Checksum(data []byte) uint32 { return finish(update(1, 0, data)) } diff --git a/src/pkg/hash/adler32/adler32_test.go b/src/pkg/hash/adler32/adler32_test.go index 0197270b2..cfe9c9547 100644 --- a/src/pkg/hash/adler32/adler32_test.go +++ b/src/pkg/hash/adler32/adler32_test.go @@ -5,13 +5,13 @@ package adler32 import ( - "io"; - "testing"; + "io" + "testing" ) type _Adler32Test struct { - out uint32; - in string; + out uint32 + in string } var golden = []_Adler32Test{ @@ -51,13 +51,13 @@ var golden = []_Adler32Test{ func TestGolden(t *testing.T) { for i := 0; i < len(golden); i++ { - g := golden[i]; - c := New(); - io.WriteString(c, g.in); - s := c.Sum32(); + g := golden[i] + c := New() + io.WriteString(c, g.in) + s := c.Sum32() if s != g.out { - t.Errorf("adler32(%s) = 0x%x want 0x%x", g.in, s, g.out); - t.FailNow(); + t.Errorf("adler32(%s) = 0x%x want 0x%x", g.in, s, g.out) + t.FailNow() } } } diff --git a/src/pkg/hash/crc32/crc32.go b/src/pkg/hash/crc32/crc32.go index 9330f9812..c8fd9f014 100644 --- a/src/pkg/hash/crc32/crc32.go +++ b/src/pkg/hash/crc32/crc32.go @@ -7,8 +7,8 @@ package crc32 import ( - "hash"; - "os"; + "hash" + "os" ) // The size of a CRC-32 checksum in bytes. @@ -18,17 +18,17 @@ const Size = 4 const ( // Far and away the most common CRC-32 polynomial. // Used by ethernet (IEEE 802.3), v.42, fddi, gzip, zip, png, mpeg-2, ... - IEEE = 0xedb88320; + IEEE = 0xedb88320 // Castagnoli's polynomial, used in iSCSI. // Has better error detection characteristics than IEEE. // http://dx.doi.org/10.1109/26.231911 - Castagnoli = 0x82f63b78; + Castagnoli = 0x82f63b78 // Koopman's polynomial. // Also has better error detection characteristics than IEEE. // http://dx.doi.org/10.1109/DSN.2002.1028931 - Koopman = 0xeb31d82e; + Koopman = 0xeb31d82e ) // Table is a 256-word table representing the polynomial for efficient processing. @@ -36,9 +36,9 @@ type Table [256]uint32 // MakeTable returns the Table constructed from the specified polynomial. func MakeTable(poly uint32) *Table { - t := new(Table); + t := new(Table) for i := 0; i < 256; i++ { - crc := uint32(i); + crc := uint32(i) for j := 0; j < 8; j++ { if crc&1 == 1 { crc = (crc >> 1) ^ poly @@ -46,9 +46,9 @@ func MakeTable(poly uint32) *Table { crc >>= 1 } } - t[i] = crc; + t[i] = crc } - return t; + return t } // IEEETable is the table for the IEEE polynomial. @@ -56,51 +56,51 @@ var IEEETable = MakeTable(IEEE) // digest represents the partial evaluation of a checksum. type digest struct { - crc uint32; - tab *Table; + crc uint32 + tab *Table } // New creates a new hash.Hash32 computing the CRC-32 checksum // using the polynomial represented by the Table. -func New(tab *Table) hash.Hash32 { return &digest{0, tab} } +func New(tab *Table) hash.Hash32 { return &digest{0, tab} } // NewIEEE creates a new hash.Hash32 computing the CRC-32 checksum // using the IEEE polynomial. -func NewIEEE() hash.Hash32 { return New(IEEETable) } +func NewIEEE() hash.Hash32 { return New(IEEETable) } -func (d *digest) Size() int { return Size } +func (d *digest) Size() int { return Size } -func (d *digest) Reset() { d.crc = 0 } +func (d *digest) Reset() { d.crc = 0 } func update(crc uint32, tab *Table, p []byte) uint32 { - crc = ^crc; + crc = ^crc for i := 0; i < len(p); i++ { crc = tab[byte(crc)^p[i]] ^ (crc >> 8) } - return ^crc; + return ^crc } func (d *digest) Write(p []byte) (n int, err os.Error) { - d.crc = update(d.crc, d.tab, p); - return len(p), nil; + d.crc = update(d.crc, d.tab, p) + return len(p), nil } -func (d *digest) Sum32() uint32 { return d.crc } +func (d *digest) Sum32() uint32 { return d.crc } func (d *digest) Sum() []byte { - p := make([]byte, 4); - s := d.Sum32(); - p[0] = byte(s >> 24); - p[1] = byte(s >> 16); - p[2] = byte(s >> 8); - p[3] = byte(s); - return p; + p := make([]byte, 4) + s := d.Sum32() + p[0] = byte(s >> 24) + p[1] = byte(s >> 16) + p[2] = byte(s >> 8) + p[3] = byte(s) + return p } // Checksum returns the CRC-32 checksum of data // using the polynomial represented by the Table. -func Checksum(data []byte, tab *Table) uint32 { return update(0, tab, data) } +func Checksum(data []byte, tab *Table) uint32 { return update(0, tab, data) } // ChecksumIEEE returns the CRC-32 checksum of data // using the IEEE polynomial. -func ChecksumIEEE(data []byte) uint32 { return update(0, IEEETable, data) } +func ChecksumIEEE(data []byte) uint32 { return update(0, IEEETable, data) } diff --git a/src/pkg/hash/crc32/crc32_test.go b/src/pkg/hash/crc32/crc32_test.go index f9e6053ed..ce81b7231 100644 --- a/src/pkg/hash/crc32/crc32_test.go +++ b/src/pkg/hash/crc32/crc32_test.go @@ -5,13 +5,13 @@ package crc32 import ( - "io"; - "testing"; + "io" + "testing" ) type _Crc32Test struct { - out uint32; - in string; + out uint32 + in string } var golden = []_Crc32Test{ @@ -50,25 +50,25 @@ var golden = []_Crc32Test{ func TestGolden(t *testing.T) { for i := 0; i < len(golden); i++ { - g := golden[i]; - c := NewIEEE(); - io.WriteString(c, g.in); - s := c.Sum32(); + g := golden[i] + c := NewIEEE() + io.WriteString(c, g.in) + s := c.Sum32() if s != g.out { - t.Errorf("crc32(%s) = 0x%x want 0x%x", g.in, s, g.out); - t.FailNow(); + t.Errorf("crc32(%s) = 0x%x want 0x%x", g.in, s, g.out) + t.FailNow() } } } func BenchmarkCrc32KB(b *testing.B) { - b.StopTimer(); - data := make([]uint8, 1024); + b.StopTimer() + data := make([]uint8, 1024) for i := 0; i < 1024; i++ { data[i] = uint8(i) } - c := NewIEEE(); - b.StartTimer(); + c := NewIEEE() + b.StartTimer() for i := 0; i < b.N; i++ { c.Write(data) diff --git a/src/pkg/hash/hash.go b/src/pkg/hash/hash.go index 62ec13ba8..470e9a36c 100644 --- a/src/pkg/hash/hash.go +++ b/src/pkg/hash/hash.go @@ -10,14 +10,14 @@ import "io" // The Write method never returns an error. // Sum returns the bytes of integer hash codes in big-endian order. type Hash interface { - io.Writer; - Sum() []byte; - Reset(); - Size() int; // number of bytes Sum returns + io.Writer + Sum() []byte + Reset() + Size() int // number of bytes Sum returns } // Hash32 is the common interface implemented by all 32-bit hash functions. type Hash32 interface { - Hash; - Sum32() uint32; + Hash + Sum32() uint32 } diff --git a/src/pkg/http/client.go b/src/pkg/http/client.go index 70fa49fcc..aa3d3be6d 100644 --- a/src/pkg/http/client.go +++ b/src/pkg/http/client.go @@ -7,19 +7,19 @@ package http import ( - "bufio"; - "fmt"; - "io"; - "net"; - "os"; - "strconv"; - "strings"; + "bufio" + "fmt" + "io" + "net" + "os" + "strconv" + "strings" ) // Response represents the response from an HTTP request. type Response struct { - Status string; // e.g. "200 OK" - StatusCode int; // e.g. 200 + Status string // e.g. "200 OK" + StatusCode int // e.g. 200 // Header maps header keys to values. If the response had multiple // headers with the same key, they will be concatenated, with comma @@ -27,10 +27,10 @@ type Response struct { // be semantically equivalent to a comma-delimited sequence.) // // Keys in the map are canonicalized (see CanonicalHeaderKey). - Header map[string]string; + Header map[string]string // Stream from which the response body can be read. - Body io.ReadCloser; + Body io.ReadCloser } // GetHeader returns the value of the response header with the given @@ -39,15 +39,15 @@ type Response struct { // response headers with the given key, it returns the empty string and // false. Keys are not case sensitive. func (r *Response) GetHeader(key string) (value string) { - value, _ = r.Header[CanonicalHeaderKey(key)]; - return; + value, _ = r.Header[CanonicalHeaderKey(key)] + return } // AddHeader adds a value under the given key. Keys are not case sensitive. func (r *Response) AddHeader(key, value string) { - key = CanonicalHeaderKey(key); + key = CanonicalHeaderKey(key) - oldValues, oldValuesPresent := r.Header[key]; + oldValues, oldValuesPresent := r.Header[key] if oldValuesPresent { r.Header[key] = oldValues + "," + value } else { @@ -57,50 +57,50 @@ func (r *Response) AddHeader(key, value string) { // Given a string of the form "host", "host:port", or "[ipv6::address]:port", // return true if the string includes a port. -func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") } +func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") } // Used in Send to implement io.ReadCloser by bundling together the // io.BufReader through which we read the response, and the underlying // network connection. type readClose struct { - io.Reader; - io.Closer; + io.Reader + io.Closer } // ReadResponse reads and returns an HTTP response from r. func ReadResponse(r *bufio.Reader) (*Response, os.Error) { - resp := new(Response); + resp := new(Response) // Parse the first line of the response. - resp.Header = make(map[string]string); + resp.Header = make(map[string]string) - line, err := readLine(r); + line, err := readLine(r) if err != nil { return nil, err } - f := strings.Split(line, " ", 3); + f := strings.Split(line, " ", 3) if len(f) < 3 { return nil, &badStringError{"malformed HTTP response", line} } - resp.Status = f[1] + " " + f[2]; - resp.StatusCode, err = strconv.Atoi(f[1]); + resp.Status = f[1] + " " + f[2] + resp.StatusCode, err = strconv.Atoi(f[1]) if err != nil { return nil, &badStringError{"malformed HTTP status code", f[1]} } // Parse the response headers. for { - key, value, err := readKeyValue(r); + key, value, err := readKeyValue(r) if err != nil { return nil, err } if key == "" { - break // end of response header + break // end of response header } - resp.AddHeader(key, value); + resp.AddHeader(key, value) } - return resp, nil; + return resp, nil } @@ -114,41 +114,41 @@ func send(req *Request) (resp *Response, err os.Error) { return nil, &badStringError{"unsupported protocol scheme", req.URL.Scheme} } - addr := req.URL.Host; + addr := req.URL.Host if !hasPort(addr) { addr += ":http" } - conn, err := net.Dial("tcp", "", addr); + conn, err := net.Dial("tcp", "", addr) if err != nil { return nil, err } - err = req.Write(conn); + err = req.Write(conn) if err != nil { - conn.Close(); - return nil, err; + conn.Close() + return nil, err } - reader := bufio.NewReader(conn); - resp, err = ReadResponse(reader); + reader := bufio.NewReader(conn) + resp, err = ReadResponse(reader) if err != nil { - conn.Close(); - return nil, err; + conn.Close() + return nil, err } - r := io.Reader(reader); + r := io.Reader(reader) if v := resp.GetHeader("Transfer-Encoding"); v == "chunked" { r = newChunkedReader(reader) } else if v := resp.GetHeader("Content-Length"); v != "" { - n, err := strconv.Atoi64(v); + n, err := strconv.Atoi64(v) if err != nil { return nil, &badStringError{"invalid Content-Length", v} } - r = io.LimitReader(r, n); + r = io.LimitReader(r, n) } - resp.Body = readClose{r, conn}; + resp.Body = readClose{r, conn} - return; + return } // True if the specified HTTP status code is one for which the Get utility should @@ -158,7 +158,7 @@ func shouldRedirect(statusCode int) bool { case StatusMovedPermanently, StatusFound, StatusSeeOther, StatusTemporaryRedirect: return true } - return false; + return false } // Get issues a GET to the specified URL. If the response is one of the following @@ -179,11 +179,11 @@ func Get(url string) (r *Response, finalURL string, err os.Error) { // TODO: set referrer header on redirects. for redirect := 0; ; redirect++ { if redirect >= 10 { - err = os.ErrorString("stopped after 10 redirects"); - break; + err = os.ErrorString("stopped after 10 redirects") + break } - var req Request; + var req Request if req.URL, err = ParseURL(url); err != nil { break } @@ -191,19 +191,19 @@ func Get(url string) (r *Response, finalURL string, err os.Error) { break } if shouldRedirect(r.StatusCode) { - r.Body.Close(); + r.Body.Close() if url = r.GetHeader("Location"); url == "" { - err = os.ErrorString(fmt.Sprintf("%d response missing Location header", r.StatusCode)); - break; + err = os.ErrorString(fmt.Sprintf("%d response missing Location header", r.StatusCode)) + break } - continue; + continue } - finalURL = url; - return; + finalURL = url + return } - err = &URLError{"Get", url, err}; - return; + err = &URLError{"Get", url, err} + return } @@ -211,18 +211,18 @@ func Get(url string) (r *Response, finalURL string, err os.Error) { // // Caller should close r.Body when done reading it. func Post(url string, bodyType string, body io.Reader) (r *Response, err os.Error) { - var req Request; - req.Method = "POST"; - req.Body = body; + var req Request + req.Method = "POST" + req.Body = body req.Header = map[string]string{ "Content-Type": bodyType, "Transfer-Encoding": "chunked", - }; + } - req.URL, err = ParseURL(url); + req.URL, err = ParseURL(url) if err != nil { return nil, err } - return send(&req); + return send(&req) } diff --git a/src/pkg/http/client_test.go b/src/pkg/http/client_test.go index 76aad7e81..6787825d8 100644 --- a/src/pkg/http/client_test.go +++ b/src/pkg/http/client_test.go @@ -7,20 +7,20 @@ package http import ( - "io/ioutil"; - "strings"; - "testing"; + "io/ioutil" + "strings" + "testing" ) func TestClient(t *testing.T) { // TODO: add a proper test suite. Current test merely verifies that // we can retrieve the Google robots.txt file. - r, _, err := Get("http://www.google.com/robots.txt"); - var b []byte; + r, _, err := Get("http://www.google.com/robots.txt") + var b []byte if err == nil { - b, err = ioutil.ReadAll(r.Body); - r.Body.Close(); + b, err = ioutil.ReadAll(r.Body) + r.Body.Close() } if err != nil { t.Error(err) diff --git a/src/pkg/http/fs.go b/src/pkg/http/fs.go index 507ce33a9..fff0b8d0e 100644 --- a/src/pkg/http/fs.go +++ b/src/pkg/http/fs.go @@ -7,12 +7,12 @@ package http import ( - "fmt"; - "io"; - "os"; - "path"; - "strings"; - "utf8"; + "fmt" + "io" + "os" + "path" + "strings" + "utf8" ) // TODO this should be in a mime package somewhere @@ -30,7 +30,7 @@ var contentByExt = map[string]string{ // contain any unprintable ASCII or Unicode characters. func isText(b []byte) bool { for len(b) > 0 && utf8.FullRune(b) { - rune, size := utf8.DecodeRune(b); + rune, size := utf8.DecodeRune(b) if size == 1 && rune == utf8.RuneError { // decoding error return false @@ -47,110 +47,110 @@ func isText(b []byte) bool { return false } } - b = b[size:]; + b = b[size:] } - return true; + return true } func dirList(c *Conn, f *os.File) { - fmt.Fprintf(c, "<pre>\n"); + fmt.Fprintf(c, "<pre>\n") for { - dirs, err := f.Readdir(100); + dirs, err := f.Readdir(100) if err != nil || len(dirs) == 0 { break } for _, d := range dirs { - name := d.Name; + name := d.Name if d.IsDirectory() { name += "/" } // TODO htmlescape - fmt.Fprintf(c, "<a href=\"%s\">%s</a>\n", name, name); + fmt.Fprintf(c, "<a href=\"%s\">%s</a>\n", name, name) } } - fmt.Fprintf(c, "</pre>\n"); + fmt.Fprintf(c, "</pre>\n") } func serveFileInternal(c *Conn, r *Request, name string, redirect bool) { - const indexPage = "/index.html"; + const indexPage = "/index.html" // redirect .../index.html to .../ if strings.HasSuffix(r.URL.Path, indexPage) { - Redirect(c, r.URL.Path[0:len(r.URL.Path)-len(indexPage)+1], StatusMovedPermanently); - return; + Redirect(c, r.URL.Path[0:len(r.URL.Path)-len(indexPage)+1], StatusMovedPermanently) + return } - f, err := os.Open(name, os.O_RDONLY, 0); + f, err := os.Open(name, os.O_RDONLY, 0) if err != nil { // TODO expose actual error? - NotFound(c, r); - return; + NotFound(c, r) + return } - defer f.Close(); + defer f.Close() - d, err1 := f.Stat(); + d, err1 := f.Stat() if err1 != nil { // TODO expose actual error? - NotFound(c, r); - return; + NotFound(c, r) + return } if redirect { // redirect to canonical path: / at end of directory url // r.URL.Path always begins with / - url := r.URL.Path; + url := r.URL.Path if d.IsDirectory() { if url[len(url)-1] != '/' { - Redirect(c, url+"/", StatusMovedPermanently); - return; + Redirect(c, url+"/", StatusMovedPermanently) + return } } else { if url[len(url)-1] == '/' { - Redirect(c, url[0:len(url)-1], StatusMovedPermanently); - return; + Redirect(c, url[0:len(url)-1], StatusMovedPermanently) + return } } } // use contents of index.html for directory, if present if d.IsDirectory() { - index := name + indexPage; - ff, err := os.Open(index, os.O_RDONLY, 0); + index := name + indexPage + ff, err := os.Open(index, os.O_RDONLY, 0) if err == nil { - defer ff.Close(); - dd, err := ff.Stat(); + defer ff.Close() + dd, err := ff.Stat() if err == nil { - name = index; - d = dd; - f = ff; + name = index + d = dd + f = ff } } } if d.IsDirectory() { - dirList(c, f); - return; + dirList(c, f) + return } // serve file // use extension to find content type. - ext := path.Ext(name); + ext := path.Ext(name) if ctype, ok := contentByExt[ext]; ok { c.SetHeader("Content-Type", ctype) } else { // read first chunk to decide between utf-8 text and binary - var buf [1024]byte; - n, _ := io.ReadFull(f, &buf); - b := buf[0:n]; + var buf [1024]byte + n, _ := io.ReadFull(f, &buf) + b := buf[0:n] if isText(b) { c.SetHeader("Content-Type", "text-plain; charset=utf-8") } else { - c.SetHeader("Content-Type", "application/octet-stream") // generic binary + c.SetHeader("Content-Type", "application/octet-stream") // generic binary } - c.Write(b); + c.Write(b) } - io.Copy(c, f); + io.Copy(c, f) } // ServeFile replies to the request with the contents of the named file or directory. @@ -159,22 +159,22 @@ func ServeFile(c *Conn, r *Request, name string) { } type fileHandler struct { - root string; - prefix string; + root string + prefix string } // FileServer returns a handler that serves HTTP requests // with the contents of the file system rooted at root. // It strips prefix from the incoming requests before // looking up the file name in the file system. -func FileServer(root, prefix string) Handler { return &fileHandler{root, prefix} } +func FileServer(root, prefix string) Handler { return &fileHandler{root, prefix} } func (f *fileHandler) ServeHTTP(c *Conn, r *Request) { - path := r.URL.Path; + path := r.URL.Path if !strings.HasPrefix(path, f.prefix) { - NotFound(c, r); - return; + NotFound(c, r) + return } - path = path[len(f.prefix):]; - serveFileInternal(c, r, f.root+"/"+path, true); + path = path[len(f.prefix):] + serveFileInternal(c, r, f.root+"/"+path, true) } diff --git a/src/pkg/http/request.go b/src/pkg/http/request.go index 83374a549..bf1e299d7 100644 --- a/src/pkg/http/request.go +++ b/src/pkg/http/request.go @@ -10,50 +10,50 @@ package http import ( - "bufio"; - "bytes"; - "container/vector"; - "fmt"; - "io"; - "io/ioutil"; - "os"; - "strconv"; - "strings"; + "bufio" + "bytes" + "container/vector" + "fmt" + "io" + "io/ioutil" + "os" + "strconv" + "strings" ) const ( - maxLineLength = 1024; // assumed < bufio.DefaultBufSize - maxValueLength = 1024; - maxHeaderLines = 1024; - chunkSize = 4 << 10; // 4 KB chunks + maxLineLength = 1024 // assumed < bufio.DefaultBufSize + maxValueLength = 1024 + maxHeaderLines = 1024 + chunkSize = 4 << 10 // 4 KB chunks ) // HTTP request parsing errors. type ProtocolError struct { - os.ErrorString; + os.ErrorString } var ( - ErrLineTooLong = &ProtocolError{"header line too long"}; - ErrHeaderTooLong = &ProtocolError{"header too long"}; - ErrShortBody = &ProtocolError{"entity body too short"}; + ErrLineTooLong = &ProtocolError{"header line too long"} + ErrHeaderTooLong = &ProtocolError{"header too long"} + ErrShortBody = &ProtocolError{"entity body too short"} ) type badStringError struct { - what string; - str string; + what string + str string } -func (e *badStringError) String() string { return fmt.Sprintf("%s %q", e.what, e.str) } +func (e *badStringError) String() string { return fmt.Sprintf("%s %q", e.what, e.str) } // A Request represents a parsed HTTP request header. type Request struct { - Method string; // GET, POST, PUT, etc. - RawURL string; // The raw URL given in the request. - URL *URL; // Parsed URL. - Proto string; // "HTTP/1.0" - ProtoMajor int; // 1 - ProtoMinor int; // 0 + Method string // GET, POST, PUT, etc. + RawURL string // The raw URL given in the request. + URL *URL // Parsed URL. + Proto string // "HTTP/1.0" + ProtoMajor int // 1 + ProtoMinor int // 0 // A header mapping request lines to their values. // If the header says @@ -74,18 +74,18 @@ type Request struct { // The request parser implements this by canonicalizing the // name, making the first character and any characters // following a hyphen uppercase and the rest lowercase. - Header map[string]string; + Header map[string]string // The message body. - Body io.Reader; + Body io.Reader // Whether to close the connection after replying to this request. - Close bool; + Close bool // The host on which the URL is sought. // Per RFC 2616, this is either the value of the Host: header // or the host name given in the URL itself. - Host string; + Host string // The referring URL, if sent in the request. // @@ -97,13 +97,13 @@ type Request struct { // can diagnose programs that use the alternate // (correct English) spelling req.Referrer but cannot // diagnose programs that use Header["Referrer"]. - Referer string; + Referer string // The User-Agent: header string, if sent in the request. - UserAgent string; + UserAgent string // The parsed form. Only available after ParseForm is called. - Form map[string][]string; + Form map[string][]string } // ProtoAtLeast returns whether the HTTP protocol used @@ -118,7 +118,7 @@ func valueOrDefault(value, def string) string { if value != "" { return value } - return def; + return def } const defaultUserAgent = "Go http package" @@ -134,14 +134,14 @@ const defaultUserAgent = "Go http package" // // If Body is present, "Transfer-Encoding: chunked" is forced as a header. func (req *Request) Write(w io.Writer) os.Error { - uri := URLEscape(req.URL.Path); + uri := URLEscape(req.URL.Path) if req.URL.RawQuery != "" { uri += "?" + req.URL.RawQuery } - fmt.Fprintf(w, "%s %s HTTP/1.1\r\n", valueOrDefault(req.Method, "GET"), uri); - fmt.Fprintf(w, "Host: %s\r\n", req.URL.Host); - fmt.Fprintf(w, "User-Agent: %s\r\n", valueOrDefault(req.UserAgent, defaultUserAgent)); + fmt.Fprintf(w, "%s %s HTTP/1.1\r\n", valueOrDefault(req.Method, "GET"), uri) + fmt.Fprintf(w, "Host: %s\r\n", req.URL.Host) + fmt.Fprintf(w, "User-Agent: %s\r\n", valueOrDefault(req.UserAgent, defaultUserAgent)) if req.Referer != "" { fmt.Fprintf(w, "Referer: %s\r\n", req.Referer) @@ -163,19 +163,19 @@ func (req *Request) Write(w io.Writer) os.Error { io.WriteString(w, k+": "+v+"\r\n") } - io.WriteString(w, "\r\n"); + io.WriteString(w, "\r\n") if req.Body != nil { - buf := make([]byte, chunkSize); + buf := make([]byte, chunkSize) Loop: for { - var nr, nw int; - var er, ew os.Error; + var nr, nw int + var er, ew os.Error if nr, er = req.Body.Read(buf); nr > 0 { if er == nil || er == os.EOF { - fmt.Fprintf(w, "%x\r\n", nr); - nw, ew = w.Write(buf[0:nr]); - fmt.Fprint(w, "\r\n"); + fmt.Fprintf(w, "%x\r\n", nr) + nw, ew = w.Write(buf[0:nr]) + fmt.Fprint(w, "\r\n") } } switch { @@ -183,7 +183,7 @@ func (req *Request) Write(w io.Writer) os.Error { if er == os.EOF { break Loop } - return er; + return er case ew != nil: return ew case nw < nr: @@ -191,10 +191,10 @@ func (req *Request) Write(w io.Writer) os.Error { } } // last-chunk CRLF - fmt.Fprint(w, "0\r\n\r\n"); + fmt.Fprint(w, "0\r\n\r\n") } - return nil; + return nil } // Read a line of bytes (up to \n) from b. @@ -208,29 +208,29 @@ func readLineBytes(b *bufio.Reader) (p []byte, err os.Error) { if err == os.EOF { err = io.ErrUnexpectedEOF } - return nil, err; + return nil, err } if len(p) >= maxLineLength { return nil, ErrLineTooLong } // Chop off trailing white space. - var i int; + var i int for i = len(p); i > 0; i-- { if c := p[i-1]; c != ' ' && c != '\r' && c != '\t' && c != '\n' { break } } - return p[0:i], nil; + return p[0:i], nil } // readLineBytes, but convert the bytes into a string. func readLine(b *bufio.Reader) (s string, err os.Error) { - p, e := readLineBytes(b); + p, e := readLineBytes(b) if e != nil { return "", e } - return string(p), nil; + return string(p), nil } var colon = []byte{':'} @@ -240,7 +240,7 @@ var colon = []byte{':'} // and the Value can continue on multiple lines if each continuation line // starts with a space. func readKeyValue(b *bufio.Reader) (key, value string, err os.Error) { - line, e := readLineBytes(b); + line, e := readLineBytes(b) if e != nil { return "", "", e } @@ -249,12 +249,12 @@ func readKeyValue(b *bufio.Reader) (key, value string, err os.Error) { } // Scan first line for colon. - i := bytes.Index(line, colon); + i := bytes.Index(line, colon) if i < 0 { goto Malformed } - key = string(line[0:i]); + key = string(line[0:i]) if strings.Index(key, " ") >= 0 { // Key field has space - no good. goto Malformed @@ -266,16 +266,16 @@ func readKeyValue(b *bufio.Reader) (key, value string, err os.Error) { break } } - value = string(line[i:]); + value = string(line[i:]) // Look for extension lines, which must begin with space. for { - c, e := b.ReadByte(); + c, e := b.ReadByte() if c != ' ' { if e != os.EOF { b.UnreadByte() } - break; + break } // Eat leading space. @@ -284,43 +284,43 @@ func readKeyValue(b *bufio.Reader) (key, value string, err os.Error) { if e == os.EOF { e = io.ErrUnexpectedEOF } - return "", "", e; + return "", "", e } } - b.UnreadByte(); + b.UnreadByte() // Read the rest of the line and add to value. if line, e = readLineBytes(b); e != nil { return "", "", e } - value += " " + string(line); + value += " " + string(line) if len(value) >= maxValueLength { return "", "", &badStringError{"value too long for key", key} } } - return key, value, nil; + return key, value, nil Malformed: - return "", "", &badStringError{"malformed header line", string(line)}; + return "", "", &badStringError{"malformed header line", string(line)} } // Convert decimal at s[i:len(s)] to integer, // returning value, string position where the digits stopped, // and whether there was a valid number (digits, not too big). func atoi(s string, i int) (n, i1 int, ok bool) { - const Big = 1000000; + const Big = 1000000 if i >= len(s) || s[i] < '0' || s[i] > '9' { return 0, 0, false } - n = 0; + n = 0 for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ { - n = n*10 + int(s[i]-'0'); + n = n*10 + int(s[i]-'0') if n > Big { return 0, 0, false } } - return n, i, true; + return n, i, true } // Parse HTTP version: "HTTP/1.2" -> (1, 2, true). @@ -328,16 +328,16 @@ func parseHTTPVersion(vers string) (int, int, bool) { if vers[0:5] != "HTTP/" { return 0, 0, false } - major, i, ok := atoi(vers, 5); + major, i, ok := atoi(vers, 5) if !ok || i >= len(vers) || vers[i] != '.' { return 0, 0, false } - var minor int; - minor, i, ok = atoi(vers, i+1); + var minor int + minor, i, ok = atoi(vers, i+1) if !ok || i != len(vers) { return 0, 0, false } - return major, minor, true; + return major, minor, true } var cmap = make(map[string]string) @@ -356,8 +356,8 @@ func CanonicalHeaderKey(s string) string { // and upper case after each dash. // (Host, User-Agent, If-Modified-Since). // HTTP headers are ASCII only, so no Unicode issues. - a := strings.Bytes(s); - upper := true; + a := strings.Bytes(s) + upper := true for i, v := range a { if upper && 'a' <= v && v <= 'z' { a[i] = v + 'A' - 'a' @@ -365,20 +365,20 @@ func CanonicalHeaderKey(s string) string { if !upper && 'A' <= v && v <= 'Z' { a[i] = v + 'a' - 'A' } - upper = false; + upper = false if v == '-' { upper = true } } - t := string(a); - cmap[s] = t; - return t; + t := string(a) + cmap[s] = t + return t } type chunkedReader struct { - r *bufio.Reader; - n uint64; // unread bytes in chunk - err os.Error; + r *bufio.Reader + n uint64 // unread bytes in chunk + err os.Error } func newChunkedReader(r *bufio.Reader) *chunkedReader { @@ -387,19 +387,19 @@ func newChunkedReader(r *bufio.Reader) *chunkedReader { func (cr *chunkedReader) beginChunk() { // chunk-size CRLF - var line string; - line, cr.err = readLine(cr.r); + var line string + line, cr.err = readLine(cr.r) if cr.err != nil { return } - cr.n, cr.err = strconv.Btoui64(line, 16); + cr.n, cr.err = strconv.Btoui64(line, 16) if cr.err != nil { return } if cr.n == 0 { // trailer CRLF for { - line, cr.err = readLine(cr.r); + line, cr.err = readLine(cr.r) if cr.err != nil { return } @@ -407,7 +407,7 @@ func (cr *chunkedReader) beginChunk() { break } } - cr.err = os.EOF; + cr.err = os.EOF } } @@ -416,7 +416,7 @@ func (cr *chunkedReader) Read(b []uint8) (n int, err os.Error) { return 0, cr.err } if cr.n == 0 { - cr.beginChunk(); + cr.beginChunk() if cr.err != nil { return 0, cr.err } @@ -424,36 +424,36 @@ func (cr *chunkedReader) Read(b []uint8) (n int, err os.Error) { if uint64(len(b)) > cr.n { b = b[0:cr.n] } - n, cr.err = cr.r.Read(b); - cr.n -= uint64(n); + n, cr.err = cr.r.Read(b) + cr.n -= uint64(n) if cr.n == 0 && cr.err == nil { // end of chunk (CRLF) - b := make([]byte, 2); + b := make([]byte, 2) if _, cr.err = io.ReadFull(cr.r, b); cr.err == nil { if b[0] != '\r' || b[1] != '\n' { cr.err = os.NewError("malformed chunked encoding") } } } - return n, cr.err; + return n, cr.err } // ReadRequest reads and parses a request from b. func ReadRequest(b *bufio.Reader) (req *Request, err os.Error) { - req = new(Request); + req = new(Request) // First line: GET /index.html HTTP/1.0 - var s string; + var s string if s, err = readLine(b); err != nil { return nil, err } - var f []string; + var f []string if f = strings.Split(s, " ", 3); len(f) < 3 { return nil, &badStringError{"malformed HTTP request", s} } - req.Method, req.RawURL, req.Proto = f[0], f[1], f[2]; - var ok bool; + req.Method, req.RawURL, req.Proto = f[0], f[1], f[2] + var ok bool if req.ProtoMajor, req.ProtoMinor, ok = parseHTTPVersion(req.Proto); !ok { return nil, &badStringError{"malformed HTTP version", req.Proto} } @@ -463,10 +463,10 @@ func ReadRequest(b *bufio.Reader) (req *Request, err os.Error) { } // Subsequent lines: Key: value. - nheader := 0; - req.Header = make(map[string]string); + nheader := 0 + req.Header = make(map[string]string) for { - var key, value string; + var key, value string if key, value, err = readKeyValue(b); err != nil { return nil, err } @@ -477,12 +477,12 @@ func ReadRequest(b *bufio.Reader) (req *Request, err os.Error) { return nil, ErrHeaderTooLong } - key = CanonicalHeaderKey(key); + key = CanonicalHeaderKey(key) // RFC 2616 says that if you send the same header key // multiple times, it has to be semantically equivalent // to concatenating the values separated by commas. - oldvalue, present := req.Header[key]; + oldvalue, present := req.Header[key] if present { req.Header[key] = oldvalue + "," + value } else { @@ -561,30 +561,30 @@ func ReadRequest(b *bufio.Reader) (req *Request, err os.Error) { if v, present := req.Header["Transfer-Encoding"]; present && v == "chunked" { req.Body = newChunkedReader(b) } else if v, present := req.Header["Content-Length"]; present { - length, err := strconv.Btoui64(v, 10); + length, err := strconv.Btoui64(v, 10) if err != nil { return nil, &badStringError{"invalid Content-Length", v} } // TODO: limit the Content-Length. This is an easy DoS vector. - raw := make([]byte, length); - n, err := b.Read(raw); + raw := make([]byte, length) + n, err := b.Read(raw) if err != nil || uint64(n) < length { return nil, ErrShortBody } - req.Body = bytes.NewBuffer(raw); + req.Body = bytes.NewBuffer(raw) } - return req, nil; + return req, nil } func parseForm(m map[string][]string, query string) (err os.Error) { - data := make(map[string]*vector.StringVector); + data := make(map[string]*vector.StringVector) for _, kv := range strings.Split(query, "&", 0) { - kvPair := strings.Split(kv, "=", 2); + kvPair := strings.Split(kv, "=", 2) - var key, value string; - var e os.Error; - key, e = URLUnescape(kvPair[0]); + var key, value string + var e os.Error + key, e = URLUnescape(kvPair[0]) if e == nil && len(kvPair) > 1 { value, e = URLUnescape(kvPair[1]) } @@ -592,19 +592,19 @@ func parseForm(m map[string][]string, query string) (err os.Error) { err = e } - vec, ok := data[key]; + vec, ok := data[key] if !ok { - vec = new(vector.StringVector); - data[key] = vec; + vec = new(vector.StringVector) + data[key] = vec } - vec.Push(value); + vec.Push(value) } for k, vec := range data { m[k] = vec.Data() } - return; + return } // ParseForm parses the request body as a form for POST requests, or the raw query for GET requests. @@ -613,9 +613,9 @@ func (r *Request) ParseForm() (err os.Error) { if r.Form != nil { return } - r.Form = make(map[string][]string); + r.Form = make(map[string][]string) - var query string; + var query string switch r.Method { case "GET": query = r.URL.RawQuery @@ -623,20 +623,20 @@ func (r *Request) ParseForm() (err os.Error) { if r.Body == nil { return os.ErrorString("missing form body") } - ct, _ := r.Header["Content-Type"]; + ct, _ := r.Header["Content-Type"] switch strings.Split(ct, ";", 2)[0] { case "text/plain", "application/x-www-form-urlencoded", "": - var b []byte; + var b []byte if b, err = ioutil.ReadAll(r.Body); err != nil { return err } - query = string(b); + query = string(b) // TODO(dsymonds): Handle multipart/form-data default: return &badStringError{"unknown Content-Type", ct} } } - return parseForm(r.Form, query); + return parseForm(r.Form, query) } // FormValue returns the first value for the named component of the query. @@ -648,5 +648,5 @@ func (r *Request) FormValue(key string) string { if vs, ok := r.Form[key]; ok && len(vs) > 0 { return vs[0] } - return ""; + return "" } diff --git a/src/pkg/http/request_test.go b/src/pkg/http/request_test.go index f2ef041bb..b93d1f79e 100644 --- a/src/pkg/http/request_test.go +++ b/src/pkg/http/request_test.go @@ -5,15 +5,15 @@ package http import ( - "bytes"; - "testing"; + "bytes" + "testing" ) type stringMultimap map[string][]string type parseTest struct { - query string; - out stringMultimap; + query string + out stringMultimap } var parseTests = []parseTest{ @@ -33,24 +33,24 @@ var parseTests = []parseTest{ func TestParseForm(t *testing.T) { for i, test := range parseTests { - form := make(map[string][]string); - err := parseForm(form, test.query); + form := make(map[string][]string) + err := parseForm(form, test.query) if err != nil { - t.Errorf("test %d: Unexpected error: %v", i, err); - continue; + t.Errorf("test %d: Unexpected error: %v", i, err) + continue } if len(form) != len(test.out) { t.Errorf("test %d: len(form) = %d, want %d", i, len(form), len(test.out)) } for k, evs := range test.out { - vs, ok := form[k]; + vs, ok := form[k] if !ok { - t.Errorf("test %d: Missing key %q", i, k); - continue; + t.Errorf("test %d: Missing key %q", i, k) + continue } if len(vs) != len(evs) { - t.Errorf("test %d: len(form[%q]) = %d, want %d", i, k, len(vs), len(evs)); - continue; + t.Errorf("test %d: len(form[%q]) = %d, want %d", i, k, len(vs), len(evs)) + continue } for j, ev := range evs { if v := vs[j]; v != ev { @@ -62,8 +62,8 @@ func TestParseForm(t *testing.T) { } func TestQuery(t *testing.T) { - req := &Request{Method: "GET"}; - req.URL, _ = ParseURL("http://www.google.com/search?q=foo&q=bar"); + req := &Request{Method: "GET"} + req.URL, _ = ParseURL("http://www.google.com/search?q=foo&q=bar") if q := req.FormValue("q"); q != "foo" { t.Errorf(`req.FormValue("q") = %q, want "foo"`, q) } @@ -71,8 +71,8 @@ func TestQuery(t *testing.T) { type stringMap map[string]string type parseContentTypeTest struct { - contentType stringMap; - error bool; + contentType stringMap + error bool } var parseContentTypeTests = []parseContentTypeTest{ @@ -91,8 +91,8 @@ func TestPostContentTypeParsing(t *testing.T) { Method: "POST", Header: test.contentType, Body: bytes.NewBufferString("body"), - }; - err := req.ParseForm(); + } + err := req.ParseForm() if !test.error && err != nil { t.Errorf("test %d: Unexpected error: %v", i, err) } @@ -104,14 +104,14 @@ func TestPostContentTypeParsing(t *testing.T) { func TestRedirect(t *testing.T) { const ( - start = "http://codesearch.google.com/"; - end = "http://www.google.com/codesearch"; + start = "http://codesearch.google.com/" + end = "http://www.google.com/codesearch" ) - r, url, err := Get(start); + r, url, err := Get(start) if err != nil { t.Fatal(err) } - r.Body.Close(); + r.Body.Close() if r.StatusCode != 200 || url != end { t.Fatalf("Get(%s) got status %d at %s, want 200 at %s", start, r.StatusCode, url, end) } diff --git a/src/pkg/http/server.go b/src/pkg/http/server.go index 9178d5438..f9771f9b4 100644 --- a/src/pkg/http/server.go +++ b/src/pkg/http/server.go @@ -12,61 +12,61 @@ package http import ( - "bufio"; - "fmt"; - "io"; - "log"; - "net"; - "os"; - "path"; - "strconv"; - "strings"; + "bufio" + "fmt" + "io" + "log" + "net" + "os" + "path" + "strconv" + "strings" ) // Errors introduced by the HTTP server. var ( - ErrWriteAfterFlush = os.NewError("Conn.Write called after Flush"); - ErrHijacked = os.NewError("Conn has been hijacked"); + ErrWriteAfterFlush = os.NewError("Conn.Write called after Flush") + ErrHijacked = os.NewError("Conn has been hijacked") ) // Objects implementing the Handler interface can be // registered to serve a particular path or subtree // in the HTTP server. type Handler interface { - ServeHTTP(*Conn, *Request); + ServeHTTP(*Conn, *Request) } // A Conn represents the server side of a single active HTTP connection. type Conn struct { - RemoteAddr string; // network address of remote side - Req *Request; // current HTTP request + RemoteAddr string // network address of remote side + Req *Request // current HTTP request - rwc io.ReadWriteCloser; // i/o connection - buf *bufio.ReadWriter; // buffered rwc - handler Handler; // request handler - hijacked bool; // connection has been hijacked by handler + rwc io.ReadWriteCloser // i/o connection + buf *bufio.ReadWriter // buffered rwc + handler Handler // request handler + hijacked bool // connection has been hijacked by handler // state for the current reply - closeAfterReply bool; // close connection after this reply - chunking bool; // using chunked transfer encoding for reply body - wroteHeader bool; // reply header has been written - header map[string]string; // reply header parameters - written int64; // number of bytes written in body - status int; // status code passed to WriteHeader + closeAfterReply bool // close connection after this reply + chunking bool // using chunked transfer encoding for reply body + wroteHeader bool // reply header has been written + header map[string]string // reply header parameters + written int64 // number of bytes written in body + status int // status code passed to WriteHeader } // Create new connection from rwc. func newConn(rwc net.Conn, handler Handler) (c *Conn, err os.Error) { - c = new(Conn); + c = new(Conn) if a := rwc.RemoteAddr(); a != nil { c.RemoteAddr = a.String() } - c.handler = handler; - c.rwc = rwc; - br := bufio.NewReader(rwc); - bw := bufio.NewWriter(rwc); - c.buf = bufio.NewReadWriter(br, bw); - return c, nil; + c.handler = handler + c.rwc = rwc + br := bufio.NewReader(rwc) + bw := bufio.NewWriter(rwc) + c.buf = bufio.NewReadWriter(br, bw) + return c, nil } // Read next request from connection. @@ -79,18 +79,18 @@ func (c *Conn) readRequest() (req *Request, err os.Error) { } // Reset per-request connection state. - c.header = make(map[string]string); - c.wroteHeader = false; - c.Req = req; + c.header = make(map[string]string) + c.wroteHeader = false + c.Req = req // Default output is HTML encoded in UTF-8. - c.SetHeader("Content-Type", "text/html; charset=utf-8"); + c.SetHeader("Content-Type", "text/html; charset=utf-8") if req.ProtoAtLeast(1, 1) { // HTTP/1.1 or greater: use chunked transfer encoding // to avoid closing the connection at EOF. - c.chunking = true; - c.SetHeader("Transfer-Encoding", "chunked"); + c.chunking = true + c.SetHeader("Transfer-Encoding", "chunked") } else { // HTTP version < 1.1: cannot do chunked transfer // encoding, so signal EOF by closing connection. @@ -98,11 +98,11 @@ func (c *Conn) readRequest() (req *Request, err os.Error) { // a Content-Length: header in the response, // but everyone who expects persistent connections // does HTTP/1.1 now. - c.closeAfterReply = true; - c.chunking = false; + c.closeAfterReply = true + c.chunking = false } - return req, nil; + return req, nil } // SetHeader sets a header line in the eventual reply. @@ -115,7 +115,7 @@ func (c *Conn) readRequest() (req *Request, err os.Error) { // Content-Type in this library, so users need not make that // particular call. Calls to SetHeader after WriteHeader (or Write) // are ignored. -func (c *Conn) SetHeader(hdr, val string) { c.header[CanonicalHeaderKey(hdr)] = val } +func (c *Conn) SetHeader(hdr, val string) { c.header[CanonicalHeaderKey(hdr)] = val } // WriteHeader sends an HTTP response header with status code. // If WriteHeader is not called explicitly, the first call to Write @@ -124,33 +124,33 @@ func (c *Conn) SetHeader(hdr, val string) { c.header[CanonicalHeaderKey(hdr)] = // send error codes. func (c *Conn) WriteHeader(code int) { if c.hijacked { - log.Stderr("http: Conn.WriteHeader on hijacked connection"); - return; + log.Stderr("http: Conn.WriteHeader on hijacked connection") + return } if c.wroteHeader { - log.Stderr("http: multiple Conn.WriteHeader calls"); - return; + log.Stderr("http: multiple Conn.WriteHeader calls") + return } - c.wroteHeader = true; - c.status = code; - c.written = 0; + c.wroteHeader = true + c.status = code + c.written = 0 if !c.Req.ProtoAtLeast(1, 0) { return } - proto := "HTTP/1.0"; + proto := "HTTP/1.0" if c.Req.ProtoAtLeast(1, 1) { proto = "HTTP/1.1" } - codestring := strconv.Itoa(code); - text, ok := statusText[code]; + codestring := strconv.Itoa(code) + text, ok := statusText[code] if !ok { text = "status code " + codestring } - io.WriteString(c.buf, proto+" "+codestring+" "+text+"\r\n"); + io.WriteString(c.buf, proto+" "+codestring+" "+text+"\r\n") for k, v := range c.header { io.WriteString(c.buf, k+": "+v+"\r\n") } - io.WriteString(c.buf, "\r\n"); + io.WriteString(c.buf, "\r\n") } // Write writes the data to the connection as part of an HTTP reply. @@ -158,8 +158,8 @@ func (c *Conn) WriteHeader(code int) { // before writing the data. func (c *Conn) Write(data []byte) (n int, err os.Error) { if c.hijacked { - log.Stderr("http: Conn.Write on hijacked connection"); - return 0, ErrHijacked; + log.Stderr("http: Conn.Write on hijacked connection") + return 0, ErrHijacked } if !c.wroteHeader { c.WriteHeader(StatusOK) @@ -168,15 +168,15 @@ func (c *Conn) Write(data []byte) (n int, err os.Error) { return 0, nil } - c.written += int64(len(data)); // ignoring errors, for errorKludge + c.written += int64(len(data)) // ignoring errors, for errorKludge // TODO(rsc): if chunking happened after the buffering, // then there would be fewer chunk headers. // On the other hand, it would make hijacking more difficult. if c.chunking { - fmt.Fprintf(c.buf, "%x\r\n", len(data)) // TODO(rsc): use strconv not fmt + fmt.Fprintf(c.buf, "%x\r\n", len(data)) // TODO(rsc): use strconv not fmt } - n, err = c.buf.Write(data); + n, err = c.buf.Write(data) if err == nil && c.chunking { if n != len(data) { err = io.ErrShortWrite @@ -186,7 +186,7 @@ func (c *Conn) Write(data []byte) (n int, err os.Error) { } } - return n, err; + return n, err } // If this is an error reply (4xx or 5xx) @@ -197,7 +197,7 @@ func (c *Conn) Write(data []byte) (n int, err os.Error) { // browsers are in the 256-512 range. // Pad to 1024 bytes. func errorKludge(c *Conn, req *Request) { - const min = 1024; + const min = 1024 // Is this an error? if kind := c.status / 100; kind != 4 && kind != 5 { @@ -210,7 +210,7 @@ func errorKludge(c *Conn, req *Request) { } // Is it a broken browser? - var msg string; + var msg string switch agent := req.UserAgent; { case strings.Index(agent, "MSIE") >= 0: msg = "Internet Explorer" @@ -219,19 +219,19 @@ func errorKludge(c *Conn, req *Request) { default: return } - msg += " would ignore this error page if this text weren't here.\n"; + msg += " would ignore this error page if this text weren't here.\n" // Is it text? ("Content-Type" is always in the map) - baseType := strings.Split(c.header["Content-Type"], ";", 2)[0]; + baseType := strings.Split(c.header["Content-Type"], ";", 2)[0] switch baseType { case "text/html": - io.WriteString(c, "<!-- "); + io.WriteString(c, "<!-- ") for c.written < min { io.WriteString(c, msg) } - io.WriteString(c, " -->"); + io.WriteString(c, " -->") case "text/plain": - io.WriteString(c, "\n"); + io.WriteString(c, "\n") for c.written < min { io.WriteString(c, msg) } @@ -242,13 +242,13 @@ func (c *Conn) finishRequest() { if !c.wroteHeader { c.WriteHeader(StatusOK) } - errorKludge(c, c.Req); + errorKludge(c, c.Req) if c.chunking { - io.WriteString(c.buf, "0\r\n"); + io.WriteString(c.buf, "0\r\n") // trailer key/value pairs, followed by blank line - io.WriteString(c.buf, "\r\n"); + io.WriteString(c.buf, "\r\n") } - c.buf.Flush(); + c.buf.Flush() } // Flush sends any buffered data to the client. @@ -256,41 +256,41 @@ func (c *Conn) Flush() { if !c.wroteHeader { c.WriteHeader(StatusOK) } - c.buf.Flush(); + c.buf.Flush() } // Close the connection. func (c *Conn) close() { if c.buf != nil { - c.buf.Flush(); - c.buf = nil; + c.buf.Flush() + c.buf = nil } if c.rwc != nil { - c.rwc.Close(); - c.rwc = nil; + c.rwc.Close() + c.rwc = nil } } // Serve a new connection. func (c *Conn) serve() { for { - req, err := c.readRequest(); + req, err := c.readRequest() if err != nil { break } // HTTP cannot have multiple simultaneous active requests. // Until the server replies to this request, it can't read another, // so we might as well run the handler in this goroutine. - c.handler.ServeHTTP(c, req); + c.handler.ServeHTTP(c, req) if c.hijacked { return } - c.finishRequest(); + c.finishRequest() if c.closeAfterReply { break } } - c.close(); + c.close() } // Hijack lets the caller take over the connection. @@ -302,12 +302,12 @@ func (c *Conn) Hijack() (rwc io.ReadWriteCloser, buf *bufio.ReadWriter, err os.E if c.hijacked { return nil, nil, ErrHijacked } - c.hijacked = true; - rwc = c.rwc; - buf = c.buf; - c.rwc = nil; - c.buf = nil; - return; + c.hijacked = true + rwc = c.rwc + buf = c.buf + c.rwc = nil + c.buf = nil + return } // The HandlerFunc type is an adapter to allow the use of @@ -325,26 +325,26 @@ func (f HandlerFunc) ServeHTTP(c *Conn, req *Request) { // NotFound replies to the request with an HTTP 404 not found error. func NotFound(c *Conn, req *Request) { - c.SetHeader("Content-Type", "text/plain; charset=utf-8"); - c.WriteHeader(StatusNotFound); - io.WriteString(c, "404 page not found\n"); + c.SetHeader("Content-Type", "text/plain; charset=utf-8") + c.WriteHeader(StatusNotFound) + io.WriteString(c, "404 page not found\n") } // NotFoundHandler returns a simple request handler // that replies to each request with a ``404 page not found'' reply. -func NotFoundHandler() Handler { return HandlerFunc(NotFound) } +func NotFoundHandler() Handler { return HandlerFunc(NotFound) } // Redirect replies to the request with a redirect to url, // which may be a path relative to the request path. func Redirect(c *Conn, url string, code int) { // RFC2616 recommends that a short note "SHOULD" be included in the // response because older user agents may not understand 301/307. - note := "<a href=\"%v\">" + statusText[code] + "</a>.\n"; + note := "<a href=\"%v\">" + statusText[code] + "</a>.\n" if c.Req.Method == "POST" { note = "" } - u, err := ParseURL(url); + u, err := ParseURL(url) if err != nil { goto finish } @@ -365,36 +365,36 @@ func Redirect(c *Conn, url string, code int) { // Because of this problem, no one pays attention // to the RFC; they all send back just a new path. // So do we. - oldpath := c.Req.URL.Path; - if oldpath == "" { // should not happen, but avoid a crash if it does + oldpath := c.Req.URL.Path + if oldpath == "" { // should not happen, but avoid a crash if it does oldpath = "/" } if u.Scheme == "" { // no leading http://server if url == "" || url[0] != '/' { // make relative path absolute - olddir, _ := path.Split(oldpath); - url = olddir + url; + olddir, _ := path.Split(oldpath) + url = olddir + url } // clean up but preserve trailing slash - trailing := url[len(url)-1] == '/'; - url = path.Clean(url); + trailing := url[len(url)-1] == '/' + url = path.Clean(url) if trailing && url[len(url)-1] != '/' { url += "/" } } finish: - c.SetHeader("Location", url); - c.WriteHeader(code); - fmt.Fprintf(c, note, url); + c.SetHeader("Location", url) + c.WriteHeader(code) + fmt.Fprintf(c, note, url) } // Redirect to a fixed URL type redirectHandler struct { - url string; - code int; + url string + code int } func (rh *redirectHandler) ServeHTTP(c *Conn, req *Request) { @@ -433,11 +433,11 @@ func RedirectHandler(url string, code int) Handler { // redirecting any request containing . or .. elements to an // equivalent .- and ..-free URL. type ServeMux struct { - m map[string]Handler; + m map[string]Handler } // NewServeMux allocates and returns a new ServeMux. -func NewServeMux() *ServeMux { return &ServeMux{make(map[string]Handler)} } +func NewServeMux() *ServeMux { return &ServeMux{make(map[string]Handler)} } // DefaultServeMux is the default ServeMux used by Serve. var DefaultServeMux = NewServeMux() @@ -448,11 +448,11 @@ func pathMatch(pattern, path string) bool { // should not happen return false } - n := len(pattern); + n := len(pattern) if pattern[n-1] != '/' { return pattern == path } - return len(path) >= n && path[0:n] == pattern; + return len(path) >= n && path[0:n] == pattern } // Return the canonical path for p, eliminating . and .. elements. @@ -463,13 +463,13 @@ func cleanPath(p string) string { if p[0] != '/' { p = "/" + p } - np := path.Clean(p); + np := path.Clean(p) // path.Clean removes trailing slash except for root; // put the trailing slash back if necessary. if p[len(p)-1] == '/' && np != "/" { np += "/" } - return np; + return np } // ServeHTTP dispatches the request to the handler whose @@ -477,27 +477,27 @@ func cleanPath(p string) string { func (mux *ServeMux) ServeHTTP(c *Conn, req *Request) { // Clean path to canonical form and redirect. if p := cleanPath(req.URL.Path); p != req.URL.Path { - c.SetHeader("Location", p); - c.WriteHeader(StatusMovedPermanently); - return; + c.SetHeader("Location", p) + c.WriteHeader(StatusMovedPermanently) + return } // Most-specific (longest) pattern wins. - var h Handler; - var n = 0; + var h Handler + var n = 0 for k, v := range mux.m { if !pathMatch(k, req.URL.Path) { continue } if h == nil || len(k) > n { - n = len(k); - h = v; + n = len(k) + h = v } } if h == nil { h = NotFoundHandler() } - h.ServeHTTP(c, req); + h.ServeHTTP(c, req) } // Handle registers the handler for the given pattern. @@ -506,11 +506,11 @@ func (mux *ServeMux) Handle(pattern string, handler Handler) { panicln("http: invalid pattern", pattern) } - mux.m[pattern] = handler; + mux.m[pattern] = handler // Helpful behavior: // If pattern is /tree/, insert permanent redirect for /tree. - n := len(pattern); + n := len(pattern) if n > 0 && pattern[n-1] == '/' { mux.m[pattern[0:n-1]] = RedirectHandler(pattern, StatusMovedPermanently) } @@ -518,7 +518,7 @@ func (mux *ServeMux) Handle(pattern string, handler Handler) { // Handle registers the handler for the given pattern // in the DefaultServeMux. -func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) } +func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) } // Serve accepts incoming HTTP connections on the listener l, // creating a new service thread for each. The service threads @@ -529,17 +529,17 @@ func Serve(l net.Listener, handler Handler) os.Error { handler = DefaultServeMux } for { - rw, e := l.Accept(); + rw, e := l.Accept() if e != nil { return e } - c, err := newConn(rw, handler); + c, err := newConn(rw, handler) if err != nil { continue } - go c.serve(); + go c.serve() } - panic("not reached"); + panic("not reached") } // ListenAndServe listens on the TCP network address addr @@ -569,11 +569,11 @@ func Serve(l net.Listener, handler Handler) os.Error { // } // } func ListenAndServe(addr string, handler Handler) os.Error { - l, e := net.Listen("tcp", addr); + l, e := net.Listen("tcp", addr) if e != nil { return e } - e = Serve(l, handler); - l.Close(); - return e; + e = Serve(l, handler) + l.Close() + return e } diff --git a/src/pkg/http/status.go b/src/pkg/http/status.go index 21662c7ea..e39c19806 100644 --- a/src/pkg/http/status.go +++ b/src/pkg/http/status.go @@ -6,50 +6,50 @@ package http // HTTP status codes, defined in RFC 2616. const ( - StatusContinue = 100; - StatusSwitchingProtocols = 101; + StatusContinue = 100 + StatusSwitchingProtocols = 101 - StatusOK = 200; - StatusCreated = 201; - StatusAccepted = 202; - StatusNonAuthoritativeInfo = 203; - StatusNoContent = 204; - StatusResetContent = 205; - StatusPartialContent = 206; + StatusOK = 200 + StatusCreated = 201 + StatusAccepted = 202 + StatusNonAuthoritativeInfo = 203 + StatusNoContent = 204 + StatusResetContent = 205 + StatusPartialContent = 206 - StatusMultipleChoices = 300; - StatusMovedPermanently = 301; - StatusFound = 302; - StatusSeeOther = 303; - StatusNotModified = 304; - StatusUseProxy = 305; - StatusTemporaryRedirect = 307; + StatusMultipleChoices = 300 + StatusMovedPermanently = 301 + StatusFound = 302 + StatusSeeOther = 303 + StatusNotModified = 304 + StatusUseProxy = 305 + StatusTemporaryRedirect = 307 - StatusBadRequest = 400; - StatusUnauthorized = 401; - StatusPaymentRequired = 402; - StatusForbidden = 403; - StatusNotFound = 404; - StatusMethodNotAllowed = 405; - StatusNotAcceptable = 406; - StatusProxyAuthRequired = 407; - StatusRequestTimeout = 408; - StatusConflict = 409; - StatusGone = 410; - StatusLengthRequired = 411; - StatusPreconditionFailed = 412; - StatusRequestEntityTooLarge = 413; - StatusRequestURITooLong = 414; - StatusUnsupportedMediaType = 415; - StatusRequestedRangeNotSatisfiable = 416; - StatusExpectationFailed = 417; + StatusBadRequest = 400 + StatusUnauthorized = 401 + StatusPaymentRequired = 402 + StatusForbidden = 403 + StatusNotFound = 404 + StatusMethodNotAllowed = 405 + StatusNotAcceptable = 406 + StatusProxyAuthRequired = 407 + StatusRequestTimeout = 408 + StatusConflict = 409 + StatusGone = 410 + StatusLengthRequired = 411 + StatusPreconditionFailed = 412 + StatusRequestEntityTooLarge = 413 + StatusRequestURITooLong = 414 + StatusUnsupportedMediaType = 415 + StatusRequestedRangeNotSatisfiable = 416 + StatusExpectationFailed = 417 - StatusInternalServerError = 500; - StatusNotImplemented = 501; - StatusBadGateway = 502; - StatusServiceUnavailable = 503; - StatusGatewayTimeout = 504; - StatusHTTPVersionNotSupported = 505; + StatusInternalServerError = 500 + StatusNotImplemented = 501 + StatusBadGateway = 502 + StatusServiceUnavailable = 503 + StatusGatewayTimeout = 504 + StatusHTTPVersionNotSupported = 505 ) var statusText = map[int]string{ diff --git a/src/pkg/http/triv.go b/src/pkg/http/triv.go index 529a6ebff..dea2c23b0 100644 --- a/src/pkg/http/triv.go +++ b/src/pkg/http/triv.go @@ -5,16 +5,16 @@ package main import ( - "bytes"; - "bufio"; - "expvar"; - "flag"; - "fmt"; - "io"; - "log"; - "net"; - "os"; - "strconv"; + "bytes" + "bufio" + "expvar" + "flag" + "fmt" + "io" + "log" + "net" + "os" + "strconv" ) @@ -22,35 +22,35 @@ import ( var helloRequests = expvar.NewInt("hello-requests") func HelloServer(c *http.Conn, req *http.Request) { - helloRequests.Add(1); - io.WriteString(c, "hello, world!\n"); + helloRequests.Add(1) + io.WriteString(c, "hello, world!\n") } // Simple counter server. POSTing to it will set the value. type Counter struct { - n int; + n int } // This makes Counter satisfy the expvar.Var interface, so we can export // it directly. -func (ctr *Counter) String() string { return fmt.Sprintf("%d", ctr.n) } +func (ctr *Counter) String() string { return fmt.Sprintf("%d", ctr.n) } func (ctr *Counter) ServeHTTP(c *http.Conn, req *http.Request) { switch req.Method { case "GET": ctr.n++ case "POST": - buf := new(bytes.Buffer); - io.Copy(buf, req.Body); - body := buf.String(); + buf := new(bytes.Buffer) + io.Copy(buf, req.Body) + body := buf.String() if n, err := strconv.Atoi(body); err != nil { fmt.Fprintf(c, "bad POST: %v\nbody: [%v]\n", err, body) } else { - ctr.n = n; - fmt.Fprint(c, "counter reset\n"); + ctr.n = n + fmt.Fprint(c, "counter reset\n") } } - fmt.Fprintf(c, "counter = %d\n", ctr.n); + fmt.Fprintf(c, "counter = %d\n", ctr.n) } // simple file server @@ -58,33 +58,33 @@ var webroot = flag.String("root", "/home/rsc", "web root directory") var pathVar = expvar.NewMap("file-requests") func FileServer(c *http.Conn, req *http.Request) { - c.SetHeader("content-type", "text/plain; charset=utf-8"); - pathVar.Add(req.URL.Path, 1); - path := *webroot + req.URL.Path; // TODO: insecure: use os.CleanName - f, err := os.Open(path, os.O_RDONLY, 0); + c.SetHeader("content-type", "text/plain; charset=utf-8") + pathVar.Add(req.URL.Path, 1) + path := *webroot + req.URL.Path // TODO: insecure: use os.CleanName + f, err := os.Open(path, os.O_RDONLY, 0) if err != nil { - c.WriteHeader(http.StatusNotFound); - fmt.Fprintf(c, "open %s: %v\n", path, err); - return; + c.WriteHeader(http.StatusNotFound) + fmt.Fprintf(c, "open %s: %v\n", path, err) + return } - n, err1 := io.Copy(c, f); - fmt.Fprintf(c, "[%d bytes]\n", n); - f.Close(); + n, err1 := io.Copy(c, f) + fmt.Fprintf(c, "[%d bytes]\n", n) + f.Close() } // simple flag server var booleanflag = flag.Bool("boolean", true, "another flag for testing") func FlagServer(c *http.Conn, req *http.Request) { - c.SetHeader("content-type", "text/plain; charset=utf-8"); - fmt.Fprint(c, "Flags:\n"); + c.SetHeader("content-type", "text/plain; charset=utf-8") + fmt.Fprint(c, "Flags:\n") flag.VisitAll(func(f *flag.Flag) { if f.Value.String() != f.DefValue { fmt.Fprintf(c, "%s = %s [default = %s]\n", f.Name, f.Value.String(), f.DefValue) } else { fmt.Fprintf(c, "%s = %s\n", f.Name, f.Value.String()) } - }); + }) } // simple argument server @@ -98,13 +98,13 @@ func ArgServer(c *http.Conn, req *http.Request) { type Chan chan int func ChanCreate() Chan { - c := make(Chan); + c := make(Chan) go func(c Chan) { for x := 0; ; x++ { c <- x } - }(c); - return c; + }(c) + return c } func (ch Chan) ServeHTTP(c *http.Conn, req *http.Request) { @@ -113,46 +113,46 @@ func (ch Chan) ServeHTTP(c *http.Conn, req *http.Request) { // exec a program, redirecting output func DateServer(c *http.Conn, req *http.Request) { - c.SetHeader("content-type", "text/plain; charset=utf-8"); - r, w, err := os.Pipe(); + c.SetHeader("content-type", "text/plain; charset=utf-8") + r, w, err := os.Pipe() if err != nil { - fmt.Fprintf(c, "pipe: %s\n", err); - return; + fmt.Fprintf(c, "pipe: %s\n", err) + return } - pid, err := os.ForkExec("/bin/date", []string{"date"}, os.Environ(), "", []*os.File{nil, w, w}); - defer r.Close(); - w.Close(); + pid, err := os.ForkExec("/bin/date", []string{"date"}, os.Environ(), "", []*os.File{nil, w, w}) + defer r.Close() + w.Close() if err != nil { - fmt.Fprintf(c, "fork/exec: %s\n", err); - return; + fmt.Fprintf(c, "fork/exec: %s\n", err) + return } - io.Copy(c, r); - wait, err := os.Wait(pid, 0); + io.Copy(c, r) + wait, err := os.Wait(pid, 0) if err != nil { - fmt.Fprintf(c, "wait: %s\n", err); - return; + fmt.Fprintf(c, "wait: %s\n", err) + return } if !wait.Exited() || wait.ExitStatus() != 0 { - fmt.Fprintf(c, "date: %v\n", wait); - return; + fmt.Fprintf(c, "date: %v\n", wait) + return } } func main() { - flag.Parse(); + flag.Parse() // The counter is published as a variable directly. - ctr := new(Counter); - http.Handle("/counter", ctr); - expvar.Publish("counter", ctr); - - http.Handle("/go/", http.HandlerFunc(FileServer)); - http.Handle("/flags", http.HandlerFunc(FlagServer)); - http.Handle("/args", http.HandlerFunc(ArgServer)); - http.Handle("/go/hello", http.HandlerFunc(HelloServer)); - http.Handle("/chan", ChanCreate()); - http.Handle("/date", http.HandlerFunc(DateServer)); - err := http.ListenAndServe(":12345", nil); + ctr := new(Counter) + http.Handle("/counter", ctr) + expvar.Publish("counter", ctr) + + http.Handle("/go/", http.HandlerFunc(FileServer)) + http.Handle("/flags", http.HandlerFunc(FlagServer)) + http.Handle("/args", http.HandlerFunc(ArgServer)) + http.Handle("/go/hello", http.HandlerFunc(HelloServer)) + http.Handle("/chan", ChanCreate()) + http.Handle("/date", http.HandlerFunc(DateServer)) + err := http.ListenAndServe(":12345", nil) if err != nil { log.Crash("ListenAndServe: ", err) } diff --git a/src/pkg/http/url.go b/src/pkg/http/url.go index ddf0ba986..ca8c344be 100644 --- a/src/pkg/http/url.go +++ b/src/pkg/http/url.go @@ -8,19 +8,19 @@ package http import ( - "os"; - "strconv"; - "strings"; + "os" + "strconv" + "strings" ) // URLError reports an error and the operation and URL that caused it. type URLError struct { - Op string; - URL string; - Error os.Error; + Op string + URL string + Error os.Error } -func (e *URLError) String() string { return e.Op + " " + e.URL + ": " + e.Error.String() } +func (e *URLError) String() string { return e.Op + " " + e.URL + ": " + e.Error.String() } func ishex(c byte) bool { switch { @@ -31,7 +31,7 @@ func ishex(c byte) bool { case 'A' <= c && c <= 'F': return true } - return false; + return false } func unhex(c byte) byte { @@ -43,7 +43,7 @@ func unhex(c byte) byte { case 'A' <= c && c <= 'F': return c - 'A' + 10 } - return 0; + return 0 } type URLEscapeError string @@ -59,12 +59,12 @@ func shouldEscape(c byte) bool { return true } switch c { - case '<', '>', '#', '%', '"', // RFC 2396 delims - '{', '}', '|', '\\', '^', '[', ']', '`', // RFC2396 unwise - '?', '&', '=', '+': // RFC 2396 reserved in path + case '<', '>', '#', '%', '"', // RFC 2396 delims + '{', '}', '|', '\\', '^', '[', ']', '`', // RFC2396 unwise + '?', '&', '=', '+': // RFC 2396 reserved in path return true } - return false; + return false } // URLUnescape unescapes a URL-encoded string, @@ -73,23 +73,23 @@ func shouldEscape(c byte) bool { // by two hexadecimal digits. func URLUnescape(s string) (string, os.Error) { // Count %, check that they're well-formed. - n := 0; - hasPlus := false; + n := 0 + hasPlus := false for i := 0; i < len(s); { switch s[i] { case '%': - n++; + n++ if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) { - s = s[i:]; + s = s[i:] if len(s) > 3 { s = s[0:3] } - return "", URLEscapeError(s); + return "", URLEscapeError(s) } - i += 3; + i += 3 case '+': - hasPlus = true; - i++; + hasPlus = true + i++ default: i++ } @@ -99,32 +99,32 @@ func URLUnescape(s string) (string, os.Error) { return s, nil } - t := make([]byte, len(s)-2*n); - j := 0; + t := make([]byte, len(s)-2*n) + j := 0 for i := 0; i < len(s); { switch s[i] { case '%': - t[j] = unhex(s[i+1])<<4 | unhex(s[i+2]); - j++; - i += 3; + t[j] = unhex(s[i+1])<<4 | unhex(s[i+2]) + j++ + i += 3 case '+': - t[j] = ' '; - j++; - i++; + t[j] = ' ' + j++ + i++ default: - t[j] = s[i]; - j++; - i++; + t[j] = s[i] + j++ + i++ } } - return string(t), nil; + return string(t), nil } // URLEscape converts a string into URL-encoded form. func URLEscape(s string) string { - spaceCount, hexCount := 0, 0; + spaceCount, hexCount := 0, 0 for i := 0; i < len(s); i++ { - c := s[i]; + c := s[i] if shouldEscape(c) { if c == ' ' { spaceCount++ @@ -138,24 +138,24 @@ func URLEscape(s string) string { return s } - t := make([]byte, len(s)+2*hexCount); - j := 0; + t := make([]byte, len(s)+2*hexCount) + j := 0 for i := 0; i < len(s); i++ { switch c := s[i]; { case c == ' ': - t[j] = '+'; - j++; + t[j] = '+' + j++ case shouldEscape(c): - t[j] = '%'; - t[j+1] = "0123456789abcdef"[c>>4]; - t[j+2] = "0123456789abcdef"[c&15]; - j += 3; + t[j] = '%' + t[j+1] = "0123456789abcdef"[c>>4] + t[j+2] = "0123456789abcdef"[c&15] + j += 3 default: - t[j] = s[i]; - j++; + t[j] = s[i] + j++ } } - return string(t); + return string(t) } // A URL represents a parsed URL (technically, a URI reference). @@ -168,15 +168,15 @@ func URLEscape(s string) string { // Note, the reason for using wire format for the query is that it needs // to be split into key/value pairs before decoding. type URL struct { - Raw string; // the original string - Scheme string; // scheme - RawPath string; // //[userinfo@]host/path[?query][#fragment] - Authority string; // [userinfo@]host - Userinfo string; // userinfo - Host string; // host - Path string; // /path - RawQuery string; // query - Fragment string; // fragment + Raw string // the original string + Scheme string // scheme + RawPath string // //[userinfo@]host/path[?query][#fragment] + Authority string // [userinfo@]host + Userinfo string // userinfo + Host string // host + Path string // /path + RawQuery string // query + Fragment string // fragment } // Maybe rawurl is of the form scheme:path. @@ -184,7 +184,7 @@ type URL struct { // If so, return scheme, path; else return "", rawurl. func getscheme(rawurl string) (scheme, path string, err os.Error) { for i := 0; i < len(rawurl); i++ { - c := rawurl[i]; + c := rawurl[i] switch { case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z': // do nothing @@ -196,14 +196,14 @@ func getscheme(rawurl string) (scheme, path string, err os.Error) { if i == 0 { return "", "", os.ErrorString("missing protocol scheme") } - return rawurl[0:i], rawurl[i+1:], nil; + return rawurl[0:i], rawurl[i+1:], nil default: // we have encountered an invalid character, // so there is no valid scheme return "", rawurl, nil } } - return "", rawurl, nil; + return "", rawurl, nil } // Maybe s is of the form t c u. @@ -215,10 +215,10 @@ func split(s string, c byte, cutc bool) (string, string) { if cutc { return s[0:i], s[i+1:] } - return s[0:i], s[i:]; + return s[0:i], s[i:] } } - return s, ""; + return s, "" } // TODO(rsc): The BUG comment is supposed to appear in the godoc output @@ -233,18 +233,18 @@ func split(s string, c byte, cutc bool) (string, string) { // (Web browsers strip #fragment before sending the URL to a web server.) func ParseURL(rawurl string) (url *URL, err os.Error) { if rawurl == "" { - err = os.ErrorString("empty url"); - goto Error; + err = os.ErrorString("empty url") + goto Error } - url = new(URL); - url.Raw = rawurl; + url = new(URL) + url.Raw = rawurl // split off possible leading "http:", "mailto:", etc. - var path string; + var path string if url.Scheme, path, err = getscheme(rawurl); err != nil { goto Error } - url.RawPath = path; + url.RawPath = path // RFC 2396: a relative URI (no scheme) has a ?query, // but absolute URIs only have query if path begins with / @@ -279,32 +279,32 @@ func ParseURL(rawurl string) (url *URL, err os.Error) { goto Error } if strings.Index(url.Scheme, "%") >= 0 { - err = os.ErrorString("hexadecimal escape in scheme"); - goto Error; + err = os.ErrorString("hexadecimal escape in scheme") + goto Error } if strings.Index(url.Host, "%") >= 0 { - err = os.ErrorString("hexadecimal escape in host"); - goto Error; + err = os.ErrorString("hexadecimal escape in host") + goto Error } - return url, nil; + return url, nil Error: - return nil, &URLError{"parse", rawurl, err}; + return nil, &URLError{"parse", rawurl, err} } // ParseURLReference is like ParseURL but allows a trailing #fragment. func ParseURLReference(rawurlref string) (url *URL, err os.Error) { // Cut off #frag. - rawurl, frag := split(rawurlref, '#', true); + rawurl, frag := split(rawurlref, '#', true) if url, err = ParseURL(rawurl); err != nil { return nil, err } if url.Fragment, err = URLUnescape(frag); err != nil { return nil, &URLError{"parse", rawurl, err} } - return url, nil; + return url, nil } // String reassembles url into a valid URL string. @@ -313,23 +313,23 @@ func ParseURLReference(rawurlref string) (url *URL, err os.Error) { // the String method consults Scheme, Path, Host, Userinfo, // RawQuery, and Fragment, but not Raw, RawPath or Authority. func (url *URL) String() string { - result := ""; + result := "" if url.Scheme != "" { result += url.Scheme + ":" } if url.Host != "" || url.Userinfo != "" { - result += "//"; + result += "//" if url.Userinfo != "" { result += URLEscape(url.Userinfo) + "@" } - result += url.Host; + result += url.Host } - result += URLEscape(url.Path); + result += URLEscape(url.Path) if url.RawQuery != "" { result += "?" + url.RawQuery } if url.Fragment != "" { result += "#" + URLEscape(url.Fragment) } - return result; + return result } diff --git a/src/pkg/http/url_test.go b/src/pkg/http/url_test.go index 2f9707a2e..0e3fa2d6e 100644 --- a/src/pkg/http/url_test.go +++ b/src/pkg/http/url_test.go @@ -5,10 +5,10 @@ package http import ( - "fmt"; - "os"; - "reflect"; - "testing"; + "fmt" + "os" + "reflect" + "testing" ) // TODO(rsc): @@ -17,9 +17,9 @@ import ( // test ParseURL type URLTest struct { - in string; - out *URL; - roundtrip string; // expected result of reserializing the URL; empty means same as "in". + in string + out *URL + roundtrip string // expected result of reserializing the URL; empty means same as "in". } var urltests = []URLTest{ @@ -191,10 +191,10 @@ func ufmt(u *URL) string { func DoTest(t *testing.T, parse func(string) (*URL, os.Error), name string, tests []URLTest) { for _, tt := range tests { - u, err := parse(tt.in); + u, err := parse(tt.in) if err != nil { - t.Errorf("%s(%q) returned error %s", name, tt.in, err); - continue; + t.Errorf("%s(%q) returned error %s", name, tt.in, err) + continue } if !reflect.DeepEqual(u, tt.out) { t.Errorf("%s(%q):\n\thave %v\n\twant %v\n", @@ -204,24 +204,24 @@ func DoTest(t *testing.T, parse func(string) (*URL, os.Error), name string, test } func TestParseURL(t *testing.T) { - DoTest(t, ParseURL, "ParseURL", urltests); - DoTest(t, ParseURL, "ParseURL", urlnofragtests); + DoTest(t, ParseURL, "ParseURL", urltests) + DoTest(t, ParseURL, "ParseURL", urlnofragtests) } func TestParseURLReference(t *testing.T) { - DoTest(t, ParseURLReference, "ParseURLReference", urltests); - DoTest(t, ParseURLReference, "ParseURLReference", urlfragtests); + DoTest(t, ParseURLReference, "ParseURLReference", urltests) + DoTest(t, ParseURLReference, "ParseURLReference", urlfragtests) } func DoTestString(t *testing.T, parse func(string) (*URL, os.Error), name string, tests []URLTest) { for _, tt := range tests { - u, err := parse(tt.in); + u, err := parse(tt.in) if err != nil { - t.Errorf("%s(%q) returned error %s", name, tt.in, err); - continue; + t.Errorf("%s(%q) returned error %s", name, tt.in, err) + continue } - s := u.String(); - expected := tt.in; + s := u.String() + expected := tt.in if len(tt.roundtrip) > 0 { expected = tt.roundtrip } @@ -232,18 +232,18 @@ func DoTestString(t *testing.T, parse func(string) (*URL, os.Error), name string } func TestURLString(t *testing.T) { - DoTestString(t, ParseURL, "ParseURL", urltests); - DoTestString(t, ParseURL, "ParseURL", urlfragtests); - DoTestString(t, ParseURL, "ParseURL", urlnofragtests); - DoTestString(t, ParseURLReference, "ParseURLReference", urltests); - DoTestString(t, ParseURLReference, "ParseURLReference", urlfragtests); - DoTestString(t, ParseURLReference, "ParseURLReference", urlnofragtests); + DoTestString(t, ParseURL, "ParseURL", urltests) + DoTestString(t, ParseURL, "ParseURL", urlfragtests) + DoTestString(t, ParseURL, "ParseURL", urlnofragtests) + DoTestString(t, ParseURLReference, "ParseURLReference", urltests) + DoTestString(t, ParseURLReference, "ParseURLReference", urlfragtests) + DoTestString(t, ParseURLReference, "ParseURLReference", urlnofragtests) } type URLEscapeTest struct { - in string; - out string; - err os.Error; + in string + out string + err os.Error } var unescapeTests = []URLEscapeTest{ @@ -278,27 +278,27 @@ var unescapeTests = []URLEscapeTest{ nil, }, URLEscapeTest{ - "%", // not enough characters after % + "%", // not enough characters after % "", URLEscapeError("%"), }, URLEscapeTest{ - "%a", // not enough characters after % + "%a", // not enough characters after % "", URLEscapeError("%a"), }, URLEscapeTest{ - "%1", // not enough characters after % + "%1", // not enough characters after % "", URLEscapeError("%1"), }, URLEscapeTest{ - "123%45%6", // not enough characters after % + "123%45%6", // not enough characters after % "", URLEscapeError("%6"), }, URLEscapeTest{ - "%zzzzz", // invalid hex digits + "%zzzzz", // invalid hex digits "", URLEscapeError("%zz"), }, @@ -306,7 +306,7 @@ var unescapeTests = []URLEscapeTest{ func TestURLUnescape(t *testing.T) { for _, tt := range unescapeTests { - actual, err := URLUnescape(tt.in); + actual, err := URLUnescape(tt.in) if actual != tt.out || (err != nil) != (tt.err != nil) { t.Errorf("URLUnescape(%q) = %q, %s; want %q, %s", tt.in, actual, err, tt.out, tt.err) } @@ -343,13 +343,13 @@ var escapeTests = []URLEscapeTest{ func TestURLEscape(t *testing.T) { for _, tt := range escapeTests { - actual := URLEscape(tt.in); + actual := URLEscape(tt.in) if tt.out != actual { t.Errorf("URLEscape(%q) = %q, want %q", tt.in, actual, tt.out) } // for bonus points, verify that escape:unescape is an identity. - roundtrip, err := URLUnescape(actual); + roundtrip, err := URLUnescape(actual) if roundtrip != tt.in || err != nil { t.Errorf("URLUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]") } diff --git a/src/pkg/image/color.go b/src/pkg/image/color.go index bf8eefb60..8594ac538 100644 --- a/src/pkg/image/color.go +++ b/src/pkg/image/color.go @@ -8,102 +8,102 @@ package image // All Colors can convert themselves, with a possible loss of precision, to 128-bit alpha-premultiplied RGBA. type Color interface { - RGBA() (r, g, b, a uint32); + RGBA() (r, g, b, a uint32) } // An RGBAColor represents a traditional 32-bit alpha-premultiplied color, having 8 bits for each of red, green, blue and alpha. type RGBAColor struct { - R, G, B, A uint8; + R, G, B, A uint8 } func (c RGBAColor) RGBA() (r, g, b, a uint32) { - r = uint32(c.R); - r |= r << 8; - r |= r << 16; - g = uint32(c.G); - g |= g << 8; - g |= g << 16; - b = uint32(c.B); - b |= b << 8; - b |= b << 16; - a = uint32(c.A); - a |= a << 8; - a |= a << 16; - return; + r = uint32(c.R) + r |= r << 8 + r |= r << 16 + g = uint32(c.G) + g |= g << 8 + g |= g << 16 + b = uint32(c.B) + b |= b << 8 + b |= b << 16 + a = uint32(c.A) + a |= a << 8 + a |= a << 16 + return } // An RGBA64Color represents a 64-bit alpha-premultiplied color, having 16 bits for each of red, green, blue and alpha. type RGBA64Color struct { - R, G, B, A uint16; + R, G, B, A uint16 } func (c RGBA64Color) RGBA() (r, g, b, a uint32) { - r = uint32(c.R); - r |= r << 16; - g = uint32(c.G); - g |= g << 16; - b = uint32(c.B); - b |= b << 16; - a = uint32(c.A); - a |= a << 16; - return; + r = uint32(c.R) + r |= r << 16 + g = uint32(c.G) + g |= g << 16 + b = uint32(c.B) + b |= b << 16 + a = uint32(c.A) + a |= a << 16 + return } // An NRGBAColor represents a non-alpha-premultiplied 32-bit color. type NRGBAColor struct { - R, G, B, A uint8; + R, G, B, A uint8 } func (c NRGBAColor) RGBA() (r, g, b, a uint32) { - r = uint32(c.R); - r |= r << 8; - r *= uint32(c.A); - r /= 0xff; - r |= r << 16; - g = uint32(c.G); - g |= g << 8; - g *= uint32(c.A); - g /= 0xff; - g |= g << 16; - b = uint32(c.B); - b |= b << 8; - b *= uint32(c.A); - b /= 0xff; - b |= b << 16; - a = uint32(c.A); - a |= a << 8; - a |= a << 16; - return; + r = uint32(c.R) + r |= r << 8 + r *= uint32(c.A) + r /= 0xff + r |= r << 16 + g = uint32(c.G) + g |= g << 8 + g *= uint32(c.A) + g /= 0xff + g |= g << 16 + b = uint32(c.B) + b |= b << 8 + b *= uint32(c.A) + b /= 0xff + b |= b << 16 + a = uint32(c.A) + a |= a << 8 + a |= a << 16 + return } // An NRGBA64Color represents a non-alpha-premultiplied 64-bit color, having 16 bits for each of red, green, blue and alpha. type NRGBA64Color struct { - R, G, B, A uint16; + R, G, B, A uint16 } func (c NRGBA64Color) RGBA() (r, g, b, a uint32) { - r = uint32(c.R); - r *= uint32(c.A); - r /= 0xffff; - r |= r << 16; - g = uint32(c.G); - g *= uint32(c.A); - g /= 0xffff; - g |= g << 16; - b = uint32(c.B); - b *= uint32(c.A); - b /= 0xffff; - b |= b << 16; - a = uint32(c.A); - a |= a << 8; - a |= a << 16; - return; + r = uint32(c.R) + r *= uint32(c.A) + r /= 0xffff + r |= r << 16 + g = uint32(c.G) + g *= uint32(c.A) + g /= 0xffff + g |= g << 16 + b = uint32(c.B) + b *= uint32(c.A) + b /= 0xffff + b |= b << 16 + a = uint32(c.A) + a |= a << 8 + a |= a << 16 + return } // A ColorModel can convert foreign Colors, with a possible loss of precision, to a Color // from its own color model. type ColorModel interface { - Convert(c Color) Color; + Convert(c Color) Color } // The ColorModelFunc type is an adapter to allow the use of an ordinary @@ -117,52 +117,52 @@ func (f ColorModelFunc) Convert(c Color) Color { } func toRGBAColor(c Color) Color { - if _, ok := c.(RGBAColor); ok { // no-op conversion + if _, ok := c.(RGBAColor); ok { // no-op conversion return c } - r, g, b, a := c.RGBA(); - return RGBAColor{uint8(r >> 24), uint8(g >> 24), uint8(b >> 24), uint8(a >> 24)}; + r, g, b, a := c.RGBA() + return RGBAColor{uint8(r >> 24), uint8(g >> 24), uint8(b >> 24), uint8(a >> 24)} } func toRGBA64Color(c Color) Color { - if _, ok := c.(RGBA64Color); ok { // no-op conversion + if _, ok := c.(RGBA64Color); ok { // no-op conversion return c } - r, g, b, a := c.RGBA(); - return RGBA64Color{uint16(r >> 16), uint16(g >> 16), uint16(b >> 16), uint16(a >> 16)}; + r, g, b, a := c.RGBA() + return RGBA64Color{uint16(r >> 16), uint16(g >> 16), uint16(b >> 16), uint16(a >> 16)} } func toNRGBAColor(c Color) Color { - if _, ok := c.(NRGBAColor); ok { // no-op conversion + if _, ok := c.(NRGBAColor); ok { // no-op conversion return c } - r, g, b, a := c.RGBA(); - a >>= 16; + r, g, b, a := c.RGBA() + a >>= 16 if a == 0xffff { return NRGBAColor{uint8(r >> 24), uint8(g >> 24), uint8(b >> 24), 0xff} } if a == 0 { return NRGBAColor{0, 0, 0, 0} } - r >>= 16; - g >>= 16; - b >>= 16; + r >>= 16 + g >>= 16 + b >>= 16 // Since Color.RGBA returns a alpha-premultiplied color, we should have r <= a && g <= a && b <= a. - r = (r * 0xffff) / a; - g = (g * 0xffff) / a; - b = (b * 0xffff) / a; - return NRGBAColor{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8)}; + r = (r * 0xffff) / a + g = (g * 0xffff) / a + b = (b * 0xffff) / a + return NRGBAColor{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8)} } func toNRGBA64Color(c Color) Color { - if _, ok := c.(NRGBA64Color); ok { // no-op conversion + if _, ok := c.(NRGBA64Color); ok { // no-op conversion return c } - r, g, b, a := c.RGBA(); - a >>= 16; - r >>= 16; - g >>= 16; - b >>= 16; + r, g, b, a := c.RGBA() + a >>= 16 + r >>= 16 + g >>= 16 + b >>= 16 if a == 0xffff { return NRGBA64Color{uint16(r), uint16(g), uint16(b), 0xffff} } @@ -170,10 +170,10 @@ func toNRGBA64Color(c Color) Color { return NRGBA64Color{0, 0, 0, 0} } // Since Color.RGBA returns a alpha-premultiplied color, we should have r <= a && g <= a && b <= a. - r = (r * 0xffff) / a; - g = (g * 0xffff) / a; - b = (b * 0xffff) / a; - return NRGBA64Color{uint16(r), uint16(g), uint16(b), uint16(a)}; + r = (r * 0xffff) / a + g = (g * 0xffff) / a + b = (b * 0xffff) / a + return NRGBA64Color{uint16(r), uint16(g), uint16(b), uint16(a)} } // The ColorModel associated with RGBAColor. diff --git a/src/pkg/image/image.go b/src/pkg/image/image.go index 9fc753b0f..b35094418 100644 --- a/src/pkg/image/image.go +++ b/src/pkg/image/image.go @@ -7,132 +7,132 @@ package image // An Image is a rectangular grid of Colors drawn from a ColorModel. type Image interface { - ColorModel() ColorModel; - Width() int; - Height() int; + ColorModel() ColorModel + Width() int + Height() int // At(0, 0) returns the upper-left pixel of the grid. // At(Width()-1, Height()-1) returns the lower-right pixel. - At(x, y int) Color; + At(x, y int) Color } // An RGBA is an in-memory image backed by a 2-D slice of RGBAColor values. type RGBA struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. - Pixel [][]RGBAColor; + Pixel [][]RGBAColor } -func (p *RGBA) ColorModel() ColorModel { return RGBAColorModel } +func (p *RGBA) ColorModel() ColorModel { return RGBAColorModel } func (p *RGBA) Width() int { if len(p.Pixel) == 0 { return 0 } - return len(p.Pixel[0]); + return len(p.Pixel[0]) } -func (p *RGBA) Height() int { return len(p.Pixel) } +func (p *RGBA) Height() int { return len(p.Pixel) } -func (p *RGBA) At(x, y int) Color { return p.Pixel[y][x] } +func (p *RGBA) At(x, y int) Color { return p.Pixel[y][x] } -func (p *RGBA) Set(x, y int, c Color) { p.Pixel[y][x] = toRGBAColor(c).(RGBAColor) } +func (p *RGBA) Set(x, y int, c Color) { p.Pixel[y][x] = toRGBAColor(c).(RGBAColor) } // NewRGBA returns a new RGBA with the given width and height. func NewRGBA(w, h int) *RGBA { - pixel := make([][]RGBAColor, h); + pixel := make([][]RGBAColor, h) for y := 0; y < h; y++ { pixel[y] = make([]RGBAColor, w) } - return &RGBA{pixel}; + return &RGBA{pixel} } // An RGBA64 is an in-memory image backed by a 2-D slice of RGBA64Color values. type RGBA64 struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. - Pixel [][]RGBA64Color; + Pixel [][]RGBA64Color } -func (p *RGBA64) ColorModel() ColorModel { return RGBA64ColorModel } +func (p *RGBA64) ColorModel() ColorModel { return RGBA64ColorModel } func (p *RGBA64) Width() int { if len(p.Pixel) == 0 { return 0 } - return len(p.Pixel[0]); + return len(p.Pixel[0]) } -func (p *RGBA64) Height() int { return len(p.Pixel) } +func (p *RGBA64) Height() int { return len(p.Pixel) } -func (p *RGBA64) At(x, y int) Color { return p.Pixel[y][x] } +func (p *RGBA64) At(x, y int) Color { return p.Pixel[y][x] } -func (p *RGBA64) Set(x, y int, c Color) { p.Pixel[y][x] = toRGBA64Color(c).(RGBA64Color) } +func (p *RGBA64) Set(x, y int, c Color) { p.Pixel[y][x] = toRGBA64Color(c).(RGBA64Color) } // NewRGBA64 returns a new RGBA64 with the given width and height. func NewRGBA64(w, h int) *RGBA64 { - pixel := make([][]RGBA64Color, h); + pixel := make([][]RGBA64Color, h) for y := 0; y < h; y++ { pixel[y] = make([]RGBA64Color, w) } - return &RGBA64{pixel}; + return &RGBA64{pixel} } // A NRGBA is an in-memory image backed by a 2-D slice of NRGBAColor values. type NRGBA struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. - Pixel [][]NRGBAColor; + Pixel [][]NRGBAColor } -func (p *NRGBA) ColorModel() ColorModel { return NRGBAColorModel } +func (p *NRGBA) ColorModel() ColorModel { return NRGBAColorModel } func (p *NRGBA) Width() int { if len(p.Pixel) == 0 { return 0 } - return len(p.Pixel[0]); + return len(p.Pixel[0]) } -func (p *NRGBA) Height() int { return len(p.Pixel) } +func (p *NRGBA) Height() int { return len(p.Pixel) } -func (p *NRGBA) At(x, y int) Color { return p.Pixel[y][x] } +func (p *NRGBA) At(x, y int) Color { return p.Pixel[y][x] } -func (p *NRGBA) Set(x, y int, c Color) { p.Pixel[y][x] = toNRGBAColor(c).(NRGBAColor) } +func (p *NRGBA) Set(x, y int, c Color) { p.Pixel[y][x] = toNRGBAColor(c).(NRGBAColor) } // NewNRGBA returns a new NRGBA with the given width and height. func NewNRGBA(w, h int) *NRGBA { - pixel := make([][]NRGBAColor, h); + pixel := make([][]NRGBAColor, h) for y := 0; y < h; y++ { pixel[y] = make([]NRGBAColor, w) } - return &NRGBA{pixel}; + return &NRGBA{pixel} } // A NRGBA64 is an in-memory image backed by a 2-D slice of NRGBA64Color values. type NRGBA64 struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. - Pixel [][]NRGBA64Color; + Pixel [][]NRGBA64Color } -func (p *NRGBA64) ColorModel() ColorModel { return NRGBA64ColorModel } +func (p *NRGBA64) ColorModel() ColorModel { return NRGBA64ColorModel } func (p *NRGBA64) Width() int { if len(p.Pixel) == 0 { return 0 } - return len(p.Pixel[0]); + return len(p.Pixel[0]) } -func (p *NRGBA64) Height() int { return len(p.Pixel) } +func (p *NRGBA64) Height() int { return len(p.Pixel) } -func (p *NRGBA64) At(x, y int) Color { return p.Pixel[y][x] } +func (p *NRGBA64) At(x, y int) Color { return p.Pixel[y][x] } -func (p *NRGBA64) Set(x, y int, c Color) { p.Pixel[y][x] = toNRGBA64Color(c).(NRGBA64Color) } +func (p *NRGBA64) Set(x, y int, c Color) { p.Pixel[y][x] = toNRGBA64Color(c).(NRGBA64Color) } // NewNRGBA64 returns a new NRGBA64 with the given width and height. func NewNRGBA64(w, h int) *NRGBA64 { - pixel := make([][]NRGBA64Color, h); + pixel := make([][]NRGBA64Color, h) for y := 0; y < h; y++ { pixel[y] = make([]NRGBA64Color, w) } - return &NRGBA64{pixel}; + return &NRGBA64{pixel} } // A PalettedColorModel represents a fixed palette of colors. @@ -142,7 +142,7 @@ func diff(a, b uint32) uint32 { if a > b { return a - b } - return b - a; + return b - a } // Convert returns the palette color closest to c in Euclidean R,G,B space. @@ -153,47 +153,47 @@ func (p PalettedColorModel) Convert(c Color) Color { // TODO(nigeltao): Revisit the "pick the palette color which minimizes sum-squared-difference" // algorithm when the premultiplied vs unpremultiplied issue is resolved. // Currently, we only compare the R, G and B values, and ignore A. - cr, cg, cb, _ := c.RGBA(); + cr, cg, cb, _ := c.RGBA() // Shift by 17 bits to avoid potential uint32 overflow in sum-squared-difference. - cr >>= 17; - cg >>= 17; - cb >>= 17; - result := Color(nil); - bestSSD := uint32(1<<32 - 1); + cr >>= 17 + cg >>= 17 + cb >>= 17 + result := Color(nil) + bestSSD := uint32(1<<32 - 1) for _, v := range p { - vr, vg, vb, _ := v.RGBA(); - vr >>= 17; - vg >>= 17; - vb >>= 17; - dr, dg, db := diff(cr, vr), diff(cg, vg), diff(cb, vb); - ssd := (dr * dr) + (dg * dg) + (db * db); + vr, vg, vb, _ := v.RGBA() + vr >>= 17 + vg >>= 17 + vb >>= 17 + dr, dg, db := diff(cr, vr), diff(cg, vg), diff(cb, vb) + ssd := (dr * dr) + (dg * dg) + (db * db) if ssd < bestSSD { - bestSSD = ssd; - result = v; + bestSSD = ssd + result = v } } - return result; + return result } // A Paletted is an in-memory image backed by a 2-D slice of uint8 values and a PalettedColorModel. type Paletted struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Palette[Pixel[y][x]]. - Pixel [][]uint8; - Palette PalettedColorModel; + Pixel [][]uint8 + Palette PalettedColorModel } -func (p *Paletted) ColorModel() ColorModel { return p.Palette } +func (p *Paletted) ColorModel() ColorModel { return p.Palette } func (p *Paletted) Width() int { if len(p.Pixel) == 0 { return 0 } - return len(p.Pixel[0]); + return len(p.Pixel[0]) } -func (p *Paletted) Height() int { return len(p.Pixel) } +func (p *Paletted) Height() int { return len(p.Pixel) } -func (p *Paletted) At(x, y int) Color { return p.Palette[p.Pixel[y][x]] } +func (p *Paletted) At(x, y int) Color { return p.Palette[p.Pixel[y][x]] } func (p *Paletted) ColorIndexAt(x, y int) uint8 { return p.Pixel[y][x] @@ -205,9 +205,9 @@ func (p *Paletted) SetColorIndex(x, y int, index uint8) { // NewPaletted returns a new Paletted with the given width, height and palette. func NewPaletted(w, h int, m PalettedColorModel) *Paletted { - pixel := make([][]uint8, h); + pixel := make([][]uint8, h) for y := 0; y < h; y++ { pixel[y] = make([]uint8, w) } - return &Paletted{pixel, m}; + return &Paletted{pixel, m} } diff --git a/src/pkg/image/png/reader.go b/src/pkg/image/png/reader.go index 96528af0d..9176524c9 100644 --- a/src/pkg/image/png/reader.go +++ b/src/pkg/image/png/reader.go @@ -8,31 +8,31 @@ package png import ( - "compress/zlib"; - "hash"; - "hash/crc32"; - "image"; - "io"; - "os"; + "compress/zlib" + "hash" + "hash/crc32" + "image" + "io" + "os" ) // Color type, as per the PNG spec. const ( - ctGrayscale = 0; - ctTrueColor = 2; - ctPaletted = 3; - ctGrayscaleAlpha = 4; - ctTrueColorAlpha = 6; + ctGrayscale = 0 + ctTrueColor = 2 + ctPaletted = 3 + ctGrayscaleAlpha = 4 + ctTrueColorAlpha = 6 ) // Filter type, as per the PNG spec. const ( - ftNone = 0; - ftSub = 1; - ftUp = 2; - ftAverage = 3; - ftPaeth = 4; - nFilter = 5; + ftNone = 0 + ftSub = 1 + ftUp = 2 + ftAverage = 3 + ftPaeth = 4 + nFilter = 5 ) // Decoding stage. @@ -41,43 +41,43 @@ const ( // IDAT chunks must be sequential (i.e. they may not have any other chunks // between them). const ( - dsStart = iota; - dsSeenIHDR; - dsSeenPLTE; - dsSeenIDAT; - dsSeenIEND; + dsStart = iota + dsSeenIHDR + dsSeenPLTE + dsSeenIDAT + dsSeenIEND ) const pngHeader = "\x89PNG\r\n\x1a\n" type decoder struct { - width, height int; - image image.Image; - colorType uint8; - stage int; - idatWriter io.WriteCloser; - idatDone chan os.Error; - tmp [3 * 256]byte; + width, height int + image image.Image + colorType uint8 + stage int + idatWriter io.WriteCloser + idatDone chan os.Error + tmp [3 * 256]byte } // A FormatError reports that the input is not a valid PNG. type FormatError string -func (e FormatError) String() string { return "invalid PNG format: " + string(e) } +func (e FormatError) String() string { return "invalid PNG format: " + string(e) } var chunkOrderError = FormatError("chunk out of order") // An IDATDecodingError wraps an inner error (such as a ZLIB decoding error) encountered while processing an IDAT chunk. type IDATDecodingError struct { - Err os.Error; + Err os.Error } -func (e IDATDecodingError) String() string { return "IDAT decoding error: " + e.Err.String() } +func (e IDATDecodingError) String() string { return "IDAT decoding error: " + e.Err.String() } // An UnsupportedError reports that the input uses a valid but unimplemented PNG feature. type UnsupportedError string -func (e UnsupportedError) String() string { return "unsupported PNG feature: " + string(e) } +func (e UnsupportedError) String() string { return "unsupported PNG feature: " + string(e) } // Big-endian. func parseUint32(b []uint8) uint32 { @@ -88,41 +88,41 @@ func abs(x int) int { if x < 0 { return -x } - return x; + return x } func min(a, b int) int { if a < b { return a } - return b; + return b } func (d *decoder) parseIHDR(r io.Reader, crc hash.Hash32, length uint32) os.Error { if length != 13 { return FormatError("bad IHDR length") } - _, err := io.ReadFull(r, d.tmp[0:13]); + _, err := io.ReadFull(r, d.tmp[0:13]) if err != nil { return err } - crc.Write(d.tmp[0:13]); + crc.Write(d.tmp[0:13]) if d.tmp[8] != 8 { return UnsupportedError("bit depth") } if d.tmp[10] != 0 || d.tmp[11] != 0 || d.tmp[12] != 0 { return UnsupportedError("compression, filter or interlace method") } - w := int32(parseUint32(d.tmp[0:4])); - h := int32(parseUint32(d.tmp[4:8])); + w := int32(parseUint32(d.tmp[0:4])) + h := int32(parseUint32(d.tmp[4:8])) if w < 0 || h < 0 { return FormatError("negative dimension") } - nPixels := int64(w) * int64(h); + nPixels := int64(w) * int64(h) if nPixels != int64(int(nPixels)) { return UnsupportedError("dimension overflow") } - d.colorType = d.tmp[9]; + d.colorType = d.tmp[9] switch d.colorType { case ctTrueColor: d.image = image.NewRGBA(int(w), int(h)) @@ -133,27 +133,27 @@ func (d *decoder) parseIHDR(r io.Reader, crc hash.Hash32, length uint32) os.Erro default: return UnsupportedError("color type") } - d.width, d.height = int(w), int(h); - return nil; + d.width, d.height = int(w), int(h) + return nil } func (d *decoder) parsePLTE(r io.Reader, crc hash.Hash32, length uint32) os.Error { - np := int(length / 3); // The number of palette entries. + np := int(length / 3) // The number of palette entries. if length%3 != 0 || np <= 0 || np > 256 { return FormatError("bad PLTE length") } - n, err := io.ReadFull(r, d.tmp[0:3*np]); + n, err := io.ReadFull(r, d.tmp[0:3*np]) if err != nil { return err } - crc.Write(d.tmp[0:n]); + crc.Write(d.tmp[0:n]) switch d.colorType { case ctPaletted: - palette := make([]image.Color, np); + palette := make([]image.Color, np) for i := 0; i < np; i++ { palette[i] = image.RGBAColor{d.tmp[3*i+0], d.tmp[3*i+1], d.tmp[3*i+2], 0xff} } - d.image.(*image.Paletted).Palette = image.PalettedColorModel(palette); + d.image.(*image.Paletted).Palette = image.PalettedColorModel(palette) case ctTrueColor, ctTrueColorAlpha: // As per the PNG spec, a PLTE chunk is optional (and for practical purposes, // ignorable) for the ctTrueColor and ctTrueColorAlpha color types (section 4.1.2). @@ -161,63 +161,63 @@ func (d *decoder) parsePLTE(r io.Reader, crc hash.Hash32, length uint32) os.Erro default: return FormatError("PLTE, color type mismatch") } - return nil; + return nil } // The Paeth filter function, as per the PNG specification. func paeth(a, b, c uint8) uint8 { - p := int(a) + int(b) - int(c); - pa := abs(p - int(a)); - pb := abs(p - int(b)); - pc := abs(p - int(c)); + p := int(a) + int(b) - int(c) + pa := abs(p - int(a)) + pb := abs(p - int(b)) + pc := abs(p - int(c)) if pa <= pb && pa <= pc { return a } else if pb <= pc { return b } - return c; + return c } func (d *decoder) idatReader(idat io.Reader) os.Error { - r, err := zlib.NewInflater(idat); + r, err := zlib.NewInflater(idat) if err != nil { return err } - defer r.Close(); - bpp := 0; // Bytes per pixel. - maxPalette := uint8(0); + defer r.Close() + bpp := 0 // Bytes per pixel. + maxPalette := uint8(0) var ( - rgba *image.RGBA; - nrgba *image.NRGBA; - paletted *image.Paletted; + rgba *image.RGBA + nrgba *image.NRGBA + paletted *image.Paletted ) switch d.colorType { case ctTrueColor: - bpp = 3; - rgba = d.image.(*image.RGBA); + bpp = 3 + rgba = d.image.(*image.RGBA) case ctPaletted: - bpp = 1; - paletted = d.image.(*image.Paletted); - maxPalette = uint8(len(paletted.Palette) - 1); + bpp = 1 + paletted = d.image.(*image.Paletted) + maxPalette = uint8(len(paletted.Palette) - 1) case ctTrueColorAlpha: - bpp = 4; - nrgba = d.image.(*image.NRGBA); + bpp = 4 + nrgba = d.image.(*image.NRGBA) } // cr and pr are the bytes for the current and previous row. // The +1 is for the per-row filter type, which is at cr[0]. - cr := make([]uint8, 1+bpp*d.width); - pr := make([]uint8, 1+bpp*d.width); + cr := make([]uint8, 1+bpp*d.width) + pr := make([]uint8, 1+bpp*d.width) for y := 0; y < d.height; y++ { // Read the decompressed bytes. - _, err := io.ReadFull(r, cr); + _, err := io.ReadFull(r, cr) if err != nil { return err } // Apply the filter. - cdat := cr[1:]; - pdat := pr[1:]; + cdat := cr[1:] + pdat := pr[1:] switch cr[0] { case ftNone: // No-op. @@ -258,7 +258,7 @@ func (d *decoder) idatReader(idat io.Reader) os.Error { if cdat[x] > maxPalette { return FormatError("palette index out of range") } - paletted.SetColorIndex(x, y, cdat[x]); + paletted.SetColorIndex(x, y, cdat[x]) } case ctTrueColorAlpha: for x := 0; x < d.width; x++ { @@ -267,9 +267,9 @@ func (d *decoder) idatReader(idat io.Reader) os.Error { } // The current row for y is the previous row for y+1. - pr, cr = cr, pr; + pr, cr = cr, pr } - return nil; + return nil } func (d *decoder) parseIDAT(r io.Reader, crc hash.Hash32, length uint32) os.Error { @@ -279,65 +279,65 @@ func (d *decoder) parseIDAT(r io.Reader, crc hash.Hash32, length uint32) os.Erro // we see them, and decode the stream in a separate go-routine, which // signals its completion (successful or not) via a channel. if d.idatWriter == nil { - pr, pw := io.Pipe(); - d.idatWriter = pw; - d.idatDone = make(chan os.Error); + pr, pw := io.Pipe() + d.idatWriter = pw + d.idatDone = make(chan os.Error) go func() { - err := d.idatReader(pr); + err := d.idatReader(pr) if err == os.EOF { err = FormatError("too little IDAT") } - pr.CloseWithError(FormatError("too much IDAT")); - d.idatDone <- err; - }(); + pr.CloseWithError(FormatError("too much IDAT")) + d.idatDone <- err + }() } - var buf [4096]byte; + var buf [4096]byte for length > 0 { - n, err1 := r.Read(buf[0:min(len(buf), int(length))]); + n, err1 := r.Read(buf[0:min(len(buf), int(length))]) // We delay checking err1. It is possible to get n bytes and an error, // but if the n bytes themselves contain a FormatError, for example, we // want to report that error, and not the one that made the Read stop. - n, err2 := d.idatWriter.Write(buf[0:n]); + n, err2 := d.idatWriter.Write(buf[0:n]) if err2 != nil { return err2 } if err1 != nil { return err1 } - crc.Write(buf[0:n]); - length -= uint32(n); + crc.Write(buf[0:n]) + length -= uint32(n) } - return nil; + return nil } func (d *decoder) parseIEND(r io.Reader, crc hash.Hash32, length uint32) os.Error { if length != 0 { return FormatError("bad IEND length") } - return nil; + return nil } func (d *decoder) parseChunk(r io.Reader) os.Error { // Read the length. - n, err := io.ReadFull(r, d.tmp[0:4]); + n, err := io.ReadFull(r, d.tmp[0:4]) if err == os.EOF { return io.ErrUnexpectedEOF } if err != nil { return err } - length := parseUint32(d.tmp[0:4]); + length := parseUint32(d.tmp[0:4]) // Read the chunk type. - n, err = io.ReadFull(r, d.tmp[0:4]); + n, err = io.ReadFull(r, d.tmp[0:4]) if err == os.EOF { return io.ErrUnexpectedEOF } if err != nil { return err } - crc := crc32.NewIEEE(); - crc.Write(d.tmp[0:4]); + crc := crc32.NewIEEE() + crc.Write(d.tmp[0:4]) // Read the chunk data. switch string(d.tmp[0:4]) { @@ -345,36 +345,36 @@ func (d *decoder) parseChunk(r io.Reader) os.Error { if d.stage != dsStart { return chunkOrderError } - d.stage = dsSeenIHDR; - err = d.parseIHDR(r, crc, length); + d.stage = dsSeenIHDR + err = d.parseIHDR(r, crc, length) case "PLTE": if d.stage != dsSeenIHDR { return chunkOrderError } - d.stage = dsSeenPLTE; - err = d.parsePLTE(r, crc, length); + d.stage = dsSeenPLTE + err = d.parsePLTE(r, crc, length) case "IDAT": if d.stage < dsSeenIHDR || d.stage > dsSeenIDAT || (d.colorType == ctPaletted && d.stage == dsSeenIHDR) { return chunkOrderError } - d.stage = dsSeenIDAT; - err = d.parseIDAT(r, crc, length); + d.stage = dsSeenIDAT + err = d.parseIDAT(r, crc, length) case "IEND": if d.stage != dsSeenIDAT { return chunkOrderError } - d.stage = dsSeenIEND; - err = d.parseIEND(r, crc, length); + d.stage = dsSeenIEND + err = d.parseIEND(r, crc, length) default: // Ignore this chunk (of a known length). - var ignored [4096]byte; + var ignored [4096]byte for length > 0 { - n, err = io.ReadFull(r, ignored[0:min(len(ignored), int(length))]); + n, err = io.ReadFull(r, ignored[0:min(len(ignored), int(length))]) if err != nil { return err } - crc.Write(ignored[0:n]); - length -= uint32(n); + crc.Write(ignored[0:n]) + length -= uint32(n) } } if err != nil { @@ -382,7 +382,7 @@ func (d *decoder) parseChunk(r io.Reader) os.Error { } // Read the checksum. - n, err = io.ReadFull(r, d.tmp[0:4]); + n, err = io.ReadFull(r, d.tmp[0:4]) if err == os.EOF { return io.ErrUnexpectedEOF } @@ -392,37 +392,37 @@ func (d *decoder) parseChunk(r io.Reader) os.Error { if parseUint32(d.tmp[0:4]) != crc.Sum32() { return FormatError("invalid checksum") } - return nil; + return nil } func (d *decoder) checkHeader(r io.Reader) os.Error { - _, err := io.ReadFull(r, d.tmp[0:8]); + _, err := io.ReadFull(r, d.tmp[0:8]) if err != nil { return err } if string(d.tmp[0:8]) != pngHeader { return FormatError("not a PNG file") } - return nil; + return nil } // Decode reads a PNG formatted image from r and returns it as an image.Image. // The type of Image returned depends on the PNG contents. func Decode(r io.Reader) (image.Image, os.Error) { - var d decoder; - err := d.checkHeader(r); + var d decoder + err := d.checkHeader(r) if err != nil { return nil, err } for d.stage = dsStart; d.stage != dsSeenIEND; { - err = d.parseChunk(r); + err = d.parseChunk(r) if err != nil { break } } if d.idatWriter != nil { - d.idatWriter.Close(); - err1 := <-d.idatDone; + d.idatWriter.Close() + err1 := <-d.idatDone if err == nil { err = err1 } @@ -430,5 +430,5 @@ func Decode(r io.Reader) (image.Image, os.Error) { if err != nil { return nil, err } - return d.image, nil; + return d.image, nil } diff --git a/src/pkg/image/png/reader_test.go b/src/pkg/image/png/reader_test.go index 2885b3344..68aab7832 100644 --- a/src/pkg/image/png/reader_test.go +++ b/src/pkg/image/png/reader_test.go @@ -5,12 +5,12 @@ package png import ( - "bufio"; - "fmt"; - "image"; - "io"; - "os"; - "testing"; + "bufio" + "fmt" + "image" + "io" + "os" + "testing" ) // The go PNG library currently supports only a subset of the full PNG specification. @@ -34,124 +34,124 @@ var filenames = []string{ } func readPng(filename string) (image.Image, os.Error) { - f, err := os.Open(filename, os.O_RDONLY, 0444); + f, err := os.Open(filename, os.O_RDONLY, 0444) if err != nil { return nil, err } - defer f.Close(); - return Decode(f); + defer f.Close() + return Decode(f) } // An approximation of the sng command-line tool. func sng(w io.WriteCloser, filename string, png image.Image) { - defer w.Close(); + defer w.Close() // For now, the go PNG parser only reads bitdepths of 8. - bitdepth := 8; + bitdepth := 8 // Write the filename and IHDR. - io.WriteString(w, "#SNG: from "+filename+".png\nIHDR {\n"); - fmt.Fprintf(w, " width: %d; height: %d; bitdepth: %d;\n", png.Width(), png.Height(), bitdepth); - cm := png.ColorModel(); - var paletted *image.Paletted; - cpm, _ := cm.(image.PalettedColorModel); + io.WriteString(w, "#SNG: from "+filename+".png\nIHDR {\n") + fmt.Fprintf(w, " width: %d; height: %d; bitdepth: %d;\n", png.Width(), png.Height(), bitdepth) + cm := png.ColorModel() + var paletted *image.Paletted + cpm, _ := cm.(image.PalettedColorModel) switch { case cm == image.RGBAColorModel: io.WriteString(w, " using color;\n") case cm == image.NRGBAColorModel: io.WriteString(w, " using color alpha;\n") case cpm != nil: - io.WriteString(w, " using color palette;\n"); - paletted = png.(*image.Paletted); + io.WriteString(w, " using color palette;\n") + paletted = png.(*image.Paletted) default: io.WriteString(w, "unknown PNG decoder color model\n") } - io.WriteString(w, "}\n"); + io.WriteString(w, "}\n") // We fake a gAMA output. The test files have a gAMA chunk but the go PNG parser ignores it // (the PNG spec section 11.3 says "Ancillary chunks may be ignored by a decoder"). - io.WriteString(w, "gAMA {1.0000}\n"); + io.WriteString(w, "gAMA {1.0000}\n") // Write the PLTE (if applicable). if cpm != nil { - io.WriteString(w, "PLTE {\n"); + io.WriteString(w, "PLTE {\n") for i := 0; i < len(cpm); i++ { - r, g, b, _ := cpm[i].RGBA(); - r >>= 24; - g >>= 24; - b >>= 24; - fmt.Fprintf(w, " (%3d,%3d,%3d) # rgb = (0x%02x,0x%02x,0x%02x)\n", r, g, b, r, g, b); + r, g, b, _ := cpm[i].RGBA() + r >>= 24 + g >>= 24 + b >>= 24 + fmt.Fprintf(w, " (%3d,%3d,%3d) # rgb = (0x%02x,0x%02x,0x%02x)\n", r, g, b, r, g, b) } - io.WriteString(w, "}\n"); + io.WriteString(w, "}\n") } // Write the IMAGE. - io.WriteString(w, "IMAGE {\n pixels hex\n"); + io.WriteString(w, "IMAGE {\n pixels hex\n") for y := 0; y < png.Height(); y++ { switch { case cm == image.RGBAColorModel: for x := 0; x < png.Width(); x++ { - rgba := png.At(x, y).(image.RGBAColor); - fmt.Fprintf(w, "%02x%02x%02x ", rgba.R, rgba.G, rgba.B); + rgba := png.At(x, y).(image.RGBAColor) + fmt.Fprintf(w, "%02x%02x%02x ", rgba.R, rgba.G, rgba.B) } case cm == image.NRGBAColorModel: for x := 0; x < png.Width(); x++ { - nrgba := png.At(x, y).(image.NRGBAColor); - fmt.Fprintf(w, "%02x%02x%02x%02x ", nrgba.R, nrgba.G, nrgba.B, nrgba.A); + nrgba := png.At(x, y).(image.NRGBAColor) + fmt.Fprintf(w, "%02x%02x%02x%02x ", nrgba.R, nrgba.G, nrgba.B, nrgba.A) } case cpm != nil: for x := 0; x < png.Width(); x++ { fmt.Fprintf(w, "%02x", paletted.ColorIndexAt(x, y)) } } - io.WriteString(w, "\n"); + io.WriteString(w, "\n") } - io.WriteString(w, "}\n"); + io.WriteString(w, "}\n") } func TestReader(t *testing.T) { for _, fn := range filenames { // Read the .png file. - image, err := readPng("testdata/pngsuite/" + fn + ".png"); + image, err := readPng("testdata/pngsuite/" + fn + ".png") if err != nil { - t.Error(fn, err); - continue; + t.Error(fn, err) + continue } - piper, pipew := io.Pipe(); - pb := bufio.NewReader(piper); - go sng(pipew, fn, image); - defer piper.Close(); + piper, pipew := io.Pipe() + pb := bufio.NewReader(piper) + go sng(pipew, fn, image) + defer piper.Close() // Read the .sng file. - sf, err := os.Open("testdata/pngsuite/"+fn+".sng", os.O_RDONLY, 0444); + sf, err := os.Open("testdata/pngsuite/"+fn+".sng", os.O_RDONLY, 0444) if err != nil { - t.Error(fn, err); - continue; + t.Error(fn, err) + continue } - defer sf.Close(); - sb := bufio.NewReader(sf); + defer sf.Close() + sb := bufio.NewReader(sf) if err != nil { - t.Error(fn, err); - continue; + t.Error(fn, err) + continue } // Compare the two, in SNG format, line by line. for { - ps, perr := pb.ReadString('\n'); - ss, serr := sb.ReadString('\n'); + ps, perr := pb.ReadString('\n') + ss, serr := sb.ReadString('\n') if perr == os.EOF && serr == os.EOF { break } if perr != nil { - t.Error(fn, perr); - break; + t.Error(fn, perr) + break } if serr != nil { - t.Error(fn, serr); - break; + t.Error(fn, serr) + break } if ps != ss { - t.Errorf("%s: Mismatch\n%sversus\n%s\n", fn, ps, ss); - break; + t.Errorf("%s: Mismatch\n%sversus\n%s\n", fn, ps, ss) + break } } } diff --git a/src/pkg/image/png/writer.go b/src/pkg/image/png/writer.go index 9ec2544d0..b0550b0f1 100644 --- a/src/pkg/image/png/writer.go +++ b/src/pkg/image/png/writer.go @@ -5,44 +5,44 @@ package png import ( - "bufio"; - "compress/zlib"; - "hash/crc32"; - "image"; - "io"; - "os"; - "strconv"; + "bufio" + "compress/zlib" + "hash/crc32" + "image" + "io" + "os" + "strconv" ) type encoder struct { - w io.Writer; - m image.Image; - colorType uint8; - err os.Error; - header [8]byte; - footer [4]byte; - tmp [3 * 256]byte; + w io.Writer + m image.Image + colorType uint8 + err os.Error + header [8]byte + footer [4]byte + tmp [3 * 256]byte } // Big-endian. func writeUint32(b []uint8, u uint32) { - b[0] = uint8(u >> 24); - b[1] = uint8(u >> 16); - b[2] = uint8(u >> 8); - b[3] = uint8(u >> 0); + b[0] = uint8(u >> 24) + b[1] = uint8(u >> 16) + b[2] = uint8(u >> 8) + b[3] = uint8(u >> 0) } // Returns whether or not the image is fully opaque. func opaque(m image.Image) bool { for y := 0; y < m.Height(); y++ { for x := 0; x < m.Width(); x++ { - _, _, _, a := m.At(x, y).RGBA(); + _, _, _, a := m.At(x, y).RGBA() if a != 0xffffffff { return false } } } - return true; + return true } // The absolute value of a byte interpreted as a signed int8. @@ -50,66 +50,66 @@ func abs8(d uint8) int { if d < 128 { return int(d) } - return 256 - int(d); + return 256 - int(d) } func (e *encoder) writeChunk(b []byte, name string) { if e.err != nil { return } - n := uint32(len(b)); + n := uint32(len(b)) if int(n) != len(b) { - e.err = UnsupportedError(name + " chunk is too large: " + strconv.Itoa(len(b))); - return; + e.err = UnsupportedError(name + " chunk is too large: " + strconv.Itoa(len(b))) + return } - writeUint32(e.header[0:4], n); - e.header[4] = name[0]; - e.header[5] = name[1]; - e.header[6] = name[2]; - e.header[7] = name[3]; - crc := crc32.NewIEEE(); - crc.Write(e.header[4:8]); - crc.Write(b); - writeUint32(e.footer[0:4], crc.Sum32()); + writeUint32(e.header[0:4], n) + e.header[4] = name[0] + e.header[5] = name[1] + e.header[6] = name[2] + e.header[7] = name[3] + crc := crc32.NewIEEE() + crc.Write(e.header[4:8]) + crc.Write(b) + writeUint32(e.footer[0:4], crc.Sum32()) - _, e.err = e.w.Write(e.header[0:8]); + _, e.err = e.w.Write(e.header[0:8]) if e.err != nil { return } - _, e.err = e.w.Write(b); + _, e.err = e.w.Write(b) if e.err != nil { return } - _, e.err = e.w.Write(e.footer[0:4]); + _, e.err = e.w.Write(e.footer[0:4]) } func (e *encoder) writeIHDR() { - writeUint32(e.tmp[0:4], uint32(e.m.Width())); - writeUint32(e.tmp[4:8], uint32(e.m.Height())); - e.tmp[8] = 8; // bit depth - e.tmp[9] = e.colorType; - e.tmp[10] = 0; // default compression method - e.tmp[11] = 0; // default filter method - e.tmp[12] = 0; // non-interlaced - e.writeChunk(e.tmp[0:13], "IHDR"); + writeUint32(e.tmp[0:4], uint32(e.m.Width())) + writeUint32(e.tmp[4:8], uint32(e.m.Height())) + e.tmp[8] = 8 // bit depth + e.tmp[9] = e.colorType + e.tmp[10] = 0 // default compression method + e.tmp[11] = 0 // default filter method + e.tmp[12] = 0 // non-interlaced + e.writeChunk(e.tmp[0:13], "IHDR") } func (e *encoder) writePLTE(p image.PalettedColorModel) { if len(p) < 1 || len(p) > 256 { - e.err = FormatError("bad palette length: " + strconv.Itoa(len(p))); - return; + e.err = FormatError("bad palette length: " + strconv.Itoa(len(p))) + return } for i := 0; i < len(p); i++ { - r, g, b, a := p[i].RGBA(); + r, g, b, a := p[i].RGBA() if a != 0xffffffff { - e.err = UnsupportedError("non-opaque palette color"); - return; + e.err = UnsupportedError("non-opaque palette color") + return } - e.tmp[3*i+0] = uint8(r >> 24); - e.tmp[3*i+1] = uint8(g >> 24); - e.tmp[3*i+2] = uint8(b >> 24); + e.tmp[3*i+0] = uint8(r >> 24) + e.tmp[3*i+1] = uint8(g >> 24) + e.tmp[3*i+2] = uint8(b >> 24) } - e.writeChunk(e.tmp[0:3*len(p)], "PLTE"); + e.writeChunk(e.tmp[0:3*len(p)], "PLTE") } // An encoder is an io.Writer that satisfies writes by writing PNG IDAT chunks, @@ -123,11 +123,11 @@ func (e *encoder) writePLTE(p image.PalettedColorModel) { // occur on a separate go-routine than the e.writeIDATs call, and care should be // taken that e's state (such as its tmp buffer) is not modified concurrently. func (e *encoder) Write(b []byte) (int, os.Error) { - e.writeChunk(b, "IDAT"); + e.writeChunk(b, "IDAT") if e.err != nil { return 0, e.err } - return len(b), nil; + return len(b), nil } // Chooses the filter to use for encoding the current row, and applies it. @@ -137,108 +137,108 @@ func filter(cr [][]byte, pr []byte, bpp int) int { // This is the same heuristic that libpng uses, although the filters are attempted in order of // estimated most likely to be minimal (ftUp, ftPaeth, ftNone, ftSub, ftAverage), rather than // in their enumeration order (ftNone, ftSub, ftUp, ftAverage, ftPaeth). - cdat0 := cr[0][1:]; - cdat1 := cr[1][1:]; - cdat2 := cr[2][1:]; - cdat3 := cr[3][1:]; - cdat4 := cr[4][1:]; - pdat := pr[1:]; - n := len(cdat0); + cdat0 := cr[0][1:] + cdat1 := cr[1][1:] + cdat2 := cr[2][1:] + cdat3 := cr[3][1:] + cdat4 := cr[4][1:] + pdat := pr[1:] + n := len(cdat0) // The up filter. - sum := 0; + sum := 0 for i := 0; i < n; i++ { - cdat2[i] = cdat0[i] - pdat[i]; - sum += abs8(cdat2[i]); + cdat2[i] = cdat0[i] - pdat[i] + sum += abs8(cdat2[i]) } - best := sum; - filter := ftUp; + best := sum + filter := ftUp // The Paeth filter. - sum = 0; + sum = 0 for i := 0; i < bpp; i++ { - cdat4[i] = cdat0[i] - paeth(0, pdat[i], 0); - sum += abs8(cdat4[i]); + cdat4[i] = cdat0[i] - paeth(0, pdat[i], 0) + sum += abs8(cdat4[i]) } for i := bpp; i < n; i++ { - cdat4[i] = cdat0[i] - paeth(cdat0[i-bpp], pdat[i], pdat[i-bpp]); - sum += abs8(cdat4[i]); + cdat4[i] = cdat0[i] - paeth(cdat0[i-bpp], pdat[i], pdat[i-bpp]) + sum += abs8(cdat4[i]) if sum >= best { break } } if sum < best { - best = sum; - filter = ftPaeth; + best = sum + filter = ftPaeth } // The none filter. - sum = 0; + sum = 0 for i := 0; i < n; i++ { - sum += abs8(cdat0[i]); + sum += abs8(cdat0[i]) if sum >= best { break } } if sum < best { - best = sum; - filter = ftNone; + best = sum + filter = ftNone } // The sub filter. - sum = 0; + sum = 0 for i := 0; i < bpp; i++ { - cdat1[i] = cdat0[i]; - sum += abs8(cdat1[i]); + cdat1[i] = cdat0[i] + sum += abs8(cdat1[i]) } for i := bpp; i < n; i++ { - cdat1[i] = cdat0[i] - cdat0[i-bpp]; - sum += abs8(cdat1[i]); + cdat1[i] = cdat0[i] - cdat0[i-bpp] + sum += abs8(cdat1[i]) if sum >= best { break } } if sum < best { - best = sum; - filter = ftSub; + best = sum + filter = ftSub } // The average filter. - sum = 0; + sum = 0 for i := 0; i < bpp; i++ { - cdat3[i] = cdat0[i] - pdat[i]/2; - sum += abs8(cdat3[i]); + cdat3[i] = cdat0[i] - pdat[i]/2 + sum += abs8(cdat3[i]) } for i := bpp; i < n; i++ { - cdat3[i] = cdat0[i] - uint8((int(cdat0[i-bpp])+int(pdat[i]))/2); - sum += abs8(cdat3[i]); + cdat3[i] = cdat0[i] - uint8((int(cdat0[i-bpp])+int(pdat[i]))/2) + sum += abs8(cdat3[i]) if sum >= best { break } } if sum < best { - best = sum; - filter = ftAverage; + best = sum + filter = ftAverage } - return filter; + return filter } func writeImage(w io.Writer, m image.Image, ct uint8) os.Error { - zw, err := zlib.NewDeflater(w); + zw, err := zlib.NewDeflater(w) if err != nil { return err } - defer zw.Close(); + defer zw.Close() - bpp := 0; // Bytes per pixel. - var paletted *image.Paletted; + bpp := 0 // Bytes per pixel. + var paletted *image.Paletted switch ct { case ctTrueColor: bpp = 3 case ctPaletted: - bpp = 1; - paletted = m.(*image.Paletted); + bpp = 1 + paletted = m.(*image.Paletted) case ctTrueColorAlpha: bpp = 4 } @@ -247,12 +247,12 @@ func writeImage(w io.Writer, m image.Image, ct uint8) os.Error { // cr[ft], for non-zero filter types ft, are buffers for transforming cr[0] under the // other PNG filter types. These buffers are allocated once and re-used for each row. // The +1 is for the per-row filter type, which is at cr[*][0]. - var cr [nFilter][]uint8; + var cr [nFilter][]uint8 for i := 0; i < len(cr); i++ { - cr[i] = make([]uint8, 1+bpp*m.Width()); - cr[i][0] = uint8(i); + cr[i] = make([]uint8, 1+bpp*m.Width()) + cr[i][0] = uint8(i) } - pr := make([]uint8, 1+bpp*m.Width()); + pr := make([]uint8, 1+bpp*m.Width()) for y := 0; y < m.Height(); y++ { // Convert from colors to bytes. @@ -260,10 +260,10 @@ func writeImage(w io.Writer, m image.Image, ct uint8) os.Error { case ctTrueColor: for x := 0; x < m.Width(); x++ { // We have previously verified that the alpha value is fully opaque. - r, g, b, _ := m.At(x, y).RGBA(); - cr[0][3*x+1] = uint8(r >> 24); - cr[0][3*x+2] = uint8(g >> 24); - cr[0][3*x+3] = uint8(b >> 24); + r, g, b, _ := m.At(x, y).RGBA() + cr[0][3*x+1] = uint8(r >> 24) + cr[0][3*x+2] = uint8(g >> 24) + cr[0][3*x+3] = uint8(b >> 24) } case ctPaletted: for x := 0; x < m.Width(); x++ { @@ -272,27 +272,27 @@ func writeImage(w io.Writer, m image.Image, ct uint8) os.Error { case ctTrueColorAlpha: // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied. for x := 0; x < m.Width(); x++ { - c := image.NRGBAColorModel.Convert(m.At(x, y)).(image.NRGBAColor); - cr[0][4*x+1] = c.R; - cr[0][4*x+2] = c.G; - cr[0][4*x+3] = c.B; - cr[0][4*x+4] = c.A; + c := image.NRGBAColorModel.Convert(m.At(x, y)).(image.NRGBAColor) + cr[0][4*x+1] = c.R + cr[0][4*x+2] = c.G + cr[0][4*x+3] = c.B + cr[0][4*x+4] = c.A } } // Apply the filter. - f := filter(cr[0:nFilter], pr, bpp); + f := filter(cr[0:nFilter], pr, bpp) // Write the compressed bytes. - _, err = zw.Write(cr[f]); + _, err = zw.Write(cr[f]) if err != nil { return err } // The current row for y is the previous row for y+1. - pr, cr[0] = cr[0], pr; + pr, cr[0] = cr[0], pr } - return nil; + return nil } // Write the actual image data to one or more IDAT chunks. @@ -300,19 +300,19 @@ func (e *encoder) writeIDATs() { if e.err != nil { return } - var bw *bufio.Writer; - bw, e.err = bufio.NewWriterSize(e, 1<<15); + var bw *bufio.Writer + bw, e.err = bufio.NewWriterSize(e, 1<<15) if e.err != nil { return } - e.err = writeImage(bw, e.m, e.colorType); + e.err = writeImage(bw, e.m, e.colorType) if e.err != nil { return } - e.err = bw.Flush(); + e.err = bw.Flush() } -func (e *encoder) writeIEND() { e.writeChunk(e.tmp[0:0], "IEND") } +func (e *encoder) writeIEND() { e.writeChunk(e.tmp[0:0], "IEND") } // Encode writes the Image m to w in PNG format. Any Image may be encoded, but // images that are not image.NRGBA might be encoded lossily. @@ -320,28 +320,28 @@ func Encode(w io.Writer, m image.Image) os.Error { // Obviously, negative widths and heights are invalid. Furthermore, the PNG // spec section 11.2.2 says that zero is invalid. Excessively large images are // also rejected. - mw, mh := int64(m.Width()), int64(m.Height()); + mw, mh := int64(m.Width()), int64(m.Height()) if mw <= 0 || mh <= 0 || mw >= 1<<32 || mh >= 1<<32 { return FormatError("invalid image size: " + strconv.Itoa64(mw) + "x" + strconv.Itoa64(mw)) } - var e encoder; - e.w = w; - e.m = m; - e.colorType = uint8(ctTrueColorAlpha); - pal, _ := m.(*image.Paletted); + var e encoder + e.w = w + e.m = m + e.colorType = uint8(ctTrueColorAlpha) + pal, _ := m.(*image.Paletted) if pal != nil { e.colorType = ctPaletted } else if opaque(m) { e.colorType = ctTrueColor } - _, e.err = io.WriteString(w, pngHeader); - e.writeIHDR(); + _, e.err = io.WriteString(w, pngHeader) + e.writeIHDR() if pal != nil { e.writePLTE(pal.Palette) } - e.writeIDATs(); - e.writeIEND(); - return e.err; + e.writeIDATs() + e.writeIEND() + return e.err } diff --git a/src/pkg/image/png/writer_test.go b/src/pkg/image/png/writer_test.go index db50a9872..a61e1c95a 100644 --- a/src/pkg/image/png/writer_test.go +++ b/src/pkg/image/png/writer_test.go @@ -5,11 +5,11 @@ package png import ( - "fmt"; - "image"; - "io"; - "os"; - "testing"; + "fmt" + "image" + "io" + "os" + "testing" ) func diff(m0, m1 image.Image) os.Error { @@ -18,52 +18,52 @@ func diff(m0, m1 image.Image) os.Error { } for y := 0; y < m0.Height(); y++ { for x := 0; x < m0.Width(); x++ { - r0, g0, b0, a0 := m0.At(x, y).RGBA(); - r1, g1, b1, a1 := m1.At(x, y).RGBA(); + r0, g0, b0, a0 := m0.At(x, y).RGBA() + r1, g1, b1, a1 := m1.At(x, y).RGBA() if r0 != r1 || g0 != g1 || b0 != b1 || a0 != a1 { return os.NewError(fmt.Sprintf("colors differ at (%d, %d): %v vs %v", x, y, m0.At(x, y), m1.At(x, y))) } } } - return nil; + return nil } func TestWriter(t *testing.T) { // The filenames variable is declared in reader_test.go. for _, fn := range filenames { - qfn := "testdata/pngsuite/" + fn + ".png"; + qfn := "testdata/pngsuite/" + fn + ".png" // Read the image. - m0, err := readPng(qfn); + m0, err := readPng(qfn) if err != nil { - t.Error(fn, err); - continue; + t.Error(fn, err) + continue } // Read the image again, and push it through a pipe that encodes at the write end, and decodes at the read end. - pr, pw := io.Pipe(); - defer pr.Close(); + pr, pw := io.Pipe() + defer pr.Close() go func() { - defer pw.Close(); - m1, err := readPng(qfn); + defer pw.Close() + m1, err := readPng(qfn) if err != nil { - t.Error(fn, err); - return; + t.Error(fn, err) + return } - err = Encode(pw, m1); + err = Encode(pw, m1) if err != nil { - t.Error(fn, err); - return; + t.Error(fn, err) + return } - }(); - m2, err := Decode(pr); + }() + m2, err := Decode(pr) if err != nil { - t.Error(fn, err); - continue; + t.Error(fn, err) + continue } // Compare the two. - err = diff(m0, m2); + err = diff(m0, m2) if err != nil { - t.Error(fn, err); - continue; + t.Error(fn, err) + continue } } } diff --git a/src/pkg/io/io.go b/src/pkg/io/io.go index 68c5ccc24..5d18476f5 100644 --- a/src/pkg/io/io.go +++ b/src/pkg/io/io.go @@ -9,13 +9,13 @@ package io import ( - "os"; - "strings"; + "os" + "strings" ) // Error represents an unexpected I/O behavior. type Error struct { - os.ErrorString; + os.ErrorString } // ErrShortWrite means that a write accepted fewer bytes than requested @@ -39,7 +39,7 @@ var ErrUnexpectedEOF os.Error = &Error{"unexpected EOF"} // Read may return a non-zero number of bytes with a non-nil err. // In particular, a Read that exhausts the input may return n > 0, os.EOF. type Reader interface { - Read(p []byte) (n int, err os.Error); + Read(p []byte) (n int, err os.Error) } // Writer is the interface that wraps the basic Write method. @@ -49,12 +49,12 @@ type Reader interface { // and any error encountered that caused the write to stop early. // Write must return a non-nil error if it returns n < len(p). type Writer interface { - Write(p []byte) (n int, err os.Error); + Write(p []byte) (n int, err os.Error) } // Closer is the interface that wraps the basic Close method. type Closer interface { - Close() os.Error; + Close() os.Error } // Seeker is the interface that wraps the basic Seek method. @@ -65,61 +65,61 @@ type Closer interface { // relative to the end. Seek returns the new offset and an Error, if // any. type Seeker interface { - Seek(offset int64, whence int) (ret int64, err os.Error); + Seek(offset int64, whence int) (ret int64, err os.Error) } // ReadWriter is the interface that groups the basic Read and Write methods. type ReadWriter interface { - Reader; - Writer; + Reader + Writer } // ReadCloser is the interface that groups the basic Read and Close methods. type ReadCloser interface { - Reader; - Closer; + Reader + Closer } // WriteCloser is the interface that groups the basic Write and Close methods. type WriteCloser interface { - Writer; - Closer; + Writer + Closer } // ReadWriteCloser is the interface that groups the basic Read, Write and Close methods. type ReadWriteCloser interface { - Reader; - Writer; - Closer; + Reader + Writer + Closer } // ReadSeeker is the interface that groups the basic Read and Seek methods. type ReadSeeker interface { - Reader; - Seeker; + Reader + Seeker } // WriteSeeker is the interface that groups the basic Write and Seek methods. type WriteSeeker interface { - Writer; - Seeker; + Writer + Seeker } // ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods. type ReadWriteSeeker interface { - Reader; - Writer; - Seeker; + Reader + Writer + Seeker } // ReaderFrom is the interface that wraps the ReadFrom method. type ReaderFrom interface { - ReadFrom(r Reader) (n int64, err os.Error); + ReadFrom(r Reader) (n int64, err os.Error) } // WriterTo is the interface that wraps the WriteTo method. type WriterTo interface { - WriteTo(w Writer) (n int64, err os.Error); + WriteTo(w Writer) (n int64, err os.Error) } // ReaderAt is the interface that wraps the basic ReadAt method. @@ -137,7 +137,7 @@ type WriterTo interface { // ReadAt may return a non-zero number of bytes with a non-nil err. // In particular, a ReadAt that exhausts the input may return n > 0, os.EOF. type ReaderAt interface { - ReadAt(p []byte, off int64) (n int, err os.Error); + ReadAt(p []byte, off int64) (n int, err os.Error) } // WriterAt is the interface that wraps the basic WriteAt method. @@ -147,7 +147,7 @@ type ReaderAt interface { // and any error encountered that caused the write to stop early. // WriteAt must return a non-nil error if it returns n < len(p). type WriterAt interface { - WriteAt(p []byte, off int64) (n int, err os.Error); + WriteAt(p []byte, off int64) (n int, err os.Error) } // WriteString writes the contents of the string s to w, which accepts an array of bytes. @@ -161,9 +161,9 @@ func WriteString(w Writer, s string) (n int, err os.Error) { // If an EOF happens after reading fewer than min bytes, // ReadAtLeast returns ErrUnexpectedEOF. func ReadAtLeast(r Reader, buf []byte, min int) (n int, err os.Error) { - n = 0; + n = 0 for n < min { - nn, e := r.Read(buf[n:]); + nn, e := r.Read(buf[n:]) if nn > 0 { n += nn } @@ -171,10 +171,10 @@ func ReadAtLeast(r Reader, buf []byte, min int) (n int, err os.Error) { if e == os.EOF && n > 0 { e = ErrUnexpectedEOF } - return n, e; + return n, e } } - return n, nil; + return n, nil } // ReadFull reads exactly len(buf) bytes from r into buf. @@ -197,33 +197,33 @@ func Copyn(dst Writer, src Reader, n int64) (written int64, err os.Error) { if rt, ok := dst.(ReaderFrom); ok { return rt.ReadFrom(LimitReader(src, n)) } - buf := make([]byte, 32*1024); + buf := make([]byte, 32*1024) for written < n { - l := len(buf); + l := len(buf) if d := n - written; d < int64(l) { l = int(d) } - nr, er := src.Read(buf[0:l]); + nr, er := src.Read(buf[0:l]) if nr > 0 { - nw, ew := dst.Write(buf[0:nr]); + nw, ew := dst.Write(buf[0:nr]) if nw > 0 { written += int64(nw) } if ew != nil { - err = ew; - break; + err = ew + break } if nr != nw { - err = ErrShortWrite; - break; + err = ErrShortWrite + break } } if er != nil { - err = er; - break; + err = er + break } } - return written, err; + return written, err } // Copy copies from src to dst until either EOF is reached @@ -244,41 +244,41 @@ func Copy(dst Writer, src Reader) (written int64, err os.Error) { if wt, ok := src.(WriterTo); ok { return wt.WriteTo(dst) } - buf := make([]byte, 32*1024); + buf := make([]byte, 32*1024) for { - nr, er := src.Read(buf); + nr, er := src.Read(buf) if nr > 0 { - nw, ew := dst.Write(buf[0:nr]); + nw, ew := dst.Write(buf[0:nr]) if nw > 0 { written += int64(nw) } if ew != nil { - err = ew; - break; + err = ew + break } if nr != nw { - err = ErrShortWrite; - break; + err = ErrShortWrite + break } } if er == os.EOF { break } if er != nil { - err = er; - break; + err = er + break } } - return written, err; + return written, err } // LimitReader returns a Reader that reads from r // but stops with os.EOF after n bytes. -func LimitReader(r Reader, n int64) Reader { return &limitedReader{r, n} } +func LimitReader(r Reader, n int64) Reader { return &limitedReader{r, n} } type limitedReader struct { - r Reader; - n int64; + r Reader + n int64 } func (l *limitedReader) Read(p []byte) (n int, err os.Error) { @@ -288,9 +288,9 @@ func (l *limitedReader) Read(p []byte) (n int, err os.Error) { if int64(len(p)) > l.n { p = p[0:l.n] } - n, err = l.r.Read(p); - l.n -= int64(n); - return; + n, err = l.r.Read(p) + l.n -= int64(n) + return } // NewSectionReader returns a SectionReader that reads from r @@ -302,10 +302,10 @@ func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader { // SectionReader implements Read, Seek, and ReadAt on a section // of an underlying ReaderAt. type SectionReader struct { - r ReaderAt; - base int64; - off int64; - limit int64; + r ReaderAt + base int64 + off int64 + limit int64 } func (s *SectionReader) Read(p []byte) (n int, err os.Error) { @@ -315,9 +315,9 @@ func (s *SectionReader) Read(p []byte) (n int, err os.Error) { if max := s.limit - s.off; int64(len(p)) > max { p = p[0:max] } - n, err = s.r.ReadAt(p, s.off); - s.off += int64(n); - return; + n, err = s.r.ReadAt(p, s.off) + s.off += int64(n) + return } func (s *SectionReader) Seek(offset int64, whence int) (ret int64, err os.Error) { @@ -334,20 +334,20 @@ func (s *SectionReader) Seek(offset int64, whence int) (ret int64, err os.Error) if offset < s.off || offset > s.limit { return 0, os.EINVAL } - s.off = offset; - return offset - s.base, nil; + s.off = offset + return offset - s.base, nil } func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err os.Error) { if off < 0 || off >= s.limit-s.base { return 0, os.EOF } - off += s.base; + off += s.base if max := s.limit - off; int64(len(p)) > max { p = p[0:max] } - return s.r.ReadAt(p, off); + return s.r.ReadAt(p, off) } // Size returns the size of the section in bytes. -func (s *SectionReader) Size() int64 { return s.limit - s.base } +func (s *SectionReader) Size() int64 { return s.limit - s.base } diff --git a/src/pkg/io/io_test.go b/src/pkg/io/io_test.go index 571712031..4ad1e5951 100644 --- a/src/pkg/io/io_test.go +++ b/src/pkg/io/io_test.go @@ -5,75 +5,75 @@ package io_test import ( - "bytes"; - . "io"; - "testing"; + "bytes" + . "io" + "testing" ) // An version of bytes.Buffer without ReadFrom and WriteTo type Buffer struct { - bytes.Buffer; - ReaderFrom; // conflicts with and hides bytes.Buffer's ReaderFrom. - WriterTo; // conflicts with and hides bytes.Buffer's WriterTo. + bytes.Buffer + ReaderFrom // conflicts with and hides bytes.Buffer's ReaderFrom. + WriterTo // conflicts with and hides bytes.Buffer's WriterTo. } // Simple tests, primarily to verify the ReadFrom and WriteTo callouts inside Copy and Copyn. func TestCopy(t *testing.T) { - rb := new(Buffer); - wb := new(Buffer); - rb.WriteString("hello, world."); - Copy(wb, rb); + rb := new(Buffer) + wb := new(Buffer) + rb.WriteString("hello, world.") + Copy(wb, rb) if wb.String() != "hello, world." { t.Errorf("Copy did not work properly") } } func TestCopyReadFrom(t *testing.T) { - rb := new(Buffer); - wb := new(bytes.Buffer); // implements ReadFrom. - rb.WriteString("hello, world."); - Copy(wb, rb); + rb := new(Buffer) + wb := new(bytes.Buffer) // implements ReadFrom. + rb.WriteString("hello, world.") + Copy(wb, rb) if wb.String() != "hello, world." { t.Errorf("Copy did not work properly") } } func TestCopyWriteTo(t *testing.T) { - rb := new(bytes.Buffer); // implements WriteTo. - wb := new(Buffer); - rb.WriteString("hello, world."); - Copy(wb, rb); + rb := new(bytes.Buffer) // implements WriteTo. + wb := new(Buffer) + rb.WriteString("hello, world.") + Copy(wb, rb) if wb.String() != "hello, world." { t.Errorf("Copy did not work properly") } } func TestCopyn(t *testing.T) { - rb := new(Buffer); - wb := new(Buffer); - rb.WriteString("hello, world."); - Copyn(wb, rb, 5); + rb := new(Buffer) + wb := new(Buffer) + rb.WriteString("hello, world.") + Copyn(wb, rb, 5) if wb.String() != "hello" { t.Errorf("Copyn did not work properly") } } func TestCopynReadFrom(t *testing.T) { - rb := new(Buffer); - wb := new(bytes.Buffer); // implements ReadFrom. - rb.WriteString("hello"); - Copyn(wb, rb, 5); + rb := new(Buffer) + wb := new(bytes.Buffer) // implements ReadFrom. + rb.WriteString("hello") + Copyn(wb, rb, 5) if wb.String() != "hello" { t.Errorf("Copyn did not work properly") } } func TestCopynWriteTo(t *testing.T) { - rb := new(bytes.Buffer); // implements WriteTo. - wb := new(Buffer); - rb.WriteString("hello, world."); - Copyn(wb, rb, 5); + rb := new(bytes.Buffer) // implements WriteTo. + wb := new(Buffer) + rb.WriteString("hello, world.") + Copyn(wb, rb, 5) if wb.String() != "hello" { t.Errorf("Copyn did not work properly") } diff --git a/src/pkg/io/ioutil/ioutil.go b/src/pkg/io/ioutil/ioutil.go index c322f49c2..65f457b24 100644 --- a/src/pkg/io/ioutil/ioutil.go +++ b/src/pkg/io/ioutil/ioutil.go @@ -7,84 +7,84 @@ package ioutil import ( - "bytes"; - "io"; - "os"; - "sort"; + "bytes" + "io" + "os" + "sort" ) // ReadAll reads from r until an error or EOF and returns the data it read. func ReadAll(r io.Reader) ([]byte, os.Error) { - var buf bytes.Buffer; - _, err := io.Copy(&buf, r); - return buf.Bytes(), err; + var buf bytes.Buffer + _, err := io.Copy(&buf, r) + return buf.Bytes(), err } // ReadFile reads the file named by filename and returns the contents. func ReadFile(filename string) ([]byte, os.Error) { - f, err := os.Open(filename, os.O_RDONLY, 0); + f, err := os.Open(filename, os.O_RDONLY, 0) if err != nil { return nil, err } - defer f.Close(); + defer f.Close() // It's a good but not certain bet that Stat will tell us exactly how much to // read, so let's try it but be prepared for the answer to be wrong. - dir, err := f.Stat(); - var n uint64; - if err != nil && dir.Size < 2e9 { // Don't preallocate a huge buffer, just in case. + dir, err := f.Stat() + var n uint64 + if err != nil && dir.Size < 2e9 { // Don't preallocate a huge buffer, just in case. n = dir.Size } // Add a little extra in case Size is zero, and to avoid another allocation after // Read has filled the buffer. - n += bytes.MinRead; + n += bytes.MinRead // Pre-allocate the correct size of buffer, then set its size to zero. The // Buffer will read into the allocated space cheaply. If the size was wrong, // we'll either waste some space off the end or reallocate as needed, but // in the overwhelmingly common case we'll get it just right. - buf := bytes.NewBuffer(make([]byte, 0, n)); - _, err = buf.ReadFrom(f); - return buf.Bytes(), err; + buf := bytes.NewBuffer(make([]byte, 0, n)) + _, err = buf.ReadFrom(f) + return buf.Bytes(), err } // WriteFile writes data to a file named by filename. // If the file does not exist, WriteFile creates it with permissions perm; // otherwise WriteFile truncates it before writing. func WriteFile(filename string, data []byte, perm int) os.Error { - f, err := os.Open(filename, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, perm); + f, err := os.Open(filename, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, perm) if err != nil { return err } - n, err := f.Write(data); - f.Close(); + n, err := f.Write(data) + f.Close() if err == nil && n < len(data) { err = io.ErrShortWrite } - return err; + return err } // A dirList implements sort.Interface. type dirList []*os.Dir -func (d dirList) Len() int { return len(d) } -func (d dirList) Less(i, j int) bool { return d[i].Name < d[j].Name } -func (d dirList) Swap(i, j int) { d[i], d[j] = d[j], d[i] } +func (d dirList) Len() int { return len(d) } +func (d dirList) Less(i, j int) bool { return d[i].Name < d[j].Name } +func (d dirList) Swap(i, j int) { d[i], d[j] = d[j], d[i] } // ReadDir reads the directory named by dirname and returns // a list of sorted directory entries. func ReadDir(dirname string) ([]*os.Dir, os.Error) { - f, err := os.Open(dirname, os.O_RDONLY, 0); + f, err := os.Open(dirname, os.O_RDONLY, 0) if err != nil { return nil, err } - list, err := f.Readdir(-1); - f.Close(); + list, err := f.Readdir(-1) + f.Close() if err != nil { return nil, err } - dirs := make(dirList, len(list)); + dirs := make(dirList, len(list)) for i := range list { dirs[i] = &list[i] } - sort.Sort(dirs); - return dirs, nil; + sort.Sort(dirs) + return dirs, nil } diff --git a/src/pkg/io/ioutil/ioutil_test.go b/src/pkg/io/ioutil/ioutil_test.go index aa57c6560..1deffe83e 100644 --- a/src/pkg/io/ioutil/ioutil_test.go +++ b/src/pkg/io/ioutil/ioutil_test.go @@ -5,14 +5,14 @@ package ioutil_test import ( - . "io/ioutil"; - "os"; - "strings"; - "testing"; + . "io/ioutil" + "os" + "strings" + "testing" ) func checkSize(t *testing.T, path string, size uint64) { - dir, err := os.Stat(path); + dir, err := os.Stat(path) if err != nil { t.Fatalf("Stat %q (looking for size %d): %s", path, size, err) } @@ -22,32 +22,32 @@ func checkSize(t *testing.T, path string, size uint64) { } func TestReadFile(t *testing.T) { - filename := "rumpelstilzchen"; - contents, err := ReadFile(filename); + filename := "rumpelstilzchen" + contents, err := ReadFile(filename) if err == nil { t.Fatalf("ReadFile %s: error expected, none found", filename) } - filename = "ioutil_test.go"; - contents, err = ReadFile(filename); + filename = "ioutil_test.go" + contents, err = ReadFile(filename) if err != nil { t.Fatalf("ReadFile %s: %v", filename, err) } - checkSize(t, filename, uint64(len(contents))); + checkSize(t, filename, uint64(len(contents))) } func TestWriteFile(t *testing.T) { - filename := "_obj/rumpelstilzchen"; + filename := "_obj/rumpelstilzchen" data := "Programming today is a race between software engineers striving to " + "build bigger and better idiot-proof programs, and the Universe trying " + - "to produce bigger and better idiots. So far, the Universe is winning."; + "to produce bigger and better idiots. So far, the Universe is winning." if err := WriteFile(filename, strings.Bytes(data), 0644); err != nil { t.Fatalf("WriteFile %s: %v", filename, err) } - contents, err := ReadFile(filename); + contents, err := ReadFile(filename) if err != nil { t.Fatalf("ReadFile %s: %v", filename, err) } @@ -57,25 +57,25 @@ func TestWriteFile(t *testing.T) { } // cleanup - os.Remove(filename); // ignore error + os.Remove(filename) // ignore error } func TestReadDir(t *testing.T) { - dirname := "rumpelstilzchen"; - _, err := ReadDir(dirname); + dirname := "rumpelstilzchen" + _, err := ReadDir(dirname) if err == nil { t.Fatalf("ReadDir %s: error expected, none found", dirname) } - dirname = "."; - list, err := ReadDir(dirname); + dirname = "." + list, err := ReadDir(dirname) if err != nil { t.Fatalf("ReadDir %s: %v", dirname, err) } - foundTest := false; - foundObj := false; + foundTest := false + foundObj := false for _, dir := range list { switch { case dir.IsRegular() && dir.Name == "ioutil_test.go": diff --git a/src/pkg/io/pipe.go b/src/pkg/io/pipe.go index a12d937dd..8f821a9c6 100644 --- a/src/pkg/io/pipe.go +++ b/src/pkg/io/pipe.go @@ -8,25 +8,25 @@ package io import ( - "os"; - "sync"; + "os" + "sync" ) type pipeReturn struct { - n int; - err os.Error; + n int + err os.Error } // Shared pipe structure. type pipe struct { - rclosed bool; // Read end closed? - rerr os.Error; // Error supplied to CloseReader - wclosed bool; // Write end closed? - werr os.Error; // Error supplied to CloseWriter - wpend []byte; // Written data waiting to be read. - wtot int; // Bytes consumed so far in current write. - cr chan []byte; // Write sends data here... - cw chan pipeReturn; // ... and reads the n, err back from here. + rclosed bool // Read end closed? + rerr os.Error // Error supplied to CloseReader + wclosed bool // Write end closed? + werr os.Error // Error supplied to CloseWriter + wpend []byte // Written data waiting to be read. + wtot int // Bytes consumed so far in current write. + cr chan []byte // Write sends data here... + cw chan pipeReturn // ... and reads the n, err back from here. } func (p *pipe) Read(data []byte) (n int, err os.Error) { @@ -42,28 +42,28 @@ func (p *pipe) Read(data []byte) (n int, err os.Error) { if p.wpend == nil { return 0, p.werr } - p.wtot = 0; + p.wtot = 0 } // Read from current write block. - n = len(data); + n = len(data) if n > len(p.wpend) { n = len(p.wpend) } for i := 0; i < n; i++ { data[i] = p.wpend[i] } - p.wtot += n; - p.wpend = p.wpend[n:]; + p.wtot += n + p.wpend = p.wpend[n:] // If write block is done, finish the write. if len(p.wpend) == 0 { - p.wpend = nil; - p.cw <- pipeReturn{p.wtot, nil}; - p.wtot = 0; + p.wpend = nil + p.cw <- pipeReturn{p.wtot, nil} + p.wtot = 0 } - return n, nil; + return n, nil } func (p *pipe) Write(data []byte) (n int, err os.Error) { @@ -75,11 +75,11 @@ func (p *pipe) Write(data []byte) (n int, err os.Error) { } // Send data to reader. - p.cr <- data; + p.cr <- data // Wait for reader to finish copying it. - res := <-p.cw; - return res.n, res.err; + res := <-p.cw + return res.n, res.err } func (p *pipe) CloseReader(rerr os.Error) os.Error { @@ -88,18 +88,18 @@ func (p *pipe) CloseReader(rerr os.Error) os.Error { } // Stop any future writes. - p.rclosed = true; + p.rclosed = true if rerr == nil { rerr = os.EPIPE } - p.rerr = rerr; + p.rerr = rerr // Stop the current write. if !p.wclosed { p.cw <- pipeReturn{p.wtot, rerr} } - return nil; + return nil } func (p *pipe) CloseWriter(werr os.Error) os.Error { @@ -111,15 +111,15 @@ func (p *pipe) CloseWriter(werr os.Error) os.Error { } // Stop any future reads. - p.wclosed = true; - p.werr = werr; + p.wclosed = true + p.werr = werr // Stop the current read. if !p.rclosed { p.cr <- nil } - return nil; + return nil } // Read/write halves of the pipe. @@ -132,8 +132,8 @@ func (p *pipe) CloseWriter(werr os.Error) os.Error { // A PipeReader is the read half of a pipe. type PipeReader struct { - lock sync.Mutex; - p *pipe; + lock sync.Mutex + p *pipe } // Read implements the standard Read interface: @@ -142,36 +142,36 @@ type PipeReader struct { // If the write end is closed with an error, that error is // returned as err; otherwise err is nil. func (r *PipeReader) Read(data []byte) (n int, err os.Error) { - r.lock.Lock(); - defer r.lock.Unlock(); + r.lock.Lock() + defer r.lock.Unlock() - return r.p.Read(data); + return r.p.Read(data) } // Close closes the reader; subsequent writes to the // write half of the pipe will return the error os.EPIPE. func (r *PipeReader) Close() os.Error { - r.lock.Lock(); - defer r.lock.Unlock(); + r.lock.Lock() + defer r.lock.Unlock() - return r.p.CloseReader(nil); + return r.p.CloseReader(nil) } // CloseWithError closes the reader; subsequent writes // to the write half of the pipe will return the error rerr. func (r *PipeReader) CloseWithError(rerr os.Error) os.Error { - r.lock.Lock(); - defer r.lock.Unlock(); + r.lock.Lock() + defer r.lock.Unlock() - return r.p.CloseReader(rerr); + return r.p.CloseReader(rerr) } -func (r *PipeReader) finish() { r.Close() } +func (r *PipeReader) finish() { r.Close() } // Write half of pipe. type PipeWriter struct { - lock sync.Mutex; - p *pipe; + lock sync.Mutex + p *pipe } // Write implements the standard Write interface: @@ -180,31 +180,31 @@ type PipeWriter struct { // If the read end is closed with an error, that err is // returned as err; otherwise err is os.EPIPE. func (w *PipeWriter) Write(data []byte) (n int, err os.Error) { - w.lock.Lock(); - defer w.lock.Unlock(); + w.lock.Lock() + defer w.lock.Unlock() - return w.p.Write(data); + return w.p.Write(data) } // Close closes the writer; subsequent reads from the // read half of the pipe will return no bytes and a nil error. func (w *PipeWriter) Close() os.Error { - w.lock.Lock(); - defer w.lock.Unlock(); + w.lock.Lock() + defer w.lock.Unlock() - return w.p.CloseWriter(nil); + return w.p.CloseWriter(nil) } // CloseWithError closes the writer; subsequent reads from the // read half of the pipe will return no bytes and the error werr. func (w *PipeWriter) CloseWithError(werr os.Error) os.Error { - w.lock.Lock(); - defer w.lock.Unlock(); + w.lock.Lock() + defer w.lock.Unlock() - return w.p.CloseWriter(werr); + return w.p.CloseWriter(werr) } -func (w *PipeWriter) finish() { w.Close() } +func (w *PipeWriter) finish() { w.Close() } // Pipe creates a synchronous in-memory pipe. // It can be used to connect code expecting an io.Reader @@ -212,12 +212,12 @@ func (w *PipeWriter) finish() { w.Close() } // Reads on one end are matched with writes on the other, // copying data directly between the two; there is no internal buffering. func Pipe() (*PipeReader, *PipeWriter) { - p := new(pipe); - p.cr = make(chan []byte, 1); - p.cw = make(chan pipeReturn, 1); - r := new(PipeReader); - r.p = p; - w := new(PipeWriter); - w.p = p; - return r, w; + p := new(pipe) + p.cr = make(chan []byte, 1) + p.cw = make(chan pipeReturn, 1) + r := new(PipeReader) + r.p = p + w := new(PipeWriter) + w.p = p + return r, w } diff --git a/src/pkg/io/pipe_test.go b/src/pkg/io/pipe_test.go index df83c3ade..793bed459 100644 --- a/src/pkg/io/pipe_test.go +++ b/src/pkg/io/pipe_test.go @@ -5,118 +5,118 @@ package io_test import ( - "fmt"; - . "io"; - "os"; - "strings"; - "testing"; - "time"; + "fmt" + . "io" + "os" + "strings" + "testing" + "time" ) func checkWrite(t *testing.T, w Writer, data []byte, c chan int) { - n, err := w.Write(data); + n, err := w.Write(data) if err != nil { t.Errorf("write: %v", err) } if n != len(data) { t.Errorf("short write: %d != %d", n, len(data)) } - c <- 0; + c <- 0 } // Test a single read/write pair. func TestPipe1(t *testing.T) { - c := make(chan int); - r, w := Pipe(); - var buf = make([]byte, 64); - go checkWrite(t, w, strings.Bytes("hello, world"), c); - n, err := r.Read(buf); + c := make(chan int) + r, w := Pipe() + var buf = make([]byte, 64) + go checkWrite(t, w, strings.Bytes("hello, world"), c) + n, err := r.Read(buf) if err != nil { t.Errorf("read: %v", err) } else if n != 12 || string(buf[0:12]) != "hello, world" { t.Errorf("bad read: got %q", buf[0:n]) } - <-c; - r.Close(); - w.Close(); + <-c + r.Close() + w.Close() } func reader(t *testing.T, r Reader, c chan int) { - var buf = make([]byte, 64); + var buf = make([]byte, 64) for { - n, err := r.Read(buf); + n, err := r.Read(buf) if err == os.EOF { - c <- 0; - break; + c <- 0 + break } if err != nil { t.Errorf("read: %v", err) } - c <- n; + c <- n } } // Test a sequence of read/write pairs. func TestPipe2(t *testing.T) { - c := make(chan int); - r, w := Pipe(); - go reader(t, r, c); - var buf = make([]byte, 64); + c := make(chan int) + r, w := Pipe() + go reader(t, r, c) + var buf = make([]byte, 64) for i := 0; i < 5; i++ { - p := buf[0 : 5+i*10]; - n, err := w.Write(p); + p := buf[0 : 5+i*10] + n, err := w.Write(p) if n != len(p) { t.Errorf("wrote %d, got %d", len(p), n) } if err != nil { t.Errorf("write: %v", err) } - nn := <-c; + nn := <-c if nn != n { t.Errorf("wrote %d, read got %d", n, nn) } } - w.Close(); - nn := <-c; + w.Close() + nn := <-c if nn != 0 { t.Errorf("final read got %d", nn) } } type pipeReturn struct { - n int; - err os.Error; + n int + err os.Error } // Test a large write that requires multiple reads to satisfy. func writer(w WriteCloser, buf []byte, c chan pipeReturn) { - n, err := w.Write(buf); - w.Close(); - c <- pipeReturn{n, err}; + n, err := w.Write(buf) + w.Close() + c <- pipeReturn{n, err} } func TestPipe3(t *testing.T) { - c := make(chan pipeReturn); - r, w := Pipe(); - var wdat = make([]byte, 128); + c := make(chan pipeReturn) + r, w := Pipe() + var wdat = make([]byte, 128) for i := 0; i < len(wdat); i++ { wdat[i] = byte(i) } - go writer(w, wdat, c); - var rdat = make([]byte, 1024); - tot := 0; + go writer(w, wdat, c) + var rdat = make([]byte, 1024) + tot := 0 for n := 1; n <= 256; n *= 2 { - nn, err := r.Read(rdat[tot : tot+n]); + nn, err := r.Read(rdat[tot : tot+n]) if err != nil && err != os.EOF { t.Fatalf("read: %v", err) } // only final two reads should be short - 1 byte, then 0 - expect := n; + expect := n if n == 128 { expect = 1 } else if n == 256 { - expect = 0; + expect = 0 if err != os.EOF { t.Fatalf("read at end: %v", err) } @@ -124,9 +124,9 @@ func TestPipe3(t *testing.T) { if nn != expect { t.Fatalf("read %d, expected %d, got %d", n, expect, nn) } - tot += nn; + tot += nn } - pr := <-c; + pr := <-c if pr.n != 128 || pr.err != nil { t.Fatalf("write 128: %d, %v", pr.n, pr.err) } @@ -143,14 +143,14 @@ func TestPipe3(t *testing.T) { // Test read after/before writer close. type closer interface { - CloseWithError(os.Error) os.Error; - Close() os.Error; + CloseWithError(os.Error) os.Error + Close() os.Error } type pipeTest struct { - async bool; - err os.Error; - closeWithError bool; + async bool + err os.Error + closeWithError bool } func (p pipeTest) String() string { @@ -167,8 +167,8 @@ var pipeTests = []pipeTest{ } func delayClose(t *testing.T, cl closer, ch chan int, tt pipeTest) { - time.Sleep(1e6); // 1 ms - var err os.Error; + time.Sleep(1e6) // 1 ms + var err os.Error if tt.closeWithError { err = cl.CloseWithError(tt.err) } else { @@ -177,22 +177,22 @@ func delayClose(t *testing.T, cl closer, ch chan int, tt pipeTest) { if err != nil { t.Errorf("delayClose: %v", err) } - ch <- 0; + ch <- 0 } func TestPipeReadClose(t *testing.T) { for _, tt := range pipeTests { - c := make(chan int, 1); - r, w := Pipe(); + c := make(chan int, 1) + r, w := Pipe() if tt.async { go delayClose(t, w, c, tt) } else { delayClose(t, w, c, tt) } - var buf = make([]byte, 64); - n, err := r.Read(buf); - <-c; - want := tt.err; + var buf = make([]byte, 64) + n, err := r.Read(buf) + <-c + want := tt.err if want == nil { want = os.EOF } @@ -212,16 +212,16 @@ func TestPipeReadClose(t *testing.T) { func TestPipeWriteClose(t *testing.T) { for _, tt := range pipeTests { - c := make(chan int, 1); - r, w := Pipe(); + c := make(chan int, 1) + r, w := Pipe() if tt.async { go delayClose(t, r, c, tt) } else { delayClose(t, r, c, tt) } - n, err := WriteString(w, "hello, world"); - <-c; - expect := tt.err; + n, err := WriteString(w, "hello, world") + <-c + expect := tt.err if expect == nil { expect = os.EPIPE } diff --git a/src/pkg/json/decode.go b/src/pkg/json/decode.go index 386ca0016..c2dd93eca 100644 --- a/src/pkg/json/decode.go +++ b/src/pkg/json/decode.go @@ -8,8 +8,8 @@ package json import ( - "container/vector"; - "os"; + "container/vector" + "os" ) // Decode a JSON string @@ -23,75 +23,75 @@ import ( // If Decode encounters a syntax error, it returns with err set to an // instance of ParseError. See ParseError documentation for details. func Decode(s string) (data interface{}, err os.Error) { - jb := newDecoder(nil, nil); - ok, errPos, errTok := Parse(s, jb); + jb := newDecoder(nil, nil) + ok, errPos, errTok := Parse(s, jb) if ok { data = jb.Data() } else { err = &ParseError{Index: errPos, Token: errTok} } - return; + return } type decoder struct { // A value being constructed. - value interface{}; + value interface{} // Container entity to flush into. Can be either vector.Vector or // map[string]interface{}. - container interface{}; + container interface{} // The index into the container interface. Either int or string. - index interface{}; + index interface{} } func newDecoder(container interface{}, key interface{}) *decoder { return &decoder{container: container, index: key} } -func (j *decoder) Int64(i int64) { j.value = float64(i) } +func (j *decoder) Int64(i int64) { j.value = float64(i) } -func (j *decoder) Uint64(i uint64) { j.value = float64(i) } +func (j *decoder) Uint64(i uint64) { j.value = float64(i) } -func (j *decoder) Float64(f float64) { j.value = float64(f) } +func (j *decoder) Float64(f float64) { j.value = float64(f) } -func (j *decoder) String(s string) { j.value = s } +func (j *decoder) String(s string) { j.value = s } -func (j *decoder) Bool(b bool) { j.value = b } +func (j *decoder) Bool(b bool) { j.value = b } -func (j *decoder) Null() { j.value = nil } +func (j *decoder) Null() { j.value = nil } -func (j *decoder) Array() { j.value = new(vector.Vector) } +func (j *decoder) Array() { j.value = new(vector.Vector) } -func (j *decoder) Map() { j.value = make(map[string]interface{}) } +func (j *decoder) Map() { j.value = make(map[string]interface{}) } func (j *decoder) Elem(i int) Builder { - v, ok := j.value.(*vector.Vector); + v, ok := j.value.(*vector.Vector) if !ok { - v = new(vector.Vector); - j.value = v; + v = new(vector.Vector) + j.value = v } if v.Len() <= i { v.Resize(i+1, (i+1)*2) } - return newDecoder(v, i); + return newDecoder(v, i) } func (j *decoder) Key(s string) Builder { - m, ok := j.value.(map[string]interface{}); + m, ok := j.value.(map[string]interface{}) if !ok { - m = make(map[string]interface{}); - j.value = m; + m = make(map[string]interface{}) + j.value = m } - return newDecoder(m, s); + return newDecoder(m, s) } func (j *decoder) Flush() { switch c := j.container.(type) { case *vector.Vector: - index := j.index.(int); - c.Set(index, j.Data()); + index := j.index.(int) + c.Set(index, j.Data()) case map[string]interface{}: - index := j.index.(string); - c[index] = j.Data(); + index := j.index.(string) + c[index] = j.Data() } } @@ -101,5 +101,5 @@ func (j *decoder) Data() interface{} { case *vector.Vector: return v.Data() } - return j.value; + return j.value } diff --git a/src/pkg/json/decode_test.go b/src/pkg/json/decode_test.go index 1b429b0ee..b712d6558 100644 --- a/src/pkg/json/decode_test.go +++ b/src/pkg/json/decode_test.go @@ -5,73 +5,73 @@ package json import ( - "container/vector"; - "reflect"; - "testing"; + "container/vector" + "reflect" + "testing" ) func TestDecodeInt64(t *testing.T) { - nb := newDecoder(nil, nil); - nb.Int64(-15); - assertResult(t, nb.Data(), float64(-15)); + nb := newDecoder(nil, nil) + nb.Int64(-15) + assertResult(t, nb.Data(), float64(-15)) } func TestDecodeUint64(t *testing.T) { - nb := newDecoder(nil, nil); - nb.Uint64(15); - assertResult(t, nb.Data(), float64(15)); + nb := newDecoder(nil, nil) + nb.Uint64(15) + assertResult(t, nb.Data(), float64(15)) } func TestDecodeFloat64(t *testing.T) { - nb := newDecoder(nil, nil); - nb.Float64(3.14159); - assertResult(t, nb.Data(), float64(3.14159)); + nb := newDecoder(nil, nil) + nb.Float64(3.14159) + assertResult(t, nb.Data(), float64(3.14159)) } func TestDecodeString(t *testing.T) { - nb := newDecoder(nil, nil); - nb.String("Some string"); - assertResult(t, nb.Data(), "Some string"); + nb := newDecoder(nil, nil) + nb.String("Some string") + assertResult(t, nb.Data(), "Some string") } func TestDecodeBool(t *testing.T) { - nb := newDecoder(nil, nil); - nb.Bool(true); - assertResult(t, nb.Data(), true); + nb := newDecoder(nil, nil) + nb.Bool(true) + assertResult(t, nb.Data(), true) } func TestDecodeNull(t *testing.T) { - nb := newDecoder(nil, nil); - nb.Null(); - assertResult(t, nb.Data(), nil); + nb := newDecoder(nil, nil) + nb.Null() + assertResult(t, nb.Data(), nil) } func TestDecodeEmptyArray(t *testing.T) { - nb := newDecoder(nil, nil); - nb.Array(); - assertResult(t, nb.Data(), []interface{}{}); + nb := newDecoder(nil, nil) + nb.Array() + assertResult(t, nb.Data(), []interface{}{}) } func TestDecodeEmptyMap(t *testing.T) { - nb := newDecoder(nil, nil); - nb.Map(); - assertResult(t, nb.Data(), map[string]interface{}{}); + nb := newDecoder(nil, nil) + nb.Map() + assertResult(t, nb.Data(), map[string]interface{}{}) } func TestDecodeFlushElem(t *testing.T) { - testVec := new(vector.Vector).Resize(2, 2); - nb := newDecoder(testVec, 1); - nb.Float64(3.14159); - nb.Flush(); - assertResult(t, testVec.Data(), []interface{}{nil, float64(3.14159)}); + testVec := new(vector.Vector).Resize(2, 2) + nb := newDecoder(testVec, 1) + nb.Float64(3.14159) + nb.Flush() + assertResult(t, testVec.Data(), []interface{}{nil, float64(3.14159)}) } func TestDecodeFlushKey(t *testing.T) { - testMap := make(map[string]interface{}); - nb := newDecoder(testMap, "key"); - nb.Float64(3.14159); - nb.Flush(); - assertResult(t, testMap, map[string]interface{}{"key": float64(3.14159)}); + testMap := make(map[string]interface{}) + nb := newDecoder(testMap, "key") + nb.Float64(3.14159) + nb.Flush() + assertResult(t, testMap, map[string]interface{}{"key": float64(3.14159)}) } // Elem() and Key() are hard to test in isolation because all they do @@ -80,21 +80,21 @@ func TestDecodeFlushKey(t *testing.T) { // Array(), String(), and Flush(). func TestDecodeElem(t *testing.T) { - nb := newDecoder(nil, nil); - nb.Array(); - var b Builder = nb.Elem(0); - b.String("0"); - b.Flush(); - assertResult(t, nb.Data(), []interface{}{"0"}); + nb := newDecoder(nil, nil) + nb.Array() + var b Builder = nb.Elem(0) + b.String("0") + b.Flush() + assertResult(t, nb.Data(), []interface{}{"0"}) } func TestDecodeKey(t *testing.T) { - nb := newDecoder(nil, nil); - nb.Map(); - var b Builder = nb.Key("a"); - b.String("0"); - b.Flush(); - assertResult(t, nb.Data(), map[string]interface{}{"a": "0"}); + nb := newDecoder(nil, nil) + nb.Map() + var b Builder = nb.Key("a") + b.String("0") + b.Flush() + assertResult(t, nb.Data(), map[string]interface{}{"a": "0"}) } func assertResult(t *testing.T, results, expected interface{}) { @@ -104,8 +104,8 @@ func assertResult(t *testing.T, results, expected interface{}) { } type decodeTest struct { - s string; - r interface{}; + s string + r interface{} } var tests = []decodeTest{ diff --git a/src/pkg/json/error.go b/src/pkg/json/error.go index aa5b962ae..c5f31b02d 100644 --- a/src/pkg/json/error.go +++ b/src/pkg/json/error.go @@ -9,8 +9,8 @@ import "fmt" // ParseError aggregates information about a JSON parse error. It is // compatible with the os.Error interface. type ParseError struct { - Index int; // A byte index in JSON string where the error occurred - Token string; // An offending token + Index int // A byte index in JSON string where the error occurred + Token string // An offending token } // Produce a string representation of this ParseError. diff --git a/src/pkg/json/parse.go b/src/pkg/json/parse.go index f9c472977..f7eb0a61b 100644 --- a/src/pkg/json/parse.go +++ b/src/pkg/json/parse.go @@ -11,9 +11,9 @@ package json import ( - "bytes"; - "strconv"; - "utf8"; + "bytes" + "strconv" + "utf8" ) // Strings @@ -23,12 +23,12 @@ import ( // Have also seen \' and embedded newlines. func _UnHex(p string, r, l int) (v int, ok bool) { - v = 0; + v = 0 for i := r; i < l; i++ { if i >= len(p) { return 0, false } - v *= 16; + v *= 16 switch { case '0' <= p[i] && p[i] <= '9': v += int(p[i] - '0') @@ -40,15 +40,15 @@ func _UnHex(p string, r, l int) (v int, ok bool) { return 0, false } } - return v, true; + return v, true } func _ToHex(b []byte, rune int) { - const hexDigits = "0123456789abcdef"; - b[0] = hexDigits[rune>>12&0xf]; - b[1] = hexDigits[rune>>8&0xf]; - b[2] = hexDigits[rune>>4&0xf]; - b[3] = hexDigits[rune&0xf]; + const hexDigits = "0123456789abcdef" + b[0] = hexDigits[rune>>12&0xf] + b[1] = hexDigits[rune>>8&0xf] + b[2] = hexDigits[rune>>4&0xf] + b[3] = hexDigits[rune&0xf] } // Unquote unquotes the JSON-quoted string s, @@ -58,12 +58,12 @@ func Unquote(s string) (t string, ok bool) { if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' { return } - b := make([]byte, len(s)); - w := 0; + b := make([]byte, len(s)) + w := 0 for r := 1; r < len(s)-1; { switch { case s[r] == '\\': - r++; + r++ if r >= len(s)-1 { return } @@ -71,147 +71,147 @@ func Unquote(s string) (t string, ok bool) { default: return case '"', '\\', '/', '\'': - b[w] = s[r]; - r++; - w++; + b[w] = s[r] + r++ + w++ case 'b': - b[w] = '\b'; - r++; - w++; + b[w] = '\b' + r++ + w++ case 'f': - b[w] = '\f'; - r++; - w++; + b[w] = '\f' + r++ + w++ case 'n': - b[w] = '\n'; - r++; - w++; + b[w] = '\n' + r++ + w++ case 'r': - b[w] = '\r'; - r++; - w++; + b[w] = '\r' + r++ + w++ case 't': - b[w] = '\t'; - r++; - w++; + b[w] = '\t' + r++ + w++ case 'u': - r++; - rune, ok := _UnHex(s, r, r+4); + r++ + rune, ok := _UnHex(s, r, r+4) if !ok { return } - r += 4; - w += utf8.EncodeRune(rune, b[w:]); + r += 4 + w += utf8.EncodeRune(rune, b[w:]) } // Control characters are invalid, but we've seen raw \n. case s[r] < ' ' && s[r] != '\n': if s[r] == '\n' { - b[w] = '\n'; - r++; - w++; - break; + b[w] = '\n' + r++ + w++ + break } - return; + return // ASCII case s[r] < utf8.RuneSelf: - b[w] = s[r]; - r++; - w++; + b[w] = s[r] + r++ + w++ // Coerce to well-formed UTF-8. default: - rune, size := utf8.DecodeRuneInString(s[r:]); - r += size; - w += utf8.EncodeRune(rune, b[w:]); + rune, size := utf8.DecodeRuneInString(s[r:]) + r += size + w += utf8.EncodeRune(rune, b[w:]) } } - return string(b[0:w]), true; + return string(b[0:w]), true } // Quote quotes the raw string s using JSON syntax, // so that Unquote(Quote(s)) = s, true. func Quote(s string) string { - chr := make([]byte, 6); - chr0 := chr[0:1]; - b := new(bytes.Buffer); - chr[0] = '"'; - b.Write(chr0); + chr := make([]byte, 6) + chr0 := chr[0:1] + b := new(bytes.Buffer) + chr[0] = '"' + b.Write(chr0) for _, rune := range s { switch { case rune == '"' || rune == '\\': - chr[0] = '\\'; - chr[1] = byte(rune); - b.Write(chr[0:2]); + chr[0] = '\\' + chr[1] = byte(rune) + b.Write(chr[0:2]) case rune == '\b': - chr[0] = '\\'; - chr[1] = 'b'; - b.Write(chr[0:2]); + chr[0] = '\\' + chr[1] = 'b' + b.Write(chr[0:2]) case rune == '\f': - chr[0] = '\\'; - chr[1] = 'f'; - b.Write(chr[0:2]); + chr[0] = '\\' + chr[1] = 'f' + b.Write(chr[0:2]) case rune == '\n': - chr[0] = '\\'; - chr[1] = 'n'; - b.Write(chr[0:2]); + chr[0] = '\\' + chr[1] = 'n' + b.Write(chr[0:2]) case rune == '\r': - chr[0] = '\\'; - chr[1] = 'r'; - b.Write(chr[0:2]); + chr[0] = '\\' + chr[1] = 'r' + b.Write(chr[0:2]) case rune == '\t': - chr[0] = '\\'; - chr[1] = 't'; - b.Write(chr[0:2]); + chr[0] = '\\' + chr[1] = 't' + b.Write(chr[0:2]) case 0x20 <= rune && rune < utf8.RuneSelf: - chr[0] = byte(rune); - b.Write(chr0); + chr[0] = byte(rune) + b.Write(chr0) default: - chr[0] = '\\'; - chr[1] = 'u'; - _ToHex(chr[2:6], rune); - b.Write(chr); + chr[0] = '\\' + chr[1] = 'u' + _ToHex(chr[2:6], rune) + b.Write(chr) } } - chr[0] = '"'; - b.Write(chr0); - return b.String(); + chr[0] = '"' + b.Write(chr0) + return b.String() } // _Lexer type _Lexer struct { - s string; - i int; - kind int; - token string; + s string + i int + kind int + token string } func punct(c byte) bool { return c == '"' || c == '[' || c == ']' || c == ':' || c == '{' || c == '}' || c == ',' } -func white(c byte) bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' } +func white(c byte) bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' } func skipwhite(p string, i int) int { for i < len(p) && white(p[i]) { i++ } - return i; + return i } func skiptoken(p string, i int) int { for i < len(p) && !punct(p[i]) && !white(p[i]) { i++ } - return i; + return i } func skipstring(p string, i int) int { @@ -223,50 +223,50 @@ func skipstring(p string, i int) int { if i >= len(p) { return i } - return i + 1; + return i + 1 } func (t *_Lexer) Next() { - i, s := t.i, t.s; - i = skipwhite(s, i); + i, s := t.i, t.s + i = skipwhite(s, i) if i >= len(s) { - t.kind = 0; - t.token = ""; - t.i = len(s); - return; + t.kind = 0 + t.token = "" + t.i = len(s) + return } - c := s[i]; + c := s[i] switch { case c == '-' || '0' <= c && c <= '9': - j := skiptoken(s, i); - t.kind = '1'; - t.token = s[i:j]; - i = j; + j := skiptoken(s, i) + t.kind = '1' + t.token = s[i:j] + i = j case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z': - j := skiptoken(s, i); - t.kind = 'a'; - t.token = s[i:j]; - i = j; + j := skiptoken(s, i) + t.kind = 'a' + t.token = s[i:j] + i = j case c == '"': - j := skipstring(s, i); - t.kind = '"'; - t.token = s[i:j]; - i = j; + j := skipstring(s, i) + t.kind = '"' + t.token = s[i:j] + i = j case c == '[', c == ']', c == ':', c == '{', c == '}', c == ',': - t.kind = int(c); - t.token = s[i : i+1]; - i++; + t.kind = int(c) + t.token = s[i : i+1] + i++ default: - t.kind = '?'; - t.token = s[i : i+1]; + t.kind = '?' + t.token = s[i : i+1] } - t.i = i; + t.i = i } @@ -297,25 +297,25 @@ type _Value interface{} // eventual representation returned by the parser. type Builder interface { // Set value - Int64(i int64); - Uint64(i uint64); - Float64(f float64); - String(s string); - Bool(b bool); - Null(); - Array(); - Map(); + Int64(i int64) + Uint64(i uint64) + Float64(f float64) + String(s string) + Bool(b bool) + Null() + Array() + Map() // Create sub-Builders - Elem(i int) Builder; - Key(s string) Builder; + Elem(i int) Builder + Key(s string) Builder // Flush changes to parent Builder if necessary. - Flush(); + Flush() } func parse(lex *_Lexer, build Builder) bool { - ok := false; + ok := false Switch: switch lex.kind { case 0: @@ -323,93 +323,93 @@ Switch: case '1': // If the number is exactly an integer, use that. if i, err := strconv.Atoi64(lex.token); err == nil { - build.Int64(i); - ok = true; + build.Int64(i) + ok = true } else if i, err := strconv.Atoui64(lex.token); err == nil { - build.Uint64(i); - ok = true; + build.Uint64(i) + ok = true } else // Fall back to floating point. if f, err := strconv.Atof64(lex.token); err == nil { - build.Float64(f); - ok = true; + build.Float64(f) + ok = true } case 'a': switch lex.token { case "true": - build.Bool(true); - ok = true; + build.Bool(true) + ok = true case "false": - build.Bool(false); - ok = true; + build.Bool(false) + ok = true case "null": - build.Null(); - ok = true; + build.Null() + ok = true } case '"': if str, ok1 := Unquote(lex.token); ok1 { - build.String(str); - ok = true; + build.String(str) + ok = true } case '[': // array - build.Array(); - lex.Next(); - n := 0; + build.Array() + lex.Next() + n := 0 for lex.kind != ']' { if n > 0 { if lex.kind != ',' { break Switch } - lex.Next(); + lex.Next() } if !parse(lex, build.Elem(n)) { break Switch } - n++; + n++ } - ok = true; + ok = true case '{': // map - lex.Next(); - build.Map(); - n := 0; + lex.Next() + build.Map() + n := 0 for lex.kind != '}' { if n > 0 { if lex.kind != ',' { break Switch } - lex.Next(); + lex.Next() } if lex.kind != '"' { break Switch } - key, ok := Unquote(lex.token); + key, ok := Unquote(lex.token) if !ok { break Switch } - lex.Next(); + lex.Next() if lex.kind != ':' { break Switch } - lex.Next(); + lex.Next() if !parse(lex, build.Key(key)) { break Switch } - n++; + n++ } - ok = true; + ok = true } if ok { lex.Next() } - build.Flush(); - return ok; + build.Flush() + return ok } // Parse parses the JSON syntax string s and makes calls to @@ -419,13 +419,13 @@ Switch: // to the byte index in s where a syntax error occurred, // and errtok set to the offending token. func Parse(s string, builder Builder) (ok bool, errindx int, errtok string) { - lex := new(_Lexer); - lex.s = s; - lex.Next(); + lex := new(_Lexer) + lex.s = s + lex.Next() if parse(lex, builder) { - if lex.kind == 0 { // EOF + if lex.kind == 0 { // EOF return true, 0, "" } } - return false, lex.i, lex.token; + return false, lex.i, lex.token } diff --git a/src/pkg/json/struct.go b/src/pkg/json/struct.go index d34939cbd..4f2a1782c 100644 --- a/src/pkg/json/struct.go +++ b/src/pkg/json/struct.go @@ -8,19 +8,19 @@ package json import ( - "fmt"; - "io"; - "os"; - "reflect"; - "strings"; + "fmt" + "io" + "os" + "reflect" + "strings" ) type structBuilder struct { - val reflect.Value; + val reflect.Value // if map_ != nil, write val to map_[key] on each change - map_ *reflect.MapValue; - key reflect.Value; + map_ *reflect.MapValue + key reflect.Value } var nobuilder *structBuilder @@ -30,7 +30,7 @@ func isfloat(v reflect.Value) bool { case *reflect.FloatValue, *reflect.Float32Value, *reflect.Float64Value: return true } - return false; + return false } func setfloat(v reflect.Value, f float64) { @@ -84,7 +84,7 @@ func (b *structBuilder) Int64(i int64) { if b == nil { return } - v := b.val; + v := b.val if isfloat(v) { setfloat(v, float64(i)) } else { @@ -96,7 +96,7 @@ func (b *structBuilder) Uint64(i uint64) { if b == nil { return } - v := b.val; + v := b.val if isfloat(v) { setfloat(v, float64(i)) } else { @@ -108,7 +108,7 @@ func (b *structBuilder) Float64(f float64) { if b == nil { return } - v := b.val; + v := b.val if isfloat(v) { setfloat(v, f) } else { @@ -116,7 +116,7 @@ func (b *structBuilder) Float64(f float64) { } } -func (b *structBuilder) Null() {} +func (b *structBuilder) Null() {} func (b *structBuilder) String(s string) { if b == nil { @@ -158,16 +158,16 @@ func (b *structBuilder) Elem(i int) Builder { } case *reflect.SliceValue: if i >= v.Cap() { - n := v.Cap(); + n := v.Cap() if n < 8 { n = 8 } for n <= i { n *= 2 } - nv := reflect.MakeSlice(v.Type().(*reflect.SliceType), v.Len(), n); - reflect.ArrayCopy(nv, v); - v.Set(nv); + nv := reflect.MakeSlice(v.Type().(*reflect.SliceType), v.Len(), n) + reflect.ArrayCopy(nv, v) + v.Set(nv) } if v.Len() <= i && i < v.Cap() { v.SetLen(i + 1) @@ -176,7 +176,7 @@ func (b *structBuilder) Elem(i int) Builder { return &structBuilder{val: v.Elem(i)} } } - return nobuilder; + return nobuilder } func (b *structBuilder) Map() { @@ -185,11 +185,11 @@ func (b *structBuilder) Map() { } if v, ok := b.val.(*reflect.PtrValue); ok && v.IsNil() { if v.IsNil() { - v.PointTo(reflect.MakeZero(v.Type().(*reflect.PtrType).Elem())); - b.Flush(); + v.PointTo(reflect.MakeZero(v.Type().(*reflect.PtrType).Elem())) + b.Flush() } - b.map_ = nil; - b.val = v.Elem(); + b.map_ = nil + b.val = v.Elem() } if v, ok := b.val.(*reflect.MapValue); ok && v.IsNil() { v.Set(reflect.MakeMap(v.Type().(*reflect.MapType))) @@ -202,28 +202,28 @@ func (b *structBuilder) Key(k string) Builder { } switch v := reflect.Indirect(b.val).(type) { case *reflect.StructValue: - t := v.Type().(*reflect.StructType); + t := v.Type().(*reflect.StructType) // Case-insensitive field lookup. - k = strings.ToLower(k); + k = strings.ToLower(k) for i := 0; i < t.NumField(); i++ { if strings.ToLower(t.Field(i).Name) == k { return &structBuilder{val: v.Field(i)} } } case *reflect.MapValue: - t := v.Type().(*reflect.MapType); + t := v.Type().(*reflect.MapType) if t.Key() != reflect.Typeof(k) { break } - key := reflect.NewValue(k); - elem := v.Elem(key); + key := reflect.NewValue(k) + elem := v.Elem(key) if elem == nil { - v.SetElem(key, reflect.MakeZero(t.Elem())); - elem = v.Elem(key); + v.SetElem(key, reflect.MakeZero(t.Elem())) + elem = v.Elem(key) } - return &structBuilder{val: elem, map_: v, key: key}; + return &structBuilder{val: elem, map_: v, key: key} } - return nobuilder; + return nobuilder } // Unmarshal parses the JSON syntax string s and fills in @@ -289,8 +289,8 @@ func (b *structBuilder) Key(k string) Builder { // On a syntax error, it returns with ok set to false and errtok // set to the offending token. func Unmarshal(s string, val interface{}) (ok bool, errtok string) { - v := reflect.NewValue(val); - var b *structBuilder; + v := reflect.NewValue(val) + var b *structBuilder // If val is a pointer to a slice, we append to the slice. if ptr, ok := v.(*reflect.PtrValue); ok { @@ -303,22 +303,22 @@ func Unmarshal(s string, val interface{}) (ok bool, errtok string) { b = &structBuilder{val: v} } - ok, _, errtok = Parse(s, b); + ok, _, errtok = Parse(s, b) if !ok { return false, errtok } - return true, ""; + return true, "" } type MarshalError struct { - T reflect.Type; + T reflect.Type } func (e *MarshalError) String() string { return "json cannot encode value of type " + e.T.String() } func writeArrayOrSlice(w io.Writer, val reflect.ArrayOrSliceValue) os.Error { - fmt.Fprint(w, "["); + fmt.Fprint(w, "[") for i := 0; i < val.Len(); i++ { if err := writeValue(w, val.Elem(i)); err != nil { @@ -330,20 +330,20 @@ func writeArrayOrSlice(w io.Writer, val reflect.ArrayOrSliceValue) os.Error { } } - fmt.Fprint(w, "]"); - return nil; + fmt.Fprint(w, "]") + return nil } func writeMap(w io.Writer, val *reflect.MapValue) os.Error { - key := val.Type().(*reflect.MapType).Key(); + key := val.Type().(*reflect.MapType).Key() if _, ok := key.(*reflect.StringType); !ok { return &MarshalError{val.Type()} } - keys := val.Keys(); - fmt.Fprint(w, "{"); + keys := val.Keys() + fmt.Fprint(w, "{") for i := 0; i < len(keys); i++ { - fmt.Fprintf(w, "%q:", keys[i].(*reflect.StringValue).Get()); + fmt.Fprintf(w, "%q:", keys[i].(*reflect.StringValue).Get()) if err := writeValue(w, val.Elem(keys[i])); err != nil { return err @@ -354,32 +354,32 @@ func writeMap(w io.Writer, val *reflect.MapValue) os.Error { } } - fmt.Fprint(w, "}"); - return nil; + fmt.Fprint(w, "}") + return nil } func writeStruct(w io.Writer, val *reflect.StructValue) os.Error { - fmt.Fprint(w, "{"); + fmt.Fprint(w, "{") - typ := val.Type().(*reflect.StructType); + typ := val.Type().(*reflect.StructType) for i := 0; i < val.NumField(); i++ { - fieldValue := val.Field(i); - fmt.Fprintf(w, "%q:", typ.Field(i).Name); - writeValue(w, fieldValue); + fieldValue := val.Field(i) + fmt.Fprintf(w, "%q:", typ.Field(i).Name) + writeValue(w, fieldValue) if i < val.NumField()-1 { fmt.Fprint(w, ",") } } - fmt.Fprint(w, "}"); - return nil; + fmt.Fprint(w, "}") + return nil } func writeValue(w io.Writer, val reflect.Value) (err os.Error) { if val == nil { - fmt.Fprint(w, "null"); - return; + fmt.Fprint(w, "null") + return } switch v := val.(type) { @@ -404,10 +404,10 @@ func writeValue(w io.Writer, val reflect.Value) (err os.Error) { err = &MarshalError{val.Type()} } default: - value := val.(reflect.Value); - fmt.Fprint(w, value.Interface()); + value := val.(reflect.Value) + fmt.Fprint(w, value.Interface()) } - return; + return } func Marshal(w io.Writer, val interface{}) os.Error { diff --git a/src/pkg/json/struct_test.go b/src/pkg/json/struct_test.go index 1511bc45c..9a928f7d0 100644 --- a/src/pkg/json/struct_test.go +++ b/src/pkg/json/struct_test.go @@ -5,34 +5,34 @@ package json import ( - "bytes"; - "reflect"; - "strconv"; - "testing"; + "bytes" + "reflect" + "strconv" + "testing" ) type myStruct struct { - T bool; - F bool; - S string; - I8 int8; - I16 int16; - I32 int32; - I64 int64; - U8 uint8; - U16 uint16; - U32 uint32; - U64 uint64; - I int; - U uint; - Fl float; - Fl32 float32; - Fl64 float64; - A []string; - My *myStruct; - Map map[string][]int; - MapStruct map[string]myStruct; - MapPtrStruct map[string]*myStruct; + T bool + F bool + S string + I8 int8 + I16 int16 + I32 int32 + I64 int64 + U8 uint8 + U16 uint16 + U32 uint32 + U64 uint64 + I int + U uint + Fl float + Fl32 float32 + Fl64 float64 + A []string + My *myStruct + Map map[string][]int + MapStruct map[string]myStruct + MapPtrStruct map[string]*myStruct } const encoded = `{"t":true,"f":false,"s":"abc","i8":1,"i16":2,"i32":3,"i64":4,` + @@ -69,58 +69,58 @@ func check(t *testing.T, ok bool, name string, v interface{}) { const whiteSpaceEncoded = " \t{\n\"s\"\r:\"string\"\v}" func TestUnmarshalWhitespace(t *testing.T) { - var m myStruct; - ok, errtok := Unmarshal(whiteSpaceEncoded, &m); + var m myStruct + ok, errtok := Unmarshal(whiteSpaceEncoded, &m) if !ok { t.Fatalf("Unmarshal failed near %s", errtok) } - check(t, m.S == "string", "string", m.S); + check(t, m.S == "string", "string", m.S) } func TestUnmarshal(t *testing.T) { - var m myStruct; - m.F = true; - ok, errtok := Unmarshal(encoded, &m); + var m myStruct + m.F = true + ok, errtok := Unmarshal(encoded, &m) if !ok { t.Fatalf("Unmarshal failed near %s", errtok) } - check(t, m.T == true, "t", m.T); - check(t, m.F == false, "f", m.F); - check(t, m.S == "abc", "s", m.S); - check(t, m.I8 == 1, "i8", m.I8); - check(t, m.I16 == 2, "i16", m.I16); - check(t, m.I32 == 3, "i32", m.I32); - check(t, m.I64 == 4, "i64", m.I64); - check(t, m.U8 == 5, "u8", m.U8); - check(t, m.U16 == 6, "u16", m.U16); - check(t, m.U32 == 7, "u32", m.U32); - check(t, m.U64 == 8, "u64", m.U64); - check(t, m.I == -9, "i", m.I); - check(t, m.U == 10, "u", m.U); - check(t, m.Fl == 11.5, "fl", m.Fl); - check(t, m.Fl32 == 12.25, "fl32", m.Fl32); - check(t, m.Fl64 == 13.75, "fl64", m.Fl64); - check(t, m.A != nil, "a", m.A); + check(t, m.T == true, "t", m.T) + check(t, m.F == false, "f", m.F) + check(t, m.S == "abc", "s", m.S) + check(t, m.I8 == 1, "i8", m.I8) + check(t, m.I16 == 2, "i16", m.I16) + check(t, m.I32 == 3, "i32", m.I32) + check(t, m.I64 == 4, "i64", m.I64) + check(t, m.U8 == 5, "u8", m.U8) + check(t, m.U16 == 6, "u16", m.U16) + check(t, m.U32 == 7, "u32", m.U32) + check(t, m.U64 == 8, "u64", m.U64) + check(t, m.I == -9, "i", m.I) + check(t, m.U == 10, "u", m.U) + check(t, m.Fl == 11.5, "fl", m.Fl) + check(t, m.Fl32 == 12.25, "fl32", m.Fl32) + check(t, m.Fl64 == 13.75, "fl64", m.Fl64) + check(t, m.A != nil, "a", m.A) if m.A != nil { - check(t, m.A[0] == "x", "a[0]", m.A[0]); - check(t, m.A[1] == "y", "a[1]", m.A[1]); - check(t, m.A[2] == "z", "a[2]", m.A[2]); + check(t, m.A[0] == "x", "a[0]", m.A[0]) + check(t, m.A[1] == "y", "a[1]", m.A[1]) + check(t, m.A[2] == "z", "a[2]", m.A[2]) } - check(t, m.My != nil, "my", m.My); + check(t, m.My != nil, "my", m.My) if m.My != nil { check(t, m.My.S == "subguy", "my.s", m.My.S) } - check(t, reflect.DeepEqual(m.Map, decodedMap), "map", m.Map); - check(t, reflect.DeepEqual(m.MapStruct, decodedMapStruct), "mapstruct", m.MapStruct); - check(t, reflect.DeepEqual(m.MapPtrStruct, decodedMapPtrStruct), "mapptrstruct", m.MapPtrStruct); + check(t, reflect.DeepEqual(m.Map, decodedMap), "map", m.Map) + check(t, reflect.DeepEqual(m.MapStruct, decodedMapStruct), "mapstruct", m.MapStruct) + check(t, reflect.DeepEqual(m.MapPtrStruct, decodedMapPtrStruct), "mapptrstruct", m.MapPtrStruct) } type Issue147Text struct { - Text string; + Text string } type Issue147 struct { - Test []Issue147Text; + Test []Issue147Text } const issue147Input = `{"test": [{"text":"0"},{"text":"1"},{"text":"2"}, @@ -135,8 +135,8 @@ const issue147Input = `{"test": [{"text":"0"},{"text":"1"},{"text":"2"}, {"text":"27"},{"text":"28"},{"text":"29"}]}` func TestIssue147(t *testing.T) { - var timeline Issue147; - Unmarshal(issue147Input, &timeline); + var timeline Issue147 + Unmarshal(issue147Input, &timeline) if len(timeline.Test) != 30 { t.Errorf("wrong length: got %d want 30", len(timeline.Test)) @@ -150,14 +150,14 @@ func TestIssue147(t *testing.T) { } type Issue114 struct { - Text string; + Text string } const issue114Input = `[{"text" : "0"}, {"text" : "1"}, {"text" : "2"}, {"text" : "3"}]` func TestIssue114(t *testing.T) { - var items []Issue114; - Unmarshal(issue114Input, &items); + var items []Issue114 + Unmarshal(issue114Input, &items) if len(items) != 4 { t.Errorf("wrong length: got %d want 4", len(items)) @@ -171,8 +171,8 @@ func TestIssue114(t *testing.T) { } type marshalTest struct { - val interface{}; - out string; + val interface{} + out string } var marshalTests = []marshalTest{ @@ -195,8 +195,8 @@ var marshalTests = []marshalTest{ marshalTest{struct{ a int }{1}, `{"a":1}`}, marshalTest{struct{ a interface{} }{nil}, `{"a":null}`}, marshalTest{struct { - a int; - b string; + a int + b string }{1, "hello"}, `{"a":1,"b":"hello"}`, }, @@ -205,14 +205,14 @@ var marshalTests = []marshalTest{ func TestMarshal(t *testing.T) { for _, tt := range marshalTests { - var buf bytes.Buffer; + var buf bytes.Buffer - err := Marshal(&buf, tt.val); + err := Marshal(&buf, tt.val) if err != nil { t.Fatalf("Marshal(%T): %s", tt.val, err) } - s := buf.String(); + s := buf.String() if s != tt.out { t.Errorf("Marshal(%T) = %q, want %q\n", tt.val, tt.out, s) } @@ -220,8 +220,8 @@ func TestMarshal(t *testing.T) { } type marshalErrorTest struct { - val interface{}; - error string; + val interface{} + error string } type MTE string @@ -233,9 +233,9 @@ var marshalErrorTests = []marshalErrorTest{ func TestMarshalError(t *testing.T) { for _, tt := range marshalErrorTests { - var buf bytes.Buffer; + var buf bytes.Buffer - err := Marshal(&buf, tt.val); + err := Marshal(&buf, tt.val) if err == nil { t.Fatalf("Marshal(%T): no error, want error %s", tt.val, tt.error) diff --git a/src/pkg/log/log.go b/src/pkg/log/log.go index 2beb99c3d..ac996a38d 100644 --- a/src/pkg/log/log.go +++ b/src/pkg/log/log.go @@ -12,37 +12,37 @@ package log import ( - "fmt"; - "io"; - "runtime"; - "os"; - "time"; + "fmt" + "io" + "runtime" + "os" + "time" ) // These flags define the properties of the Logger and the output they produce. const ( // Flags - Lok = iota; - Lexit; // terminate execution when written - Lcrash; // crash (panic) when written + Lok = iota + Lexit // terminate execution when written + Lcrash // crash (panic) when written // Bits or'ed together to control what's printed. There is no control over the // order they appear (the order listed here) or the format they present (as // described in the comments). A colon appears after these items: // 2009/0123 01:23:23.123123 /a/b/c/d.go:23: message - Ldate = 1 << iota; // the date: 2009/0123 - Ltime; // the time: 01:23:23 - Lmicroseconds; // microsecond resolution: 01:23:23.123123. assumes Ltime. - Llongfile; // full file name and line number: /a/b/c/d.go:23 - Lshortfile; // final file name element and line number: d.go:23. overrides Llongfile - lAllBits = Ldate | Ltime | Lmicroseconds | Llongfile | Lshortfile; + Ldate = 1 << iota // the date: 2009/0123 + Ltime // the time: 01:23:23 + Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime. + Llongfile // full file name and line number: /a/b/c/d.go:23 + Lshortfile // final file name element and line number: d.go:23. overrides Llongfile + lAllBits = Ldate | Ltime | Lmicroseconds | Llongfile | Lshortfile ) // Logger represents an active logging object. type Logger struct { - out0 io.Writer; // first destination for output - out1 io.Writer; // second destination for output; may be nil - prefix string; // prefix to write at beginning of each line - flag int; // properties + out0 io.Writer // first destination for output + out1 io.Writer // second destination for output; may be nil + prefix string // prefix to write at beginning of each line + flag int // properties } // New creates a new Logger. The out0 and out1 variables set the @@ -54,87 +54,87 @@ func New(out0, out1 io.Writer, prefix string, flag int) *Logger { } var ( - stdout = New(os.Stdout, nil, "", Lok|Ldate|Ltime); - stderr = New(os.Stderr, nil, "", Lok|Ldate|Ltime); - exit = New(os.Stderr, nil, "", Lexit|Ldate|Ltime); - crash = New(os.Stderr, nil, "", Lcrash|Ldate|Ltime); + stdout = New(os.Stdout, nil, "", Lok|Ldate|Ltime) + stderr = New(os.Stderr, nil, "", Lok|Ldate|Ltime) + exit = New(os.Stderr, nil, "", Lexit|Ldate|Ltime) + crash = New(os.Stderr, nil, "", Lcrash|Ldate|Ltime) ) -var shortnames = make(map[string]string) // cache of short names to avoid allocation. +var shortnames = make(map[string]string) // cache of short names to avoid allocation. // Cheap integer to fixed-width decimal ASCII. Use a negative width to avoid zero-padding func itoa(i int, wid int) string { - var u uint = uint(i); + var u uint = uint(i) if u == 0 && wid <= 1 { return "0" } // Assemble decimal in reverse order. - var b [32]byte; - bp := len(b); + var b [32]byte + bp := len(b) for ; u > 0 || wid > 0; u /= 10 { - bp--; - wid--; - b[bp] = byte(u%10) + '0'; + bp-- + wid-- + b[bp] = byte(u%10) + '0' } - return string(b[bp:]); + return string(b[bp:]) } func (l *Logger) formatHeader(ns int64, calldepth int) string { - h := l.prefix; + h := l.prefix if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 { - t := time.SecondsToLocalTime(ns / 1e9); + t := time.SecondsToLocalTime(ns / 1e9) if l.flag&(Ldate) != 0 { h += itoa(int(t.Year), 4) + "/" + itoa(t.Month, 2) + "/" + itoa(t.Day, 2) + " " } if l.flag&(Ltime|Lmicroseconds) != 0 { - h += itoa(t.Hour, 2) + ":" + itoa(t.Minute, 2) + ":" + itoa(t.Second, 2); + h += itoa(t.Hour, 2) + ":" + itoa(t.Minute, 2) + ":" + itoa(t.Second, 2) if l.flag&Lmicroseconds != 0 { h += "." + itoa(int(ns%1e9)/1e3, 6) } - h += " "; + h += " " } } if l.flag&(Lshortfile|Llongfile) != 0 { - _, file, line, ok := runtime.Caller(calldepth); + _, file, line, ok := runtime.Caller(calldepth) if ok { if l.flag&Lshortfile != 0 { - short, ok := shortnames[file]; + short, ok := shortnames[file] if !ok { - short = file; + short = file for i := len(file) - 1; i > 0; i-- { if file[i] == '/' { - short = file[i+1:]; - break; + short = file[i+1:] + break } } - shortnames[file] = short; + shortnames[file] = short } - file = short; + file = short } } else { - file = "???"; - line = 0; + file = "???" + line = 0 } - h += file + ":" + itoa(line, -1) + ": "; + h += file + ":" + itoa(line, -1) + ": " } - return h; + return h } // Output writes the output for a logging event. The string s contains the text to print after // the time stamp; calldepth is used to recover the PC. It is provided for generality, although // at the moment on all pre-defined paths it will be 2. func (l *Logger) Output(calldepth int, s string) os.Error { - now := time.Nanoseconds(); // get this early. - newline := "\n"; + now := time.Nanoseconds() // get this early. + newline := "\n" if len(s) > 0 && s[len(s)-1] == '\n' { newline = "" } - s = l.formatHeader(now, calldepth+1) + s + newline; - _, err := io.WriteString(l.out0, s); + s = l.formatHeader(now, calldepth+1) + s + newline + _, err := io.WriteString(l.out0, s) if l.out1 != nil { - _, err1 := io.WriteString(l.out1, s); + _, err1 := io.WriteString(l.out1, s) if err == nil && err1 != nil { err = err1 } @@ -145,35 +145,35 @@ func (l *Logger) Output(calldepth int, s string) os.Error { case Lexit: os.Exit(1) } - return err; + return err } // Logf is analogous to Printf() for a Logger. -func (l *Logger) Logf(format string, v ...) { l.Output(2, fmt.Sprintf(format, v)) } +func (l *Logger) Logf(format string, v ...) { l.Output(2, fmt.Sprintf(format, v)) } // Log is analogous to Print() for a Logger. -func (l *Logger) Log(v ...) { l.Output(2, fmt.Sprintln(v)) } +func (l *Logger) Log(v ...) { l.Output(2, fmt.Sprintln(v)) } // Stdout is a helper function for easy logging to stdout. It is analogous to Print(). -func Stdout(v ...) { stdout.Output(2, fmt.Sprint(v)) } +func Stdout(v ...) { stdout.Output(2, fmt.Sprint(v)) } // Stderr is a helper function for easy logging to stderr. It is analogous to Fprint(os.Stderr). -func Stderr(v ...) { stderr.Output(2, fmt.Sprintln(v)) } +func Stderr(v ...) { stderr.Output(2, fmt.Sprintln(v)) } // Stdoutf is a helper functions for easy formatted logging to stdout. It is analogous to Printf(). -func Stdoutf(format string, v ...) { stdout.Output(2, fmt.Sprintf(format, v)) } +func Stdoutf(format string, v ...) { stdout.Output(2, fmt.Sprintf(format, v)) } // Stderrf is a helper function for easy formatted logging to stderr. It is analogous to Fprintf(os.Stderr). -func Stderrf(format string, v ...) { stderr.Output(2, fmt.Sprintf(format, v)) } +func Stderrf(format string, v ...) { stderr.Output(2, fmt.Sprintf(format, v)) } // Exit is equivalent to Stderr() followed by a call to os.Exit(1). -func Exit(v ...) { exit.Output(2, fmt.Sprintln(v)) } +func Exit(v ...) { exit.Output(2, fmt.Sprintln(v)) } // Exitf is equivalent to Stderrf() followed by a call to os.Exit(1). -func Exitf(format string, v ...) { exit.Output(2, fmt.Sprintf(format, v)) } +func Exitf(format string, v ...) { exit.Output(2, fmt.Sprintf(format, v)) } // Crash is equivalent to Stderr() followed by a call to panic(). -func Crash(v ...) { crash.Output(2, fmt.Sprintln(v)) } +func Crash(v ...) { crash.Output(2, fmt.Sprintln(v)) } // Crashf is equivalent to Stderrf() followed by a call to panic(). -func Crashf(format string, v ...) { crash.Output(2, fmt.Sprintf(format, v)) } +func Crashf(format string, v ...) { crash.Output(2, fmt.Sprintf(format, v)) } diff --git a/src/pkg/log/log_test.go b/src/pkg/log/log_test.go index caef8b134..fd0b36c6e 100644 --- a/src/pkg/log/log_test.go +++ b/src/pkg/log/log_test.go @@ -7,25 +7,25 @@ package log // These tests are too simple. import ( - "bufio"; - "os"; - "regexp"; - "testing"; + "bufio" + "os" + "regexp" + "testing" ) const ( - Rdate = `[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]`; - Rtime = `[0-9][0-9]:[0-9][0-9]:[0-9][0-9]`; - Rmicroseconds = `\.[0-9][0-9][0-9][0-9][0-9][0-9]`; - Rline = `[0-9]+:`; - Rlongfile = `.*/[A-Za-z0-9_\-]+\.go:` + Rline; - Rshortfile = `[A-Za-z0-9_\-]+\.go:` + Rline; + Rdate = `[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]` + Rtime = `[0-9][0-9]:[0-9][0-9]:[0-9][0-9]` + Rmicroseconds = `\.[0-9][0-9][0-9][0-9][0-9][0-9]` + Rline = `[0-9]+:` + Rlongfile = `.*/[A-Za-z0-9_\-]+\.go:` + Rline + Rshortfile = `[A-Za-z0-9_\-]+\.go:` + Rline ) type tester struct { - flag int; - prefix string; - pattern string; // regexp that log output must match; we add ^ and expected_text$ always + flag int + prefix string + pattern string // regexp that log output must match; we add ^ and expected_text$ always } var tests = []tester{ @@ -35,10 +35,10 @@ var tests = []tester{ tester{Lok | Ldate, "", Rdate + " "}, tester{Lok | Ltime, "", Rtime + " "}, tester{Lok | Ltime | Lmicroseconds, "", Rtime + Rmicroseconds + " "}, - tester{Lok | Lmicroseconds, "", Rtime + Rmicroseconds + " "}, // microsec implies time + tester{Lok | Lmicroseconds, "", Rtime + Rmicroseconds + " "}, // microsec implies time tester{Lok | Llongfile, "", Rlongfile + " "}, tester{Lok | Lshortfile, "", Rshortfile + " "}, - tester{Lok | Llongfile | Lshortfile, "", Rshortfile + " "}, // shortfile overrides longfile + tester{Lok | Llongfile | Lshortfile, "", Rshortfile + " "}, // shortfile overrides longfile // everything at once: tester{Lok | Ldate | Ltime | Lmicroseconds | Llongfile, "XXX", "XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rlongfile + " "}, tester{Lok | Ldate | Ltime | Lmicroseconds | Lshortfile, "XXX", "XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rshortfile + " "}, @@ -46,26 +46,26 @@ var tests = []tester{ // Test using Log("hello", 23, "world") or using Logf("hello %d world", 23) func testLog(t *testing.T, flag int, prefix string, pattern string, useLogf bool) { - r, w, err1 := os.Pipe(); + r, w, err1 := os.Pipe() if err1 != nil { t.Fatal("pipe", err1) } - defer r.Close(); - defer w.Close(); - buf := bufio.NewReader(r); - l := New(w, nil, prefix, flag); + defer r.Close() + defer w.Close() + buf := bufio.NewReader(r) + l := New(w, nil, prefix, flag) if useLogf { l.Logf("hello %d world", 23) } else { l.Log("hello", 23, "world") } - line, err3 := buf.ReadString('\n'); + line, err3 := buf.ReadString('\n') if err3 != nil { t.Fatal("log error", err3) } - line = line[0 : len(line)-1]; - pattern = "^" + pattern + "hello 23 world$"; - matched, err4 := regexp.MatchString(pattern, line); + line = line[0 : len(line)-1] + pattern = "^" + pattern + "hello 23 world$" + matched, err4 := regexp.MatchString(pattern, line) if err4 != nil { t.Fatal("pattern did not compile:", err4) } @@ -76,7 +76,7 @@ func testLog(t *testing.T, flag int, prefix string, pattern string, useLogf bool func TestAllLog(t *testing.T) { for _, testcase := range tests { - testLog(t, testcase.flag, testcase.prefix, testcase.pattern, false); - testLog(t, testcase.flag, testcase.prefix, testcase.pattern, true); + testLog(t, testcase.flag, testcase.prefix, testcase.pattern, false) + testLog(t, testcase.flag, testcase.prefix, testcase.pattern, true) } } diff --git a/src/pkg/malloc/malloc.go b/src/pkg/malloc/malloc.go index ba15f04ab..c66b6237d 100644 --- a/src/pkg/malloc/malloc.go +++ b/src/pkg/malloc/malloc.go @@ -12,14 +12,14 @@ package malloc type Stats struct { - Alloc uint64; - Sys uint64; - Stacks uint64; - InusePages uint64; - NextGC uint64; - Lookups uint64; - Mallocs uint64; - EnableGC bool; + Alloc uint64 + Sys uint64 + Stacks uint64 + InusePages uint64 + NextGC uint64 + Lookups uint64 + Mallocs uint64 + EnableGC bool } func Alloc(uintptr) *byte diff --git a/src/pkg/math/all_test.go b/src/pkg/math/all_test.go index 60ce6de24..6feddac93 100644 --- a/src/pkg/math/all_test.go +++ b/src/pkg/math/all_test.go @@ -5,9 +5,9 @@ package math_test import ( - "fmt"; - . "math"; - "testing"; + "fmt" + . "math" + "testing" ) var vf = []float64{ @@ -156,22 +156,22 @@ var tanh = []float64{ } func tolerance(a, b, e float64) bool { - d := a - b; + d := a - b if d < 0 { d = -d } if a != 0 { - e = e * a; + e = e * a if e < 0 { e = -e } } - return d < e; + return d < e } -func kindaclose(a, b float64) bool { return tolerance(a, b, 1e-8) } -func close(a, b float64) bool { return tolerance(a, b, 1e-14) } -func veryclose(a, b float64) bool { return tolerance(a, b, 4e-16) } +func kindaclose(a, b float64) bool { return tolerance(a, b, 1e-8) } +func close(a, b float64) bool { return tolerance(a, b, 1e-14) } +func veryclose(a, b float64) bool { return tolerance(a, b, 4e-16) } func TestAsin(t *testing.T) { for i := 0; i < len(vf); i++ { @@ -207,7 +207,7 @@ func TestFloor(t *testing.T) { func TestLog(t *testing.T) { for i := 0; i < len(vf); i++ { - a := Fabs(vf[i]); + a := Fabs(vf[i]) if f := Log(a); log[i] != f { t.Errorf("Log(%g) = %g, want %g\n", a, f, log[i]) } @@ -243,7 +243,7 @@ func TestSinh(t *testing.T) { func TestSqrt(t *testing.T) { for i := 0; i < len(vf); i++ { - a := Fabs(vf[i]); + a := Fabs(vf[i]) if f := Sqrt(a); !veryclose(sqrt[i], f) { t.Errorf("Sqrt(%g) = %g, want %g\n", a, f, floor[i]) } @@ -268,7 +268,7 @@ func TestTanh(t *testing.T) { func TestHypot(t *testing.T) { for i := 0; i < len(vf); i++ { - a := Fabs(tanh[i] * Sqrt(2)); + a := Fabs(tanh[i] * Sqrt(2)) if f := Hypot(tanh[i], tanh[i]); !veryclose(a, f) { t.Errorf("Hypot(%g, %g) = %g, want %g\n", tanh[i], tanh[i], f, a) } @@ -278,10 +278,10 @@ func TestHypot(t *testing.T) { // Check that math functions of high angle values // return similar results to low angle values func TestLargeSin(t *testing.T) { - large := float64(100000 * Pi); + large := float64(100000 * Pi) for i := 0; i < len(vf); i++ { - f1 := Sin(vf[i]); - f2 := Sin(vf[i] + large); + f1 := Sin(vf[i]) + f2 := Sin(vf[i] + large) if !kindaclose(f1, f2) { t.Errorf("Sin(%g) = %g, want %g\n", vf[i]+large, f1, f2) } @@ -289,10 +289,10 @@ func TestLargeSin(t *testing.T) { } func TestLargeCos(t *testing.T) { - large := float64(100000 * Pi); + large := float64(100000 * Pi) for i := 0; i < len(vf); i++ { - f1 := Cos(vf[i]); - f2 := Cos(vf[i] + large); + f1 := Cos(vf[i]) + f2 := Cos(vf[i] + large) if !kindaclose(f1, f2) { t.Errorf("Cos(%g) = %g, want %g\n", vf[i]+large, f1, f2) } @@ -301,10 +301,10 @@ func TestLargeCos(t *testing.T) { func TestLargeTan(t *testing.T) { - large := float64(100000 * Pi); + large := float64(100000 * Pi) for i := 0; i < len(vf); i++ { - f1 := Tan(vf[i]); - f2 := Tan(vf[i] + large); + f1 := Tan(vf[i]) + f2 := Tan(vf[i] + large) if !kindaclose(f1, f2) { t.Errorf("Tan(%g) = %g, want %g\n", vf[i]+large, f1, f2) } @@ -316,9 +316,9 @@ func TestLargeTan(t *testing.T) { // http://code.google.com/p/go/issues/detail?id=201 type floatTest struct { - val interface{}; - name string; - str string; + val interface{} + name string + str string } var floatTests = []floatTest{ @@ -330,7 +330,7 @@ var floatTests = []floatTest{ func TestFloatMinMax(t *testing.T) { for _, tt := range floatTests { - s := fmt.Sprint(tt.val); + s := fmt.Sprint(tt.val) if s != tt.str { t.Errorf("Sprint(%v) = %s, want %s", tt.name, s, tt.str) } diff --git a/src/pkg/math/asin.go b/src/pkg/math/asin.go index 3ba36abf5..a138aac06 100644 --- a/src/pkg/math/asin.go +++ b/src/pkg/math/asin.go @@ -14,16 +14,16 @@ package math // Asin returns the arc sine of x. func Asin(x float64) float64 { - sign := false; + sign := false if x < 0 { - x = -x; - sign = true; + x = -x + sign = true } if x > 1 { return NaN() } - temp := Sqrt(1 - x*x); + temp := Sqrt(1 - x*x) if x > 0.7 { temp = Pi/2 - Atan(temp/x) } else { @@ -33,7 +33,7 @@ func Asin(x float64) float64 { if sign { temp = -temp } - return temp; + return temp } // Acos returns the arc cosine of x. @@ -41,5 +41,5 @@ func Acos(x float64) float64 { if x > 1 || x < -1 { return NaN() } - return Pi/2 - Asin(x); + return Pi/2 - Asin(x) } diff --git a/src/pkg/math/atan.go b/src/pkg/math/atan.go index 4f0ad9bf0..c811a39d9 100644 --- a/src/pkg/math/atan.go +++ b/src/pkg/math/atan.go @@ -20,21 +20,21 @@ package math */ func xatan(arg float64) float64 { const ( - P4 = .161536412982230228262e2; - P3 = .26842548195503973794141e3; - P2 = .11530293515404850115428136e4; - P1 = .178040631643319697105464587e4; - P0 = .89678597403663861959987488e3; - Q4 = .5895697050844462222791e2; - Q3 = .536265374031215315104235e3; - Q2 = .16667838148816337184521798e4; - Q1 = .207933497444540981287275926e4; - Q0 = .89678597403663861962481162e3; + P4 = .161536412982230228262e2 + P3 = .26842548195503973794141e3 + P2 = .11530293515404850115428136e4 + P1 = .178040631643319697105464587e4 + P0 = .89678597403663861959987488e3 + Q4 = .5895697050844462222791e2 + Q3 = .536265374031215315104235e3 + Q2 = .16667838148816337184521798e4 + Q1 = .207933497444540981287275926e4 + Q0 = .89678597403663861962481162e3 ) - sq := arg * arg; - value := ((((P4*sq+P3)*sq+P2)*sq+P1)*sq + P0); - value = value / (((((sq+Q4)*sq+Q3)*sq+Q2)*sq+Q1)*sq + Q0); - return value * arg; + sq := arg * arg + value := ((((P4*sq+P3)*sq+P2)*sq+P1)*sq + P0) + value = value / (((((sq+Q4)*sq+Q3)*sq+Q2)*sq+Q1)*sq + Q0) + return value * arg } /* @@ -48,7 +48,7 @@ func satan(arg float64) float64 { if arg > Sqrt2+1 { return Pi/2 - xatan(1/arg) } - return Pi/4 + xatan((arg-1)/(arg+1)); + return Pi/4 + xatan((arg-1)/(arg+1)) } /* @@ -61,5 +61,5 @@ func Atan(x float64) float64 { if x > 0 { return satan(x) } - return -satan(-x); + return -satan(-x) } diff --git a/src/pkg/math/atan2.go b/src/pkg/math/atan2.go index 26d3a1d68..80a28b15b 100644 --- a/src/pkg/math/atan2.go +++ b/src/pkg/math/atan2.go @@ -13,14 +13,14 @@ func Atan2(y, x float64) float64 { if y >= 0 { return Pi / 2 } - return -Pi / 2; + return -Pi / 2 } - q := Atan(y / x); + q := Atan(y / x) if x < 0 { if q <= 0 { return q + Pi } - return q - Pi; + return q - Pi } - return q; + return q } diff --git a/src/pkg/math/bits.go b/src/pkg/math/bits.go index 5372c6806..65eabfd60 100644 --- a/src/pkg/math/bits.go +++ b/src/pkg/math/bits.go @@ -5,32 +5,32 @@ package math const ( - uvnan = 0x7FF0000000000001; - uvinf = 0x7FF0000000000000; - uvneginf = 0xFFF0000000000000; - mask = 0x7FF; - shift = 64 - 11 - 1; - bias = 1022; + uvnan = 0x7FF0000000000001 + uvinf = 0x7FF0000000000000 + uvneginf = 0xFFF0000000000000 + mask = 0x7FF + shift = 64 - 11 - 1 + bias = 1022 ) // Inf returns positive infinity if sign >= 0, negative infinity if sign < 0. func Inf(sign int) float64 { - var v uint64; + var v uint64 if sign >= 0 { v = uvinf } else { v = uvneginf } - return Float64frombits(v); + return Float64frombits(v) } // NaN returns an IEEE 754 ``not-a-number'' value. -func NaN() float64 { return Float64frombits(uvnan) } +func NaN() float64 { return Float64frombits(uvnan) } // IsNaN returns whether f is an IEEE 754 ``not-a-number'' value. func IsNaN(f float64) (is bool) { - x := Float64bits(f); - return uint32(x>>shift)&mask == mask && x != uvinf && x != uvneginf; + x := Float64bits(f) + return uint32(x>>shift)&mask == mask && x != uvinf && x != uvneginf } // IsInf returns whether f is an infinity, according to sign. @@ -38,8 +38,8 @@ func IsNaN(f float64) (is bool) { // If sign < 0, IsInf returns whether f is negative infinity. // If sign == 0, IsInf returns whether f is either infinity. func IsInf(f float64, sign int) bool { - x := Float64bits(f); - return sign >= 0 && x == uvinf || sign <= 0 && x == uvneginf; + x := Float64bits(f) + return sign >= 0 && x == uvinf || sign <= 0 && x == uvneginf } // Frexp breaks f into a normalized fraction @@ -50,31 +50,31 @@ func Frexp(f float64) (frac float64, exp int) { if f == 0 { return } - x := Float64bits(f); - exp = int((x>>shift)&mask) - bias; - x &^= mask << shift; - x |= bias << shift; - frac = Float64frombits(x); - return; + x := Float64bits(f) + exp = int((x>>shift)&mask) - bias + x &^= mask << shift + x |= bias << shift + frac = Float64frombits(x) + return } // Ldexp is the inverse of Frexp. // It returns frac × 2<sup>exp</sup>. func Ldexp(frac float64, exp int) float64 { - x := Float64bits(frac); - exp += int(x>>shift) & mask; + x := Float64bits(frac) + exp += int(x>>shift) & mask if exp <= 0 { - return 0 // underflow + return 0 // underflow } - if exp >= mask { // overflow + if exp >= mask { // overflow if frac < 0 { return Inf(-1) } - return Inf(1); + return Inf(1) } - x &^= mask << shift; - x |= uint64(exp) << shift; - return Float64frombits(x); + x &^= mask << shift + x |= uint64(exp) << shift + return Float64frombits(x) } // Modf returns integer and fractional floating-point numbers @@ -83,20 +83,20 @@ func Ldexp(frac float64, exp int) float64 { func Modf(f float64) (int float64, frac float64) { if f < 1 { if f < 0 { - int, frac = Modf(-f); - return -int, -frac; + int, frac = Modf(-f) + return -int, -frac } - return 0, f; + return 0, f } - x := Float64bits(f); - e := uint(x>>shift)&mask - bias; + x := Float64bits(f) + e := uint(x>>shift)&mask - bias // Keep the top 11+e bits, the integer part; clear the rest. if e < 64-11 { x &^= 1<<(64-11-e) - 1 } - int = Float64frombits(x); - frac = f - int; - return; + int = Float64frombits(x) + frac = f - int + return } diff --git a/src/pkg/math/const.go b/src/pkg/math/const.go index 68ecefaa9..965a440be 100644 --- a/src/pkg/math/const.go +++ b/src/pkg/math/const.go @@ -8,46 +8,46 @@ package math // Mathematical constants. // Reference: http://www.research.att.com/~njas/sequences/Axxxxxx const ( - E = 2.71828182845904523536028747135266249775724709369995957496696763; // A001113 - Pi = 3.14159265358979323846264338327950288419716939937510582097494459; // A000796 - Phi = 1.61803398874989484820458683436563811772030917980576286213544862; // A001622 - - Sqrt2 = 1.41421356237309504880168872420969807856967187537694807317667974; // A002193 - SqrtE = 1.64872127070012814684865078781416357165377610071014801157507931; // A019774 - SqrtPi = 1.77245385090551602729816748334114518279754945612238712821380779; // A002161 - SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038; // A139339 - - Ln2 = 0.693147180559945309417232121458176568075500134360255254120680009; // A002162 - Log2E = 1 / Ln2; - Ln10 = 2.30258509299404568401799145468436420760110148862877297603332790; // A002392 - Log10E = 1 / Ln10; + E = 2.71828182845904523536028747135266249775724709369995957496696763 // A001113 + Pi = 3.14159265358979323846264338327950288419716939937510582097494459 // A000796 + Phi = 1.61803398874989484820458683436563811772030917980576286213544862 // A001622 + + Sqrt2 = 1.41421356237309504880168872420969807856967187537694807317667974 // A002193 + SqrtE = 1.64872127070012814684865078781416357165377610071014801157507931 // A019774 + SqrtPi = 1.77245385090551602729816748334114518279754945612238712821380779 // A002161 + SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038 // A139339 + + Ln2 = 0.693147180559945309417232121458176568075500134360255254120680009 // A002162 + Log2E = 1 / Ln2 + Ln10 = 2.30258509299404568401799145468436420760110148862877297603332790 // A002392 + Log10E = 1 / Ln10 ) // Floating-point limit values. // Max is the largest finite value representable by the type. // Min is the smallest nonzero value representable by the type. const ( - MaxFloat32 = 3.40282346638528859811704183484516925440e+38; /* 2^127 * (2^24 - 1) / 2^23 */ - MinFloat32 = 1.401298464324817070923729583289916131280e-45; /* 1 / 2^(127 - 1 + 23) */ + MaxFloat32 = 3.40282346638528859811704183484516925440e+38 /* 2^127 * (2^24 - 1) / 2^23 */ + MinFloat32 = 1.401298464324817070923729583289916131280e-45 /* 1 / 2^(127 - 1 + 23) */ - MaxFloat64 = 1.797693134862315708145274237317043567981e+308; /* 2^1023 * (2^53 - 1) / 2^52 */ - MinFloat64 = 4.940656458412465441765687928682213723651e-324; /* 1 / 2^(1023 - 1 + 52) */ + MaxFloat64 = 1.797693134862315708145274237317043567981e+308 /* 2^1023 * (2^53 - 1) / 2^52 */ + MinFloat64 = 4.940656458412465441765687928682213723651e-324 /* 1 / 2^(1023 - 1 + 52) */ ) // Integer limit values. const ( - MaxInt8 = 1<<7 - 1; - MinInt8 = -1 << 7; - MaxInt16 = 1<<15 - 1; - MinInt16 = -1 << 15; - MaxInt32 = 1<<31 - 1; - MinInt32 = -1 << 31; - MaxInt64 = 1<<63 - 1; - MinInt64 = -1 << 63; - MaxUint8 = 1<<8 - 1; - MaxUint16 = 1<<16 - 1; - MaxUint32 = 1<<32 - 1; - MaxUint64 = 1<<64 - 1; + MaxInt8 = 1<<7 - 1 + MinInt8 = -1 << 7 + MaxInt16 = 1<<15 - 1 + MinInt16 = -1 << 15 + MaxInt32 = 1<<31 - 1 + MinInt32 = -1 << 31 + MaxInt64 = 1<<63 - 1 + MinInt64 = -1 << 63 + MaxUint8 = 1<<8 - 1 + MaxUint16 = 1<<16 - 1 + MaxUint32 = 1<<32 - 1 + MaxUint64 = 1<<64 - 1 ) // BUG(rsc): The manual should define the special cases for all of these functions. diff --git a/src/pkg/math/exp.go b/src/pkg/math/exp.go index cdee0d70a..9ad2b3877 100644 --- a/src/pkg/math/exp.go +++ b/src/pkg/math/exp.go @@ -90,18 +90,18 @@ package math // Very small values underflow to 1. func Exp(x float64) float64 { const ( - Ln2Hi = 6.93147180369123816490e-01; - Ln2Lo = 1.90821492927058770002e-10; - Log2e = 1.44269504088896338700e+00; - P1 = 1.66666666666666019037e-01; /* 0x3FC55555; 0x5555553E */ - P2 = -2.77777777770155933842e-03; /* 0xBF66C16C; 0x16BEBD93 */ - P3 = 6.61375632143793436117e-05; /* 0x3F11566A; 0xAF25DE2C */ - P4 = -1.65339022054652515390e-06; /* 0xBEBBBD41; 0xC5D26BF1 */ - P5 = 4.13813679705723846039e-08; /* 0x3E663769; 0x72BEA4D0 */ + Ln2Hi = 6.93147180369123816490e-01 + Ln2Lo = 1.90821492927058770002e-10 + Log2e = 1.44269504088896338700e+00 + P1 = 1.66666666666666019037e-01 /* 0x3FC55555; 0x5555553E */ + P2 = -2.77777777770155933842e-03 /* 0xBF66C16C; 0x16BEBD93 */ + P3 = 6.61375632143793436117e-05 /* 0x3F11566A; 0xAF25DE2C */ + P4 = -1.65339022054652515390e-06 /* 0xBEBBBD41; 0xC5D26BF1 */ + P5 = 4.13813679705723846039e-08 /* 0x3E663769; 0x72BEA4D0 */ - Overflow = 7.09782712893383973096e+02; - Underflow = -7.45133219101941108420e+02; - NearZero = 1.0 / (1 << 28); // 2^-28 + Overflow = 7.09782712893383973096e+02 + Underflow = -7.45133219101941108420e+02 + NearZero = 1.0 / (1 << 28) // 2^-28 ) // special cases @@ -119,21 +119,21 @@ func Exp(x float64) float64 { } // reduce; computed as r = hi - lo for extra precision. - var k int; + var k int switch { case x < 0: k = int(Log2e*x - 0.5) case x > 0: k = int(Log2e*x + 0.5) } - hi := x - float64(k)*Ln2Hi; - lo := float64(k) * Ln2Lo; - r := hi - lo; + hi := x - float64(k)*Ln2Hi + lo := float64(k) * Ln2Lo + r := hi - lo // compute - t := r * r; - c := r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))); - y := 1 - ((lo - (r*c)/(2-c)) - hi); + t := r * r + c := r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))) + y := 1 - ((lo - (r*c)/(2-c)) - hi) // TODO(rsc): make sure Ldexp can handle boundary k - return Ldexp(y, k); + return Ldexp(y, k) } diff --git a/src/pkg/math/fabs.go b/src/pkg/math/fabs.go index 752133e0c..ca78f3b59 100644 --- a/src/pkg/math/fabs.go +++ b/src/pkg/math/fabs.go @@ -9,5 +9,5 @@ func Fabs(x float64) float64 { if x < 0 { return -x } - return x; + return x } diff --git a/src/pkg/math/floor.go b/src/pkg/math/floor.go index 96532acbd..2acf1e042 100644 --- a/src/pkg/math/floor.go +++ b/src/pkg/math/floor.go @@ -8,15 +8,15 @@ package math // Floor returns the greatest integer value less than or equal to x. func Floor(x float64) float64 { if x < 0 { - d, fract := Modf(-x); + d, fract := Modf(-x) if fract != 0.0 { d = d + 1 } - return -d; + return -d } - d, _ := Modf(x); - return d; + d, _ := Modf(x) + return d } // Ceil returns the least integer value greater than or equal to x. -func Ceil(x float64) float64 { return -Floor(-x) } +func Ceil(x float64) float64 { return -Floor(-x) } diff --git a/src/pkg/math/fmod.go b/src/pkg/math/fmod.go index 9539b2ac1..d88ad5359 100644 --- a/src/pkg/math/fmod.go +++ b/src/pkg/math/fmod.go @@ -18,23 +18,23 @@ func Fmod(x, y float64) float64 { y = -y } - yfr, yexp := Frexp(y); - sign := false; - r := x; + yfr, yexp := Frexp(y) + sign := false + r := x if x < 0 { - r = -x; - sign = true; + r = -x + sign = true } for r >= y { - rfr, rexp := Frexp(r); + rfr, rexp := Frexp(r) if rfr < yfr { rexp = rexp - 1 } - r = r - Ldexp(y, rexp-yexp); + r = r - Ldexp(y, rexp-yexp) } if sign { r = -r } - return r; + return r } diff --git a/src/pkg/math/hypot.go b/src/pkg/math/hypot.go index 9585da4c5..4370c2295 100644 --- a/src/pkg/math/hypot.go +++ b/src/pkg/math/hypot.go @@ -30,20 +30,20 @@ func Hypot(p, q float64) float64 { return 0 } - pfac := p; - q = q / p; - r := q; - p = 1; + pfac := p + q = q / p + r := q + p = 1 for { - r = r * r; - s := r + 4; + r = r * r + s := r + 4 if s == 4 { return p * pfac } - r = r / s; - p = p + 2*r*p; - q = q * r; - r = q / p; + r = r / s + p = p + 2*r*p + q = q * r + r = q / p } - panic("unreachable"); + panic("unreachable") } diff --git a/src/pkg/math/log.go b/src/pkg/math/log.go index e92650131..0564689f4 100644 --- a/src/pkg/math/log.go +++ b/src/pkg/math/log.go @@ -76,15 +76,15 @@ package math // Log(NaN) = NaN func Log(x float64) float64 { const ( - Ln2Hi = 6.93147180369123816490e-01; /* 3fe62e42 fee00000 */ - Ln2Lo = 1.90821492927058770002e-10; /* 3dea39ef 35793c76 */ - L1 = 6.666666666666735130e-01; /* 3FE55555 55555593 */ - L2 = 3.999999999940941908e-01; /* 3FD99999 9997FA04 */ - L3 = 2.857142874366239149e-01; /* 3FD24924 94229359 */ - L4 = 2.222219843214978396e-01; /* 3FCC71C5 1D8E78AF */ - L5 = 1.818357216161805012e-01; /* 3FC74664 96CB03DE */ - L6 = 1.531383769920937332e-01; /* 3FC39A09 D078C69F */ - L7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ + Ln2Hi = 6.93147180369123816490e-01 /* 3fe62e42 fee00000 */ + Ln2Lo = 1.90821492927058770002e-10 /* 3dea39ef 35793c76 */ + L1 = 6.666666666666735130e-01 /* 3FE55555 55555593 */ + L2 = 3.999999999940941908e-01 /* 3FD99999 9997FA04 */ + L3 = 2.857142874366239149e-01 /* 3FD24924 94229359 */ + L4 = 2.222219843214978396e-01 /* 3FCC71C5 1D8E78AF */ + L5 = 1.818357216161805012e-01 /* 3FC74664 96CB03DE */ + L6 = 1.531383769920937332e-01 /* 3FC39A09 D078C69F */ + L7 = 1.479819860511658591e-01 /* 3FC2F112 DF3E5244 */ ) // special cases @@ -98,23 +98,23 @@ func Log(x float64) float64 { } // reduce - f1, ki := Frexp(x); + f1, ki := Frexp(x) if f1 < Sqrt2/2 { - f1 *= 2; - ki--; + f1 *= 2 + ki-- } - f := f1 - 1; - k := float64(ki); + f := f1 - 1 + k := float64(ki) // compute - s := f / (2 + f); - s2 := s * s; - s4 := s2 * s2; - t1 := s2 * (L1 + s4*(L3+s4*(L5+s4*L7))); - t2 := s4 * (L2 + s4*(L4+s4*L6)); - R := t1 + t2; - hfsq := 0.5 * f * f; - return k*Ln2Hi - ((hfsq - (s*(hfsq+R) + k*Ln2Lo)) - f); + s := f / (2 + f) + s2 := s * s + s4 := s2 * s2 + t1 := s2 * (L1 + s4*(L3+s4*(L5+s4*L7))) + t2 := s4 * (L2 + s4*(L4+s4*L6)) + R := t1 + t2 + hfsq := 0.5 * f * f + return k*Ln2Hi - ((hfsq - (s*(hfsq+R) + k*Ln2Lo)) - f) } // Log10 returns the decimal logarithm of x. @@ -123,5 +123,5 @@ func Log10(x float64) float64 { if x <= 0 { return NaN() } - return Log(x) * (1 / Ln10); + return Log(x) * (1 / Ln10) } diff --git a/src/pkg/math/pow.go b/src/pkg/math/pow.go index c91dc44ec..42a968d39 100644 --- a/src/pkg/math/pow.go +++ b/src/pkg/math/pow.go @@ -23,13 +23,13 @@ func Pow(x, y float64) float64 { return 1 / Sqrt(x) } - absy := y; - flip := false; + absy := y + flip := false if absy < 0 { - absy = -absy; - flip = true; + absy = -absy + flip = true } - yi, yf := Modf(absy); + yi, yf := Modf(absy) if yf != 0 && x < 0 { return NaN() } @@ -38,33 +38,33 @@ func Pow(x, y float64) float64 { } // ans = a1 * 2^ae (= 1 for now). - a1 := float64(1); - ae := 0; + a1 := float64(1) + ae := 0 // ans *= x^yf if yf != 0 { if yf > 0.5 { - yf--; - yi++; + yf-- + yi++ } - a1 = Exp(yf * Log(x)); + a1 = Exp(yf * Log(x)) } // ans *= x^yi // by multiplying in successive squarings // of x according to bits of yi. // accumulate powers of two into exp. - x1, xe := Frexp(x); + x1, xe := Frexp(x) for i := int64(yi); i != 0; i >>= 1 { if i&1 == 1 { - a1 *= x1; - ae += xe; + a1 *= x1 + ae += xe } - x1 *= x1; - xe <<= 1; + x1 *= x1 + xe <<= 1 if x1 < .5 { - x1 += x1; - xe--; + x1 += x1 + xe-- } } @@ -72,8 +72,8 @@ func Pow(x, y float64) float64 { // if flip { ans = 1 / ans } // but in the opposite order if flip { - a1 = 1 / a1; - ae = -ae; + a1 = 1 / a1 + ae = -ae } - return Ldexp(a1, ae); + return Ldexp(a1, ae) } diff --git a/src/pkg/math/pow10.go b/src/pkg/math/pow10.go index edba40a7b..99b318e78 100644 --- a/src/pkg/math/pow10.go +++ b/src/pkg/math/pow10.go @@ -23,15 +23,15 @@ func Pow10(e int) float64 { if e < len(pow10tab) { return pow10tab[e] } - m := e / 2; - return Pow10(m) * Pow10(e-m); + m := e / 2 + return Pow10(m) * Pow10(e-m) } func init() { - pow10tab[0] = 1.0e0; - pow10tab[1] = 1.0e1; + pow10tab[0] = 1.0e0 + pow10tab[1] = 1.0e1 for i := 2; i < len(pow10tab); i++ { - m := i / 2; - pow10tab[i] = pow10tab[m] * pow10tab[i-m]; + m := i / 2 + pow10tab[i] = pow10tab[m] * pow10tab[i-m] } } diff --git a/src/pkg/math/sin.go b/src/pkg/math/sin.go index 25f676355..e17daf688 100644 --- a/src/pkg/math/sin.go +++ b/src/pkg/math/sin.go @@ -8,32 +8,32 @@ package math func sinus(x float64, quad int) float64 { // Coefficients are #3370 from Hart & Cheney (18.80D). const ( - P0 = .1357884097877375669092680e8; - P1 = -.4942908100902844161158627e7; - P2 = .4401030535375266501944918e6; - P3 = -.1384727249982452873054457e5; - P4 = .1459688406665768722226959e3; - Q0 = .8644558652922534429915149e7; - Q1 = .4081792252343299749395779e6; - Q2 = .9463096101538208180571257e4; - Q3 = .1326534908786136358911494e3; + P0 = .1357884097877375669092680e8 + P1 = -.4942908100902844161158627e7 + P2 = .4401030535375266501944918e6 + P3 = -.1384727249982452873054457e5 + P4 = .1459688406665768722226959e3 + Q0 = .8644558652922534429915149e7 + Q1 = .4081792252343299749395779e6 + Q2 = .9463096101538208180571257e4 + Q3 = .1326534908786136358911494e3 ) if x < 0 { - x = -x; - quad = quad + 2; + x = -x + quad = quad + 2 } - x = x * (2 / Pi); /* underflow? */ - var y float64; + x = x * (2 / Pi) /* underflow? */ + var y float64 if x > 32764 { - var e float64; - e, y = Modf(x); - e = e + float64(quad); - f, _ := Modf(0.25 * e); - quad = int(e - 4*f); + var e float64 + e, y = Modf(x) + e = e + float64(quad) + f, _ := Modf(0.25 * e) + quad = int(e - 4*f) } else { - k := int32(x); - y = x - float64(k); - quad = (quad + int(k)) & 3; + k := int32(x) + y = x - float64(k) + quad = (quad + int(k)) & 3 } if quad&1 != 0 { @@ -43,10 +43,10 @@ func sinus(x float64, quad int) float64 { y = -y } - yy := y * y; - temp1 := ((((P4*yy+P3)*yy+P2)*yy+P1)*yy + P0) * y; - temp2 := ((((yy+Q3)*yy+Q2)*yy+Q1)*yy + Q0); - return temp1 / temp2; + yy := y * y + temp1 := ((((P4*yy+P3)*yy+P2)*yy+P1)*yy + P0) * y + temp2 := ((((yy+Q3)*yy+Q2)*yy+Q1)*yy + Q0) + return temp1 / temp2 } // Cos returns the cosine of x. @@ -54,8 +54,8 @@ func Cos(x float64) float64 { if x < 0 { x = -x } - return sinus(x, 1); + return sinus(x, 1) } // Sin returns the sine of x. -func Sin(x float64) float64 { return sinus(x, 0) } +func Sin(x float64) float64 { return sinus(x, 0) } diff --git a/src/pkg/math/sinh.go b/src/pkg/math/sinh.go index 968b89b6d..8d70cd3dd 100644 --- a/src/pkg/math/sinh.go +++ b/src/pkg/math/sinh.go @@ -21,22 +21,22 @@ package math func Sinh(x float64) float64 { // The coefficients are #2029 from Hart & Cheney. (20.36D) const ( - P0 = -0.6307673640497716991184787251e+6; - P1 = -0.8991272022039509355398013511e+5; - P2 = -0.2894211355989563807284660366e+4; - P3 = -0.2630563213397497062819489e+2; - Q0 = -0.6307673640497716991212077277e+6; - Q1 = 0.1521517378790019070696485176e+5; - Q2 = -0.173678953558233699533450911e+3; + P0 = -0.6307673640497716991184787251e+6 + P1 = -0.8991272022039509355398013511e+5 + P2 = -0.2894211355989563807284660366e+4 + P3 = -0.2630563213397497062819489e+2 + Q0 = -0.6307673640497716991212077277e+6 + Q1 = 0.1521517378790019070696485176e+5 + Q2 = -0.173678953558233699533450911e+3 ) - sign := false; + sign := false if x < 0 { - x = -x; - sign = true; + x = -x + sign = true } - var temp float64; + var temp float64 switch true { case x > 21: temp = Exp(x) / 2 @@ -45,15 +45,15 @@ func Sinh(x float64) float64 { temp = (Exp(x) - Exp(-x)) / 2 default: - sq := x * x; - temp = (((P3*sq+P2)*sq+P1)*sq + P0) * x; - temp = temp / (((sq+Q2)*sq+Q1)*sq + Q0); + sq := x * x + temp = (((P3*sq+P2)*sq+P1)*sq + P0) * x + temp = temp / (((sq+Q2)*sq+Q1)*sq + Q0) } if sign { temp = -temp } - return temp; + return temp } // Cosh returns the hyperbolic cosine of x. @@ -64,5 +64,5 @@ func Cosh(x float64) float64 { if x > 21 { return Exp(x) / 2 } - return (Exp(x) + Exp(-x)) / 2; + return (Exp(x) + Exp(-x)) / 2 } diff --git a/src/pkg/math/sqrt.go b/src/pkg/math/sqrt.go index 63f458b4b..1e2209f2a 100644 --- a/src/pkg/math/sqrt.go +++ b/src/pkg/math/sqrt.go @@ -27,39 +27,39 @@ func Sqrt(x float64) float64 { if x < 0 { return NaN() } - return 0; + return 0 } - y, exp := Frexp(x); + y, exp := Frexp(x) for y < 0.5 { - y = y * 2; - exp = exp - 1; + y = y * 2 + exp = exp - 1 } if exp&1 != 0 { - y = y * 2; - exp = exp - 1; + y = y * 2 + exp = exp - 1 } - temp := 0.5 * (1 + y); + temp := 0.5 * (1 + y) for exp > 60 { - temp = temp * float64(1<<30); - exp = exp - 60; + temp = temp * float64(1<<30) + exp = exp - 60 } for exp < -60 { - temp = temp / float64(1<<30); - exp = exp + 60; + temp = temp / float64(1<<30) + exp = exp + 60 } if exp >= 0 { - exp = 1 << uint(exp/2); - temp = temp * float64(exp); + exp = 1 << uint(exp/2) + temp = temp * float64(exp) } else { - exp = 1 << uint(-exp/2); - temp = temp / float64(exp); + exp = 1 << uint(-exp/2) + temp = temp / float64(exp) } for i := 0; i <= 4; i++ { temp = 0.5 * (temp + x/temp) } - return temp; + return temp } diff --git a/src/pkg/math/tan.go b/src/pkg/math/tan.go index 09ade2da9..05ba232a7 100644 --- a/src/pkg/math/tan.go +++ b/src/pkg/math/tan.go @@ -13,53 +13,53 @@ package math func Tan(x float64) float64 { // Coefficients are #4285 from Hart & Cheney. (19.74D) const ( - P0 = -.1306820264754825668269611177e+5; - P1 = .1055970901714953193602353981e+4; - P2 = -.1550685653483266376941705728e+2; - P3 = .3422554387241003435328470489e-1; - P4 = .3386638642677172096076369e-4; - Q0 = -.1663895238947119001851464661e+5; - Q1 = .4765751362916483698926655581e+4; - Q2 = -.1555033164031709966900124574e+3; + P0 = -.1306820264754825668269611177e+5 + P1 = .1055970901714953193602353981e+4 + P2 = -.1550685653483266376941705728e+2 + P3 = .3422554387241003435328470489e-1 + P4 = .3386638642677172096076369e-4 + Q0 = -.1663895238947119001851464661e+5 + Q1 = .4765751362916483698926655581e+4 + Q2 = -.1555033164031709966900124574e+3 ) - flag := false; - sign := false; + flag := false + sign := false if x < 0 { - x = -x; - sign = true; + x = -x + sign = true } - x = x * (4 / Pi); /* overflow? */ - var e float64; - e, x = Modf(x); - i := int32(e); + x = x * (4 / Pi) /* overflow? */ + var e float64 + e, x = Modf(x) + i := int32(e) switch i & 3 { case 1: - x = 1 - x; - flag = true; + x = 1 - x + flag = true case 2: - sign = !sign; - flag = true; + sign = !sign + flag = true case 3: - x = 1 - x; - sign = !sign; + x = 1 - x + sign = !sign } - xsq := x * x; - temp := ((((P4*xsq+P3)*xsq+P2)*xsq+P1)*xsq + P0) * x; - temp = temp / (((xsq+Q2)*xsq+Q1)*xsq + Q0); + xsq := x * x + temp := ((((P4*xsq+P3)*xsq+P2)*xsq+P1)*xsq + P0) * x + temp = temp / (((xsq+Q2)*xsq+Q1)*xsq + Q0) if flag { if temp == 0 { panic(NaN()) } - temp = 1 / temp; + temp = 1 / temp } if sign { temp = -temp } - return temp; + return temp } diff --git a/src/pkg/math/tanh.go b/src/pkg/math/tanh.go index 93c68a6e4..144c08530 100644 --- a/src/pkg/math/tanh.go +++ b/src/pkg/math/tanh.go @@ -16,14 +16,14 @@ package math // Tanh computes the hyperbolic tangent of x. func Tanh(x float64) float64 { if x < 0 { - x = -x; + x = -x if x > 21 { return -1 } - return -Sinh(x) / Cosh(x); + return -Sinh(x) / Cosh(x) } if x > 21 { return 1 } - return Sinh(x) / Cosh(x); + return Sinh(x) / Cosh(x) } diff --git a/src/pkg/math/unsafe.go b/src/pkg/math/unsafe.go index 182b2e13b..5ae67420f 100644 --- a/src/pkg/math/unsafe.go +++ b/src/pkg/math/unsafe.go @@ -7,15 +7,15 @@ package math import "unsafe" // Float32bits returns the IEEE 754 binary representation of f. -func Float32bits(f float32) uint32 { return *(*uint32)(unsafe.Pointer(&f)) } +func Float32bits(f float32) uint32 { return *(*uint32)(unsafe.Pointer(&f)) } // Float32frombits returns the floating point number corresponding // to the IEEE 754 binary representation b. -func Float32frombits(b uint32) float32 { return *(*float32)(unsafe.Pointer(&b)) } +func Float32frombits(b uint32) float32 { return *(*float32)(unsafe.Pointer(&b)) } // Float64bits returns the IEEE 754 binary representation of f. -func Float64bits(f float64) uint64 { return *(*uint64)(unsafe.Pointer(&f)) } +func Float64bits(f float64) uint64 { return *(*uint64)(unsafe.Pointer(&f)) } // Float64frombits returns the floating point number corresponding // the IEEE 754 binary representation b. -func Float64frombits(b uint64) float64 { return *(*float64)(unsafe.Pointer(&b)) } +func Float64frombits(b uint64) float64 { return *(*float64)(unsafe.Pointer(&b)) } diff --git a/src/pkg/net/dialgoogle_test.go b/src/pkg/net/dialgoogle_test.go index 932dd8cda..dfcc8f01e 100644 --- a/src/pkg/net/dialgoogle_test.go +++ b/src/pkg/net/dialgoogle_test.go @@ -5,11 +5,11 @@ package net import ( - "flag"; - "io"; - "strings"; - "syscall"; - "testing"; + "flag" + "io" + "strings" + "syscall" + "testing" ) // If an IPv6 tunnel is running (see go/stubl), we can try dialing a real IPv6 address. @@ -18,26 +18,26 @@ var ipv6 = flag.Bool("ipv6", false, "assume ipv6 tunnel is present") // fd is already connected to the destination, port 80. // Run an HTTP request to fetch the appropriate page. func fetchGoogle(t *testing.T, fd Conn, network, addr string) { - req := strings.Bytes("GET /intl/en/privacy.html HTTP/1.0\r\nHost: www.google.com\r\n\r\n"); - n, err := fd.Write(req); + req := strings.Bytes("GET /intl/en/privacy.html HTTP/1.0\r\nHost: www.google.com\r\n\r\n") + n, err := fd.Write(req) - buf := make([]byte, 1000); - n, err = io.ReadFull(fd, buf); + buf := make([]byte, 1000) + n, err = io.ReadFull(fd, buf) if n < 1000 { - t.Errorf("fetchGoogle: short HTTP read from %s %s - %v", network, addr, err); - return; + t.Errorf("fetchGoogle: short HTTP read from %s %s - %v", network, addr, err) + return } } func doDial(t *testing.T, network, addr string) { - fd, err := Dial(network, "", addr); + fd, err := Dial(network, "", addr) if err != nil { - t.Errorf("Dial(%q, %q, %q) = _, %v", network, "", addr, err); - return; + t.Errorf("Dial(%q, %q, %q) = _, %v", network, "", addr, err) + return } - fetchGoogle(t, fd, network, addr); - fd.Close(); + fetchGoogle(t, fd, network, addr) + fd.Close() } var googleaddrs = []string{ @@ -51,7 +51,7 @@ var googleaddrs = []string{ "[0:0:0:0:0000:ffff:74.125.19.99]:80", "[0:0:0:0:000000:ffff:74.125.19.99]:80", "[0:0:0:0:0:ffff::74.125.19.99]:80", - "[2001:4860:0:2001::68]:80", // ipv6.google.com; removed if ipv6 flag not set + "[2001:4860:0:2001::68]:80", // ipv6.google.com; removed if ipv6 flag not set } func TestDialGoogle(t *testing.T) { @@ -61,22 +61,22 @@ func TestDialGoogle(t *testing.T) { } for i := 0; i < len(googleaddrs); i++ { - addr := googleaddrs[i]; + addr := googleaddrs[i] if addr == "" { continue } - t.Logf("-- %s --", addr); - doDial(t, "tcp", addr); + t.Logf("-- %s --", addr) + doDial(t, "tcp", addr) if addr[0] != '[' { - doDial(t, "tcp4", addr); + doDial(t, "tcp4", addr) if !preferIPv4 { // make sure preferIPv4 flag works. - preferIPv4 = true; - syscall.SocketDisableIPv6 = true; - doDial(t, "tcp4", addr); - syscall.SocketDisableIPv6 = false; - preferIPv4 = false; + preferIPv4 = true + syscall.SocketDisableIPv6 = true + doDial(t, "tcp4", addr) + syscall.SocketDisableIPv6 = false + preferIPv4 = false } } diff --git a/src/pkg/net/dnsclient.go b/src/pkg/net/dnsclient.go index 064e1017b..439cae806 100644 --- a/src/pkg/net/dnsclient.go +++ b/src/pkg/net/dnsclient.go @@ -15,24 +15,24 @@ package net import ( - "once"; - "os"; + "once" + "os" ) // DNSError represents a DNS lookup error. type DNSError struct { - Error string; // description of the error - Name string; // name looked for - Server string; // server used + Error string // description of the error + Name string // name looked for + Server string // server used } func (e *DNSError) String() string { - s := "lookup " + e.Name; + s := "lookup " + e.Name if e.Server != "" { s += " on " + e.Server } - s += ": " + e.Error; - return s; + s += ": " + e.Error + return s } const noSuchHost = "no such host" @@ -43,53 +43,53 @@ func _Exchange(cfg *_DNS_Config, c Conn, name string) (m *_DNS_Msg, err os.Error if len(name) >= 256 { return nil, &DNSError{"name too long", name, ""} } - out := new(_DNS_Msg); - out.id = 0x1234; + out := new(_DNS_Msg) + out.id = 0x1234 out.question = []_DNS_Question{ _DNS_Question{name, _DNS_TypeA, _DNS_ClassINET}, - }; - out.recursion_desired = true; - msg, ok := out.Pack(); + } + out.recursion_desired = true + msg, ok := out.Pack() if !ok { return nil, &DNSError{"internal error - cannot pack message", name, ""} } for attempt := 0; attempt < cfg.attempts; attempt++ { - n, err := c.Write(msg); + n, err := c.Write(msg) if err != nil { return nil, err } - c.SetReadTimeout(1e9); // nanoseconds + c.SetReadTimeout(1e9) // nanoseconds - buf := make([]byte, 2000); // More than enough. - n, err = c.Read(buf); + buf := make([]byte, 2000) // More than enough. + n, err = c.Read(buf) if isEAGAIN(err) { - err = nil; - continue; + err = nil + continue } if err != nil { return nil, err } - buf = buf[0:n]; - in := new(_DNS_Msg); + buf = buf[0:n] + in := new(_DNS_Msg) if !in.Unpack(buf) || in.id != out.id { continue } - return in, nil; + return in, nil } - var server string; + var server string if a := c.RemoteAddr(); a != nil { server = a.String() } - return nil, &DNSError{"no answer from server", name, server}; + return nil, &DNSError{"no answer from server", name, server} } // Find answer for name in dns message. // On return, if err == nil, addrs != nil. func answer(name, server string, dns *_DNS_Msg) (addrs []string, err *DNSError) { - addrs = make([]string, 0, len(dns.answer)); + addrs = make([]string, 0, len(dns.answer)) if dns.rcode == _DNS_RcodeNameError && dns.recursion_available { return nil, &DNSError{noSuchHost, name, ""} @@ -109,31 +109,31 @@ func answer(name, server string, dns *_DNS_Msg) (addrs []string, err *DNSError) // all the answers we need in this one packet. Cname: for cnameloop := 0; cnameloop < 10; cnameloop++ { - addrs = addrs[0:0]; + addrs = addrs[0:0] for i := 0; i < len(dns.answer); i++ { - rr := dns.answer[i]; - h := rr.Header(); + rr := dns.answer[i] + h := rr.Header() if h.Class == _DNS_ClassINET && h.Name == name { switch h.Rrtype { case _DNS_TypeA: - n := len(addrs); - a := rr.(*_DNS_RR_A).A; - addrs = addrs[0 : n+1]; - addrs[n] = IPv4(byte(a>>24), byte(a>>16), byte(a>>8), byte(a)).String(); + n := len(addrs) + a := rr.(*_DNS_RR_A).A + addrs = addrs[0 : n+1] + addrs[n] = IPv4(byte(a>>24), byte(a>>16), byte(a>>8), byte(a)).String() case _DNS_TypeCNAME: // redirect to cname - name = rr.(*_DNS_RR_CNAME).Cname; - continue Cname; + name = rr.(*_DNS_RR_CNAME).Cname + continue Cname } } } if len(addrs) == 0 { return nil, &DNSError{noSuchHost, name, server} } - return addrs, nil; + return addrs, nil } - return nil, &DNSError{"too many redirects", name, server}; + return nil, &DNSError{"too many redirects", name, server} } // Do a lookup for a single name, which must be rooted @@ -149,36 +149,36 @@ func tryOneName(cfg *_DNS_Config, name string) (addrs []string, err os.Error) { // The DNS config parser has already checked that // all the cfg.servers[i] are IP addresses, which // Dial will use without a DNS lookup. - server := cfg.servers[i] + ":53"; - c, cerr := Dial("udp", "", server); + server := cfg.servers[i] + ":53" + c, cerr := Dial("udp", "", server) if cerr != nil { - err = cerr; - continue; + err = cerr + continue } - msg, merr := _Exchange(cfg, c, name); - c.Close(); + msg, merr := _Exchange(cfg, c, name) + c.Close() if merr != nil { - err = merr; - continue; + err = merr + continue } - var dnserr *DNSError; - addrs, dnserr = answer(name, server, msg); + var dnserr *DNSError + addrs, dnserr = answer(name, server, msg) if dnserr != nil { err = dnserr } else { - err = nil // nil os.Error, not nil *DNSError + err = nil // nil os.Error, not nil *DNSError } if dnserr == nil || dnserr.Error == noSuchHost { break } } - return; + return } var cfg *_DNS_Config var dnserr os.Error -func loadConfig() { cfg, dnserr = _DNS_ReadConfig() } +func loadConfig() { cfg, dnserr = _DNS_ReadConfig() } func isDomainName(s string) bool { // Requirements on DNS name: @@ -192,14 +192,14 @@ func isDomainName(s string) bool { if len(s) == 0 { return false } - if s[len(s)-1] != '.' { // simplify checking loop: make name end in dot + if s[len(s)-1] != '.' { // simplify checking loop: make name end in dot s += "." } - last := byte('.'); - ok := false; // ok once we've seen a letter + last := byte('.') + ok := false // ok once we've seen a letter for i := 0; i < len(s); i++ { - c := s[i]; + c := s[i] switch { default: return false @@ -218,10 +218,10 @@ func isDomainName(s string) bool { return false } } - last = c; + last = c } - return ok; + return ok } // LookupHost looks up the host name using the local DNS resolver. @@ -231,25 +231,25 @@ func LookupHost(name string) (cname string, addrs []string, err os.Error) { if !isDomainName(name) { return name, nil, &DNSError{"invalid domain name", name, ""} } - once.Do(loadConfig); + once.Do(loadConfig) if dnserr != nil || cfg == nil { - err = dnserr; - return; + err = dnserr + return } // If name is rooted (trailing dot) or has enough dots, // try it by itself first. - rooted := len(name) > 0 && name[len(name)-1] == '.'; + rooted := len(name) > 0 && name[len(name)-1] == '.' if rooted || count(name, '.') >= cfg.ndots { - rname := name; + rname := name if !rooted { rname += "." } // Can try as ordinary name. - addrs, err = tryOneName(cfg, rname); + addrs, err = tryOneName(cfg, rname) if err == nil { - cname = rname; - return; + cname = rname + return } } if rooted { @@ -258,26 +258,26 @@ func LookupHost(name string) (cname string, addrs []string, err os.Error) { // Otherwise, try suffixes. for i := 0; i < len(cfg.search); i++ { - rname := name + "." + cfg.search[i]; + rname := name + "." + cfg.search[i] if rname[len(rname)-1] != '.' { rname += "." } - addrs, err = tryOneName(cfg, rname); + addrs, err = tryOneName(cfg, rname) if err == nil { - cname = rname; - return; + cname = rname + return } } // Last ditch effort: try unsuffixed. - rname := name; + rname := name if !rooted { rname += "." } - addrs, err = tryOneName(cfg, rname); + addrs, err = tryOneName(cfg, rname) if err == nil { - cname = rname; - return; + cname = rname + return } - return; + return } diff --git a/src/pkg/net/dnsconfig.go b/src/pkg/net/dnsconfig.go index 243a4b431..b2153e07d 100644 --- a/src/pkg/net/dnsconfig.go +++ b/src/pkg/net/dnsconfig.go @@ -9,12 +9,12 @@ package net import "os" type _DNS_Config struct { - servers []string; // servers to use - search []string; // suffixes to append to local name - ndots int; // number of dots in name to trigger absolute lookup - timeout int; // seconds before giving up on packet - attempts int; // lost packets before giving up on server - rotate bool; // round robin among servers + servers []string // servers to use + search []string // suffixes to append to local name + ndots int // number of dots in name to trigger absolute lookup + timeout int // seconds before giving up on packet + attempts int // lost packets before giving up on server + rotate bool // round robin among servers } var _DNS_configError os.Error @@ -24,81 +24,81 @@ var _DNS_configError os.Error // of the host name to get the default search domain. // We assume it's in resolv.conf anyway. func _DNS_ReadConfig() (*_DNS_Config, os.Error) { - file, err := open("/etc/resolv.conf"); + file, err := open("/etc/resolv.conf") if err != nil { return nil, err } - conf := new(_DNS_Config); - conf.servers = make([]string, 3)[0:0]; // small, but the standard limit - conf.search = make([]string, 0); - conf.ndots = 1; - conf.timeout = 1; - conf.attempts = 1; - conf.rotate = false; + conf := new(_DNS_Config) + conf.servers = make([]string, 3)[0:0] // small, but the standard limit + conf.search = make([]string, 0) + conf.ndots = 1 + conf.timeout = 1 + conf.attempts = 1 + conf.rotate = false for line, ok := file.readLine(); ok; line, ok = file.readLine() { - f := getFields(line); + f := getFields(line) if len(f) < 1 { continue } switch f[0] { - case "nameserver": // add one name server - a := conf.servers; - n := len(a); + case "nameserver": // add one name server + a := conf.servers + n := len(a) if len(f) > 1 && n < cap(a) { // One more check: make sure server name is // just an IP address. Otherwise we need DNS // to look it up. - name := f[1]; + name := f[1] if len(ParseIP(name)) != 0 { - a = a[0 : n+1]; - a[n] = name; - conf.servers = a; + a = a[0 : n+1] + a[n] = name + conf.servers = a } } - case "domain": // set search path to just this domain + case "domain": // set search path to just this domain if len(f) > 1 { - conf.search = make([]string, 1); - conf.search[0] = f[1]; + conf.search = make([]string, 1) + conf.search[0] = f[1] } else { conf.search = make([]string, 0) } - case "search": // set search path to given servers - conf.search = make([]string, len(f)-1); + case "search": // set search path to given servers + conf.search = make([]string, len(f)-1) for i := 0; i < len(conf.search); i++ { conf.search[i] = f[i+1] } - case "options": // magic options + case "options": // magic options for i := 1; i < len(f); i++ { - s := f[i]; + s := f[i] switch { case len(s) >= 6 && s[0:6] == "ndots:": - n, _, _ := dtoi(s, 6); + n, _, _ := dtoi(s, 6) if n < 1 { n = 1 } - conf.ndots = n; + conf.ndots = n case len(s) >= 8 && s[0:8] == "timeout:": - n, _, _ := dtoi(s, 8); + n, _, _ := dtoi(s, 8) if n < 1 { n = 1 } - conf.timeout = n; + conf.timeout = n case len(s) >= 8 && s[0:9] == "attempts:": - n, _, _ := dtoi(s, 9); + n, _, _ := dtoi(s, 9) if n < 1 { n = 1 } - conf.attempts = n; + conf.attempts = n case s == "rotate": conf.rotate = true } } } } - file.close(); + file.close() - return conf, nil; + return conf, nil } diff --git a/src/pkg/net/dnsmsg.go b/src/pkg/net/dnsmsg.go index 2bcb88206..01bb49078 100644 --- a/src/pkg/net/dnsmsg.go +++ b/src/pkg/net/dnsmsg.go @@ -24,9 +24,9 @@ package net import ( - "fmt"; - "os"; - "reflect"; + "fmt" + "os" + "reflect" ) // Packet formats @@ -34,77 +34,77 @@ import ( // Wire constants. const ( // valid _DNS_RR_Header.Rrtype and _DNS_Question.qtype - _DNS_TypeA = 1; - _DNS_TypeNS = 2; - _DNS_TypeMD = 3; - _DNS_TypeMF = 4; - _DNS_TypeCNAME = 5; - _DNS_TypeSOA = 6; - _DNS_TypeMB = 7; - _DNS_TypeMG = 8; - _DNS_TypeMR = 9; - _DNS_TypeNULL = 10; - _DNS_TypeWKS = 11; - _DNS_TypePTR = 12; - _DNS_TypeHINFO = 13; - _DNS_TypeMINFO = 14; - _DNS_TypeMX = 15; - _DNS_TypeTXT = 16; + _DNS_TypeA = 1 + _DNS_TypeNS = 2 + _DNS_TypeMD = 3 + _DNS_TypeMF = 4 + _DNS_TypeCNAME = 5 + _DNS_TypeSOA = 6 + _DNS_TypeMB = 7 + _DNS_TypeMG = 8 + _DNS_TypeMR = 9 + _DNS_TypeNULL = 10 + _DNS_TypeWKS = 11 + _DNS_TypePTR = 12 + _DNS_TypeHINFO = 13 + _DNS_TypeMINFO = 14 + _DNS_TypeMX = 15 + _DNS_TypeTXT = 16 // valid _DNS_Question.qtype only - _DNS_TypeAXFR = 252; - _DNS_TypeMAILB = 253; - _DNS_TypeMAILA = 254; - _DNS_TypeALL = 255; + _DNS_TypeAXFR = 252 + _DNS_TypeMAILB = 253 + _DNS_TypeMAILA = 254 + _DNS_TypeALL = 255 // valid _DNS_Question.qclass - _DNS_ClassINET = 1; - _DNS_ClassCSNET = 2; - _DNS_ClassCHAOS = 3; - _DNS_ClassHESIOD = 4; - _DNS_ClassANY = 255; + _DNS_ClassINET = 1 + _DNS_ClassCSNET = 2 + _DNS_ClassCHAOS = 3 + _DNS_ClassHESIOD = 4 + _DNS_ClassANY = 255 // _DNS_Msg.rcode - _DNS_RcodeSuccess = 0; - _DNS_RcodeFormatError = 1; - _DNS_RcodeServerFailure = 2; - _DNS_RcodeNameError = 3; - _DNS_RcodeNotImplemented = 4; - _DNS_RcodeRefused = 5; + _DNS_RcodeSuccess = 0 + _DNS_RcodeFormatError = 1 + _DNS_RcodeServerFailure = 2 + _DNS_RcodeNameError = 3 + _DNS_RcodeNotImplemented = 4 + _DNS_RcodeRefused = 5 ) // The wire format for the DNS packet header. type __DNS_Header struct { - Id uint16; - Bits uint16; - Qdcount, Ancount, Nscount, Arcount uint16; + Id uint16 + Bits uint16 + Qdcount, Ancount, Nscount, Arcount uint16 } const ( // __DNS_Header.Bits - _QR = 1 << 15; // query/response (response=1) - _AA = 1 << 10; // authoritative - _TC = 1 << 9; // truncated - _RD = 1 << 8; // recursion desired - _RA = 1 << 7; // recursion available + _QR = 1 << 15 // query/response (response=1) + _AA = 1 << 10 // authoritative + _TC = 1 << 9 // truncated + _RD = 1 << 8 // recursion desired + _RA = 1 << 7 // recursion available ) // DNS queries. type _DNS_Question struct { - Name string "domain-name"; // "domain-name" specifies encoding; see packers below - Qtype uint16; - Qclass uint16; + Name string "domain-name" // "domain-name" specifies encoding; see packers below + Qtype uint16 + Qclass uint16 } // DNS responses (resource records). // There are many types of messages, // but they all share the same header. type _DNS_RR_Header struct { - Name string "domain-name"; - Rrtype uint16; - Class uint16; - Ttl uint32; - Rdlength uint16; // length of data after header + Name string "domain-name" + Rrtype uint16 + Class uint16 + Ttl uint32 + Rdlength uint16 // length of data after header } func (h *_DNS_RR_Header) Header() *_DNS_RR_Header { @@ -112,15 +112,15 @@ func (h *_DNS_RR_Header) Header() *_DNS_RR_Header { } type _DNS_RR interface { - Header() *_DNS_RR_Header; + Header() *_DNS_RR_Header } // Specific DNS RR formats for each query type. type _DNS_RR_CNAME struct { - Hdr _DNS_RR_Header; - Cname string "domain-name"; + Hdr _DNS_RR_Header + Cname string "domain-name" } func (rr *_DNS_RR_CNAME) Header() *_DNS_RR_Header { @@ -128,9 +128,9 @@ func (rr *_DNS_RR_CNAME) Header() *_DNS_RR_Header { } type _DNS_RR_HINFO struct { - Hdr _DNS_RR_Header; - Cpu string; - Os string; + Hdr _DNS_RR_Header + Cpu string + Os string } func (rr *_DNS_RR_HINFO) Header() *_DNS_RR_Header { @@ -138,8 +138,8 @@ func (rr *_DNS_RR_HINFO) Header() *_DNS_RR_Header { } type _DNS_RR_MB struct { - Hdr _DNS_RR_Header; - Mb string "domain-name"; + Hdr _DNS_RR_Header + Mb string "domain-name" } func (rr *_DNS_RR_MB) Header() *_DNS_RR_Header { @@ -147,8 +147,8 @@ func (rr *_DNS_RR_MB) Header() *_DNS_RR_Header { } type _DNS_RR_MG struct { - Hdr _DNS_RR_Header; - Mg string "domain-name"; + Hdr _DNS_RR_Header + Mg string "domain-name" } func (rr *_DNS_RR_MG) Header() *_DNS_RR_Header { @@ -156,9 +156,9 @@ func (rr *_DNS_RR_MG) Header() *_DNS_RR_Header { } type _DNS_RR_MINFO struct { - Hdr _DNS_RR_Header; - Rmail string "domain-name"; - Email string "domain-name"; + Hdr _DNS_RR_Header + Rmail string "domain-name" + Email string "domain-name" } func (rr *_DNS_RR_MINFO) Header() *_DNS_RR_Header { @@ -166,8 +166,8 @@ func (rr *_DNS_RR_MINFO) Header() *_DNS_RR_Header { } type _DNS_RR_MR struct { - Hdr _DNS_RR_Header; - Mr string "domain-name"; + Hdr _DNS_RR_Header + Mr string "domain-name" } func (rr *_DNS_RR_MR) Header() *_DNS_RR_Header { @@ -175,9 +175,9 @@ func (rr *_DNS_RR_MR) Header() *_DNS_RR_Header { } type _DNS_RR_MX struct { - Hdr _DNS_RR_Header; - Pref uint16; - Mx string "domain-name"; + Hdr _DNS_RR_Header + Pref uint16 + Mx string "domain-name" } func (rr *_DNS_RR_MX) Header() *_DNS_RR_Header { @@ -185,8 +185,8 @@ func (rr *_DNS_RR_MX) Header() *_DNS_RR_Header { } type _DNS_RR_NS struct { - Hdr _DNS_RR_Header; - Ns string "domain-name"; + Hdr _DNS_RR_Header + Ns string "domain-name" } func (rr *_DNS_RR_NS) Header() *_DNS_RR_Header { @@ -194,8 +194,8 @@ func (rr *_DNS_RR_NS) Header() *_DNS_RR_Header { } type _DNS_RR_PTR struct { - Hdr _DNS_RR_Header; - Ptr string "domain-name"; + Hdr _DNS_RR_Header + Ptr string "domain-name" } func (rr *_DNS_RR_PTR) Header() *_DNS_RR_Header { @@ -203,14 +203,14 @@ func (rr *_DNS_RR_PTR) Header() *_DNS_RR_Header { } type _DNS_RR_SOA struct { - Hdr _DNS_RR_Header; - Ns string "domain-name"; - Mbox string "domain-name"; - Serial uint32; - Refresh uint32; - Retry uint32; - Expire uint32; - Minttl uint32; + Hdr _DNS_RR_Header + Ns string "domain-name" + Mbox string "domain-name" + Serial uint32 + Refresh uint32 + Retry uint32 + Expire uint32 + Minttl uint32 } func (rr *_DNS_RR_SOA) Header() *_DNS_RR_Header { @@ -218,8 +218,8 @@ func (rr *_DNS_RR_SOA) Header() *_DNS_RR_Header { } type _DNS_RR_TXT struct { - Hdr _DNS_RR_Header; - Txt string; // not domain name + Hdr _DNS_RR_Header + Txt string // not domain name } func (rr *_DNS_RR_TXT) Header() *_DNS_RR_Header { @@ -227,11 +227,11 @@ func (rr *_DNS_RR_TXT) Header() *_DNS_RR_Header { } type _DNS_RR_A struct { - Hdr _DNS_RR_Header; - A uint32 "ipv4"; + Hdr _DNS_RR_Header + A uint32 "ipv4" } -func (rr *_DNS_RR_A) Header() *_DNS_RR_Header { return &rr.Hdr } +func (rr *_DNS_RR_A) Header() *_DNS_RR_Header { return &rr.Hdr } // Packing and unpacking. @@ -271,30 +271,30 @@ func packDomainName(s string, msg []byte, off int) (off1 int, ok bool) { // We trade each dot byte for a length byte. // There is also a trailing zero. // Check that we have all the space we need. - tot := len(s) + 1; + tot := len(s) + 1 if off+tot > len(msg) { return len(msg), false } // Emit sequence of counted strings, chopping at dots. - begin := 0; + begin := 0 for i := 0; i < len(s); i++ { if s[i] == '.' { - if i-begin >= 1<<6 { // top two bits of length must be clear + if i-begin >= 1<<6 { // top two bits of length must be clear return len(msg), false } - msg[off] = byte(i - begin); - off++; + msg[off] = byte(i - begin) + off++ for j := begin; j < i; j++ { - msg[off] = s[j]; - off++; + msg[off] = s[j] + off++ } - begin = i + 1; + begin = i + 1 } } - msg[off] = 0; - off++; - return off, true; + msg[off] = 0 + off++ + return off, true } // Unpack a domain name. @@ -311,15 +311,15 @@ func packDomainName(s string, msg []byte, off int) (off1 int, ok bool) { // In theory, the pointers are only allowed to jump backward. // We let them jump anywhere and stop jumping after a while. func unpackDomainName(msg []byte, off int) (s string, off1 int, ok bool) { - s = ""; - ptr := 0; // number of pointers followed + s = "" + ptr := 0 // number of pointers followed Loop: for { if off >= len(msg) { return "", len(msg), false } - c := int(msg[off]); - off++; + c := int(msg[off]) + off++ switch c & 0xC0 { case 0x00: if c == 0x00 { @@ -330,8 +330,8 @@ Loop: if off+c > len(msg) { return "", len(msg), false } - s += string(msg[off:off+c]) + "."; - off += c; + s += string(msg[off:off+c]) + "." + off += c case 0xC0: // pointer to somewhere else in msg. // remember location after first ptr, @@ -341,15 +341,15 @@ Loop: if off >= len(msg) { return "", len(msg), false } - c1 := msg[off]; - off++; + c1 := msg[off] + off++ if ptr == 0 { off1 = off } if ptr++; ptr > 10 { return "", len(msg), false } - off = (c^0xC0)<<8 | int(c1); + off = (c^0xC0)<<8 | int(c1) default: // 0x80 and 0x40 are reserved return "", len(msg), false @@ -358,7 +358,7 @@ Loop: if ptr == 0 { off1 = off } - return s, off1, true; + return s, off1, true } // TODO(rsc): Move into generic library? @@ -366,41 +366,41 @@ Loop: // and other (often anonymous) structs. func packStructValue(val *reflect.StructValue, msg []byte, off int) (off1 int, ok bool) { for i := 0; i < val.NumField(); i++ { - f := val.Type().(*reflect.StructType).Field(i); + f := val.Type().(*reflect.StructType).Field(i) switch fv := val.Field(i).(type) { default: - fmt.Fprintf(os.Stderr, "net: dns: unknown packing type %v", f.Type); - return len(msg), false; + fmt.Fprintf(os.Stderr, "net: dns: unknown packing type %v", f.Type) + return len(msg), false case *reflect.StructValue: off, ok = packStructValue(fv, msg, off) case *reflect.Uint16Value: - i := fv.Get(); + i := fv.Get() if off+2 > len(msg) { return len(msg), false } - msg[off] = byte(i >> 8); - msg[off+1] = byte(i); - off += 2; + msg[off] = byte(i >> 8) + msg[off+1] = byte(i) + off += 2 case *reflect.Uint32Value: - i := fv.Get(); + i := fv.Get() if off+4 > len(msg) { return len(msg), false } - msg[off] = byte(i >> 24); - msg[off+1] = byte(i >> 16); - msg[off+2] = byte(i >> 8); - msg[off+4] = byte(i); - off += 4; + msg[off] = byte(i >> 24) + msg[off+1] = byte(i >> 16) + msg[off+2] = byte(i >> 8) + msg[off+4] = byte(i) + off += 4 case *reflect.StringValue: // There are multiple string encodings. // The tag distinguishes ordinary strings from domain names. - s := fv.Get(); + s := fv.Get() switch f.Tag { default: - fmt.Fprintf(os.Stderr, "net: dns: unknown string tag %v", f.Tag); - return len(msg), false; + fmt.Fprintf(os.Stderr, "net: dns: unknown string tag %v", f.Tag) + return len(msg), false case "domain-name": - off, ok = packDomainName(s, msg, off); + off, ok = packDomainName(s, msg, off) if !ok { return len(msg), false } @@ -409,16 +409,16 @@ func packStructValue(val *reflect.StructValue, msg []byte, off int) (off1 int, o if len(s) > 255 || off+1+len(s) > len(msg) { return len(msg), false } - msg[off] = byte(len(s)); - off++; + msg[off] = byte(len(s)) + off++ for i := 0; i < len(s); i++ { msg[off+i] = s[i] } - off += len(s); + off += len(s) } } } - return off, true; + return off, true } func structValue(any interface{}) *reflect.StructValue { @@ -426,8 +426,8 @@ func structValue(any interface{}) *reflect.StructValue { } func packStruct(any interface{}, msg []byte, off int) (off1 int, ok bool) { - off, ok = packStructValue(structValue(any), msg, off); - return off, ok; + off, ok = packStructValue(structValue(any), msg, off) + return off, ok } // TODO(rsc): Move into generic library? @@ -435,35 +435,35 @@ func packStruct(any interface{}, msg []byte, off int) (off1 int, ok bool) { // Same restrictions as packStructValue. func unpackStructValue(val *reflect.StructValue, msg []byte, off int) (off1 int, ok bool) { for i := 0; i < val.NumField(); i++ { - f := val.Type().(*reflect.StructType).Field(i); + f := val.Type().(*reflect.StructType).Field(i) switch fv := val.Field(i).(type) { default: - fmt.Fprintf(os.Stderr, "net: dns: unknown packing type %v", f.Type); - return len(msg), false; + fmt.Fprintf(os.Stderr, "net: dns: unknown packing type %v", f.Type) + return len(msg), false case *reflect.StructValue: off, ok = unpackStructValue(fv, msg, off) case *reflect.Uint16Value: if off+2 > len(msg) { return len(msg), false } - i := uint16(msg[off])<<8 | uint16(msg[off+1]); - fv.Set(i); - off += 2; + i := uint16(msg[off])<<8 | uint16(msg[off+1]) + fv.Set(i) + off += 2 case *reflect.Uint32Value: if off+4 > len(msg) { return len(msg), false } - i := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3]); - fv.Set(i); - off += 4; + i := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3]) + fv.Set(i) + off += 4 case *reflect.StringValue: - var s string; + var s string switch f.Tag { default: - fmt.Fprintf(os.Stderr, "net: dns: unknown string tag %v", f.Tag); - return len(msg), false; + fmt.Fprintf(os.Stderr, "net: dns: unknown string tag %v", f.Tag) + return len(msg), false case "domain-name": - s, off, ok = unpackDomainName(msg, off); + s, off, ok = unpackDomainName(msg, off) if !ok { return len(msg), false } @@ -471,24 +471,24 @@ func unpackStructValue(val *reflect.StructValue, msg []byte, off int) (off1 int, if off >= len(msg) || off+1+int(msg[off]) > len(msg) { return len(msg), false } - n := int(msg[off]); - off++; - b := make([]byte, n); + n := int(msg[off]) + off++ + b := make([]byte, n) for i := 0; i < n; i++ { b[i] = msg[off+i] } - off += n; - s = string(b); + off += n + s = string(b) } - fv.Set(s); + fv.Set(s) } } - return off, true; + return off, true } func unpackStruct(any interface{}, msg []byte, off int) (off1 int, ok bool) { - off, ok = unpackStructValue(structValue(any), msg, off); - return off, ok; + off, ok = unpackStructValue(structValue(any), msg, off) + return off, ok } // Generic struct printer. @@ -496,72 +496,72 @@ func unpackStruct(any interface{}, msg []byte, off int) (off1 int, ok bool) { // but does look for an "ipv4" tag on uint32 variables, // printing them as IP addresses. func printStructValue(val *reflect.StructValue) string { - s := "{"; + s := "{" for i := 0; i < val.NumField(); i++ { if i > 0 { s += ", " } - f := val.Type().(*reflect.StructType).Field(i); + f := val.Type().(*reflect.StructType).Field(i) if !f.Anonymous { s += f.Name + "=" } - fval := val.Field(i); + fval := val.Field(i) if fv, ok := fval.(*reflect.StructValue); ok { s += printStructValue(fv) } else if fv, ok := fval.(*reflect.Uint32Value); ok && f.Tag == "ipv4" { - i := fv.Get(); - s += IPv4(byte(i>>24), byte(i>>16), byte(i>>8), byte(i)).String(); + i := fv.Get() + s += IPv4(byte(i>>24), byte(i>>16), byte(i>>8), byte(i)).String() } else { s += fmt.Sprint(fval.Interface()) } } - s += "}"; - return s; + s += "}" + return s } -func printStruct(any interface{}) string { return printStructValue(structValue(any)) } +func printStruct(any interface{}) string { return printStructValue(structValue(any)) } // Resource record packer. func packRR(rr _DNS_RR, msg []byte, off int) (off2 int, ok bool) { - var off1 int; + var off1 int // pack twice, once to find end of header // and again to find end of packet. // a bit inefficient but this doesn't need to be fast. // off1 is end of header // off2 is end of rr - off1, ok = packStruct(rr.Header(), msg, off); - off2, ok = packStruct(rr, msg, off); + off1, ok = packStruct(rr.Header(), msg, off) + off2, ok = packStruct(rr, msg, off) if !ok { return len(msg), false } // pack a third time; redo header with correct data length - rr.Header().Rdlength = uint16(off2 - off1); - packStruct(rr.Header(), msg, off); - return off2, true; + rr.Header().Rdlength = uint16(off2 - off1) + packStruct(rr.Header(), msg, off) + return off2, true } // Resource record unpacker. func unpackRR(msg []byte, off int) (rr _DNS_RR, off1 int, ok bool) { // unpack just the header, to find the rr type and length - var h _DNS_RR_Header; - off0 := off; + var h _DNS_RR_Header + off0 := off if off, ok = unpackStruct(&h, msg, off); !ok { return nil, len(msg), false } - end := off + int(h.Rdlength); + end := off + int(h.Rdlength) // make an rr of that type and re-unpack. // again inefficient but doesn't need to be fast. - mk, known := rr_mk[int(h.Rrtype)]; + mk, known := rr_mk[int(h.Rrtype)] if !known { return &h, end, true } - rr = mk(); - off, ok = unpackStruct(rr, msg, off0); + rr = mk() + off, ok = unpackStruct(rr, msg, off0) if off != end { return &h, end, true } - return rr, off, ok; + return rr, off, ok } // Usable representation of a DNS packet. @@ -569,31 +569,31 @@ func unpackRR(msg []byte, off int) (rr _DNS_RR, off1 int, ok bool) { // A manually-unpacked version of (id, bits). // This is in its own struct for easy printing. type __DNS_Msg_Top struct { - id uint16; - response bool; - opcode int; - authoritative bool; - truncated bool; - recursion_desired bool; - recursion_available bool; - rcode int; + id uint16 + response bool + opcode int + authoritative bool + truncated bool + recursion_desired bool + recursion_available bool + rcode int } type _DNS_Msg struct { - __DNS_Msg_Top; - question []_DNS_Question; - answer []_DNS_RR; - ns []_DNS_RR; - extra []_DNS_RR; + __DNS_Msg_Top + question []_DNS_Question + answer []_DNS_RR + ns []_DNS_RR + extra []_DNS_RR } func (dns *_DNS_Msg) Pack() (msg []byte, ok bool) { - var dh __DNS_Header; + var dh __DNS_Header // Convert convenient _DNS_Msg into wire-like __DNS_Header. - dh.Id = dns.id; - dh.Bits = uint16(dns.opcode)<<11 | uint16(dns.rcode); + dh.Id = dns.id + dh.Bits = uint16(dns.opcode)<<11 | uint16(dns.rcode) if dns.recursion_available { dh.Bits |= _RA } @@ -611,24 +611,24 @@ func (dns *_DNS_Msg) Pack() (msg []byte, ok bool) { } // Prepare variable sized arrays. - question := dns.question; - answer := dns.answer; - ns := dns.ns; - extra := dns.extra; + question := dns.question + answer := dns.answer + ns := dns.ns + extra := dns.extra - dh.Qdcount = uint16(len(question)); - dh.Ancount = uint16(len(answer)); - dh.Nscount = uint16(len(ns)); - dh.Arcount = uint16(len(extra)); + dh.Qdcount = uint16(len(question)) + dh.Ancount = uint16(len(answer)) + dh.Nscount = uint16(len(ns)) + dh.Arcount = uint16(len(extra)) // Could work harder to calculate message size, // but this is far more than we need and not // big enough to hurt the allocator. - msg = make([]byte, 2000); + msg = make([]byte, 2000) // Pack it in: header and then the pieces. - off := 0; - off, ok = packStruct(&dh, msg, off); + off := 0 + off, ok = packStruct(&dh, msg, off) for i := 0; i < len(question); i++ { off, ok = packStruct(&question[i], msg, off) } @@ -644,31 +644,31 @@ func (dns *_DNS_Msg) Pack() (msg []byte, ok bool) { if !ok { return nil, false } - return msg[0:off], true; + return msg[0:off], true } func (dns *_DNS_Msg) Unpack(msg []byte) bool { // Header. - var dh __DNS_Header; - off := 0; - var ok bool; + var dh __DNS_Header + off := 0 + var ok bool if off, ok = unpackStruct(&dh, msg, off); !ok { return false } - dns.id = dh.Id; - dns.response = (dh.Bits & _QR) != 0; - dns.opcode = int(dh.Bits>>11) & 0xF; - dns.authoritative = (dh.Bits & _AA) != 0; - dns.truncated = (dh.Bits & _TC) != 0; - dns.recursion_desired = (dh.Bits & _RD) != 0; - dns.recursion_available = (dh.Bits & _RA) != 0; - dns.rcode = int(dh.Bits & 0xF); + dns.id = dh.Id + dns.response = (dh.Bits & _QR) != 0 + dns.opcode = int(dh.Bits>>11) & 0xF + dns.authoritative = (dh.Bits & _AA) != 0 + dns.truncated = (dh.Bits & _TC) != 0 + dns.recursion_desired = (dh.Bits & _RD) != 0 + dns.recursion_available = (dh.Bits & _RA) != 0 + dns.rcode = int(dh.Bits & 0xF) // Arrays. - dns.question = make([]_DNS_Question, dh.Qdcount); - dns.answer = make([]_DNS_RR, dh.Ancount); - dns.ns = make([]_DNS_RR, dh.Nscount); - dns.extra = make([]_DNS_RR, dh.Arcount); + dns.question = make([]_DNS_Question, dh.Qdcount) + dns.answer = make([]_DNS_RR, dh.Ancount) + dns.ns = make([]_DNS_RR, dh.Nscount) + dns.extra = make([]_DNS_RR, dh.Arcount) for i := 0; i < len(dns.question); i++ { off, ok = unpackStruct(&dns.question[i], msg, off) @@ -688,34 +688,34 @@ func (dns *_DNS_Msg) Unpack(msg []byte) bool { // if off != len(msg) { // println("extra bytes in dns packet", off, "<", len(msg)); // } - return true; + return true } func (dns *_DNS_Msg) String() string { - s := "DNS: " + printStruct(&dns.__DNS_Msg_Top) + "\n"; + s := "DNS: " + printStruct(&dns.__DNS_Msg_Top) + "\n" if len(dns.question) > 0 { - s += "-- Questions\n"; + s += "-- Questions\n" for i := 0; i < len(dns.question); i++ { s += printStruct(&dns.question[i]) + "\n" } } if len(dns.answer) > 0 { - s += "-- Answers\n"; + s += "-- Answers\n" for i := 0; i < len(dns.answer); i++ { s += printStruct(dns.answer[i]) + "\n" } } if len(dns.ns) > 0 { - s += "-- Name servers\n"; + s += "-- Name servers\n" for i := 0; i < len(dns.ns); i++ { s += printStruct(dns.ns[i]) + "\n" } } if len(dns.extra) > 0 { - s += "-- Extra\n"; + s += "-- Extra\n" for i := 0; i < len(dns.extra); i++ { s += printStruct(dns.extra[i]) + "\n" } } - return s; + return s } diff --git a/src/pkg/net/fd.go b/src/pkg/net/fd.go index 733f957e5..743bcfa47 100644 --- a/src/pkg/net/fd.go +++ b/src/pkg/net/fd.go @@ -7,40 +7,40 @@ package net import ( - "once"; - "os"; - "sync"; - "syscall"; + "once" + "os" + "sync" + "syscall" ) // Network file descriptor. type netFD struct { // locking/lifetime of sysfd - sysmu sync.Mutex; - sysref int; - closing bool; + sysmu sync.Mutex + sysref int + closing bool // immutable until Close - sysfd int; - family int; - proto int; - sysfile *os.File; - cr chan *netFD; - cw chan *netFD; - net string; - laddr Addr; - raddr Addr; + sysfd int + family int + proto int + sysfile *os.File + cr chan *netFD + cw chan *netFD + net string + laddr Addr + raddr Addr // owned by client - rdeadline_delta int64; - rdeadline int64; - rio sync.Mutex; - wdeadline_delta int64; - wdeadline int64; - wio sync.Mutex; + rdeadline_delta int64 + rdeadline int64 + rio sync.Mutex + wdeadline_delta int64 + wdeadline int64 + wio sync.Mutex // owned by fd wait server - ncr, ncw int; + ncr, ncw int } // A pollServer helps FDs determine when to retry a non-blocking @@ -78,28 +78,28 @@ type netFD struct { // will the fd be closed. type pollServer struct { - cr, cw chan *netFD; // buffered >= 1 - pr, pw *os.File; - pending map[int]*netFD; - poll *pollster; // low-level OS hooks - deadline int64; // next deadline (nsec since 1970) + cr, cw chan *netFD // buffered >= 1 + pr, pw *os.File + pending map[int]*netFD + poll *pollster // low-level OS hooks + deadline int64 // next deadline (nsec since 1970) } func newPollServer() (s *pollServer, err os.Error) { - s = new(pollServer); - s.cr = make(chan *netFD, 1); - s.cw = make(chan *netFD, 1); + s = new(pollServer) + s.cr = make(chan *netFD, 1) + s.cw = make(chan *netFD, 1) if s.pr, s.pw, err = os.Pipe(); err != nil { return nil, err } - var e int; + var e int if e = syscall.SetNonblock(s.pr.Fd(), true); e != 0 { Errno: - err = &os.PathError{"setnonblock", s.pr.Name(), os.Errno(e)}; + err = &os.PathError{"setnonblock", s.pr.Name(), os.Errno(e)} Error: - s.pr.Close(); - s.pw.Close(); - return nil, err; + s.pr.Close() + s.pw.Close() + return nil, err } if e = syscall.SetNonblock(s.pw.Fd(), true); e != 0 { goto Errno @@ -108,16 +108,16 @@ func newPollServer() (s *pollServer, err os.Error) { goto Error } if err = s.poll.AddFD(s.pr.Fd(), 'r', true); err != nil { - s.poll.Close(); - goto Error; + s.poll.Close() + goto Error } - s.pending = make(map[int]*netFD); - go s.Run(); - return s, nil; + s.pending = make(map[int]*netFD) + go s.Run() + return s, nil } func (s *pollServer) AddFD(fd *netFD, mode int) { - intfd := fd.sysfd; + intfd := fd.sysfd if intfd < 0 { // fd closed underfoot if mode == 'r' { @@ -125,74 +125,74 @@ func (s *pollServer) AddFD(fd *netFD, mode int) { } else { fd.cw <- fd } - return; + return } if err := s.poll.AddFD(intfd, mode, false); err != nil { - panicln("pollServer AddFD ", intfd, ": ", err.String(), "\n"); - return; + panicln("pollServer AddFD ", intfd, ": ", err.String(), "\n") + return } - var t int64; - key := intfd << 1; + var t int64 + key := intfd << 1 if mode == 'r' { - fd.ncr++; - t = fd.rdeadline; + fd.ncr++ + t = fd.rdeadline } else { - fd.ncw++; - key++; - t = fd.wdeadline; + fd.ncw++ + key++ + t = fd.wdeadline } - s.pending[key] = fd; + s.pending[key] = fd if t > 0 && (s.deadline == 0 || t < s.deadline) { s.deadline = t } } func (s *pollServer) LookupFD(fd int, mode int) *netFD { - key := fd << 1; + key := fd << 1 if mode == 'w' { key++ } - netfd, ok := s.pending[key]; + netfd, ok := s.pending[key] if !ok { return nil } - s.pending[key] = nil, false; - return netfd; + s.pending[key] = nil, false + return netfd } func (s *pollServer) WakeFD(fd *netFD, mode int) { if mode == 'r' { for fd.ncr > 0 { - fd.ncr--; - fd.cr <- fd; + fd.ncr-- + fd.cr <- fd } } else { for fd.ncw > 0 { - fd.ncw--; - fd.cw <- fd; + fd.ncw-- + fd.cw <- fd } } } func (s *pollServer) Now() int64 { - sec, nsec, err := os.Time(); + sec, nsec, err := os.Time() if err != nil { panic("net: os.Time: ", err.String()) } - nsec += sec * 1e9; - return nsec; + nsec += sec * 1e9 + return nsec } func (s *pollServer) CheckDeadlines() { - now := s.Now(); + now := s.Now() // TODO(rsc): This will need to be handled more efficiently, // probably with a heap indexed by wakeup time. - var next_deadline int64; + var next_deadline int64 for key, fd := range s.pending { - var t int64; - var mode int; + var t int64 + var mode int if key&1 == 0 { mode = 'r' } else { @@ -205,43 +205,43 @@ func (s *pollServer) CheckDeadlines() { } if t > 0 { if t <= now { - s.pending[key] = nil, false; + s.pending[key] = nil, false if mode == 'r' { - s.poll.DelFD(fd.sysfd, mode); - fd.rdeadline = -1; + s.poll.DelFD(fd.sysfd, mode) + fd.rdeadline = -1 } else { - s.poll.DelFD(fd.sysfd, mode); - fd.wdeadline = -1; + s.poll.DelFD(fd.sysfd, mode) + fd.wdeadline = -1 } - s.WakeFD(fd, mode); + s.WakeFD(fd, mode) } else if next_deadline == 0 || t < next_deadline { next_deadline = t } } } - s.deadline = next_deadline; + s.deadline = next_deadline } func (s *pollServer) Run() { - var scratch [100]byte; + var scratch [100]byte for { - var t = s.deadline; + var t = s.deadline if t > 0 { - t = t - s.Now(); + t = t - s.Now() if t < 0 { - s.CheckDeadlines(); - continue; + s.CheckDeadlines() + continue } } - fd, mode, err := s.poll.WaitFD(t); + fd, mode, err := s.poll.WaitFD(t) if err != nil { - print("pollServer WaitFD: ", err.String(), "\n"); - return; + print("pollServer WaitFD: ", err.String(), "\n") + return } if fd < 0 { // Timeout happened. - s.CheckDeadlines(); - continue; + s.CheckDeadlines() + continue } if fd == s.pr.Fd() { // Drain our wakeup pipe. @@ -256,30 +256,30 @@ func (s *pollServer) Run() { s.AddFD(fd, 'w') } } else { - netfd := s.LookupFD(fd, mode); + netfd := s.LookupFD(fd, mode) if netfd == nil { - print("pollServer: unexpected wakeup for fd=", netfd, " mode=", string(mode), "\n"); - continue; + print("pollServer: unexpected wakeup for fd=", netfd, " mode=", string(mode), "\n") + continue } - s.WakeFD(netfd, mode); + s.WakeFD(netfd, mode) } } } var wakeupbuf [1]byte -func (s *pollServer) Wakeup() { s.pw.Write(&wakeupbuf) } +func (s *pollServer) Wakeup() { s.pw.Write(&wakeupbuf) } func (s *pollServer) WaitRead(fd *netFD) { - s.cr <- fd; - s.Wakeup(); - <-fd.cr; + s.cr <- fd + s.Wakeup() + <-fd.cr } func (s *pollServer) WaitWrite(fd *netFD) { - s.cw <- fd; - s.Wakeup(); - <-fd.cw; + s.cw <- fd + s.Wakeup() + <-fd.cw } // Network FD methods. @@ -288,15 +288,15 @@ func (s *pollServer) WaitWrite(fd *netFD) { var pollserver *pollServer func startServer() { - p, err := newPollServer(); + p, err := newPollServer() if err != nil { print("Start pollServer: ", err.String(), "\n") } - pollserver = p; + pollserver = p } func newFD(fd, family, proto int, net string, laddr, raddr Addr) (f *netFD, err os.Error) { - once.Do(startServer); + once.Do(startServer) if e := syscall.SetNonblock(fd, true); e != 0 { return nil, &OpError{"setnonblock", net, laddr, os.Errno(e)} } @@ -307,50 +307,50 @@ func newFD(fd, family, proto int, net string, laddr, raddr Addr) (f *netFD, err net: net, laddr: laddr, raddr: raddr, - }; - var ls, rs string; + } + var ls, rs string if laddr != nil { ls = laddr.String() } if raddr != nil { rs = raddr.String() } - f.sysfile = os.NewFile(fd, net+":"+ls+"->"+rs); - f.cr = make(chan *netFD, 1); - f.cw = make(chan *netFD, 1); - return f, nil; + f.sysfile = os.NewFile(fd, net+":"+ls+"->"+rs) + f.cr = make(chan *netFD, 1) + f.cw = make(chan *netFD, 1) + return f, nil } // Add a reference to this fd. func (fd *netFD) incref() { - fd.sysmu.Lock(); - fd.sysref++; - fd.sysmu.Unlock(); + fd.sysmu.Lock() + fd.sysref++ + fd.sysmu.Unlock() } // Remove a reference to this FD and close if we've been asked to do so (and // there are no references left. func (fd *netFD) decref() { - fd.sysmu.Lock(); - fd.sysref--; + fd.sysmu.Lock() + fd.sysref-- if fd.closing && fd.sysref == 0 && fd.sysfd >= 0 { // In case the user has set linger, switch to blocking mode so // the close blocks. As long as this doesn't happen often, we // can handle the extra OS processes. Otherwise we'll need to // use the pollserver for Close too. Sigh. - syscall.SetNonblock(fd.sysfd, false); - fd.sysfile.Close(); - fd.sysfile = nil; - fd.sysfd = -1; + syscall.SetNonblock(fd.sysfd, false) + fd.sysfile.Close() + fd.sysfile = nil + fd.sysfd = -1 } - fd.sysmu.Unlock(); + fd.sysmu.Unlock() } func isEAGAIN(e os.Error) bool { if e1, ok := e.(*os.PathError); ok { return e1.Error == os.EAGAIN } - return e == os.EAGAIN; + return e == os.EAGAIN } func (fd *netFD) Close() os.Error { @@ -358,89 +358,89 @@ func (fd *netFD) Close() os.Error { return os.EINVAL } - fd.incref(); - syscall.Shutdown(fd.sysfd, syscall.SHUT_RDWR); - fd.closing = true; - fd.decref(); - return nil; + fd.incref() + syscall.Shutdown(fd.sysfd, syscall.SHUT_RDWR) + fd.closing = true + fd.decref() + return nil } func (fd *netFD) Read(p []byte) (n int, err os.Error) { if fd == nil || fd.sysfile == nil { return 0, os.EINVAL } - fd.rio.Lock(); - defer fd.rio.Unlock(); - fd.incref(); - defer fd.decref(); + fd.rio.Lock() + defer fd.rio.Unlock() + fd.incref() + defer fd.decref() if fd.rdeadline_delta > 0 { fd.rdeadline = pollserver.Now() + fd.rdeadline_delta } else { fd.rdeadline = 0 } for { - n, err = fd.sysfile.Read(p); + n, err = fd.sysfile.Read(p) if isEAGAIN(err) && fd.rdeadline >= 0 { - pollserver.WaitRead(fd); - continue; + pollserver.WaitRead(fd) + continue } - break; + break } if fd.proto == syscall.SOCK_DGRAM && err == os.EOF { // 0 in datagram protocol just means 0-length packet err = nil } - return; + return } func (fd *netFD) ReadFrom(p []byte) (n int, sa syscall.Sockaddr, err os.Error) { if fd == nil || fd.sysfile == nil { return 0, nil, os.EINVAL } - fd.rio.Lock(); - defer fd.rio.Unlock(); - fd.incref(); - defer fd.decref(); + fd.rio.Lock() + defer fd.rio.Unlock() + fd.incref() + defer fd.decref() if fd.rdeadline_delta > 0 { fd.rdeadline = pollserver.Now() + fd.rdeadline_delta } else { fd.rdeadline = 0 } for { - var errno int; - n, sa, errno = syscall.Recvfrom(fd.sysfd, p, 0); + var errno int + n, sa, errno = syscall.Recvfrom(fd.sysfd, p, 0) if errno == syscall.EAGAIN && fd.rdeadline >= 0 { - pollserver.WaitRead(fd); - continue; + pollserver.WaitRead(fd) + continue } if errno != 0 { - n = 0; - err = &os.PathError{"recvfrom", fd.sysfile.Name(), os.Errno(errno)}; + n = 0 + err = &os.PathError{"recvfrom", fd.sysfile.Name(), os.Errno(errno)} } - break; + break } - return; + return } func (fd *netFD) Write(p []byte) (n int, err os.Error) { if fd == nil || fd.sysfile == nil { return 0, os.EINVAL } - fd.wio.Lock(); - defer fd.wio.Unlock(); - fd.incref(); - defer fd.decref(); + fd.wio.Lock() + defer fd.wio.Unlock() + fd.incref() + defer fd.decref() if fd.wdeadline_delta > 0 { fd.wdeadline = pollserver.Now() + fd.wdeadline_delta } else { fd.wdeadline = 0 } - err = nil; - nn := 0; - first := true; // force at least one Write, to send 0-length datagram packets + err = nil + nn := 0 + first := true // force at least one Write, to send 0-length datagram packets for nn < len(p) || first { - first = false; - n, err = fd.sysfile.Write(p[nn:]); + first = false + n, err = fd.sysfile.Write(p[nn:]) if n > 0 { nn += n } @@ -448,45 +448,45 @@ func (fd *netFD) Write(p []byte) (n int, err os.Error) { break } if isEAGAIN(err) && fd.wdeadline >= 0 { - pollserver.WaitWrite(fd); - continue; + pollserver.WaitWrite(fd) + continue } if n == 0 || err != nil { break } } - return nn, err; + return nn, err } func (fd *netFD) WriteTo(p []byte, sa syscall.Sockaddr) (n int, err os.Error) { if fd == nil || fd.sysfile == nil { return 0, os.EINVAL } - fd.wio.Lock(); - defer fd.wio.Unlock(); - fd.incref(); - defer fd.decref(); + fd.wio.Lock() + defer fd.wio.Unlock() + fd.incref() + defer fd.decref() if fd.wdeadline_delta > 0 { fd.wdeadline = pollserver.Now() + fd.wdeadline_delta } else { fd.wdeadline = 0 } - err = nil; + err = nil for { - errno := syscall.Sendto(fd.sysfd, p, 0, sa); + errno := syscall.Sendto(fd.sysfd, p, 0, sa) if errno == syscall.EAGAIN && fd.wdeadline >= 0 { - pollserver.WaitWrite(fd); - continue; + pollserver.WaitWrite(fd) + continue } if errno != 0 { err = &os.PathError{"sendto", fd.sysfile.Name(), os.Errno(errno)} } - break; + break } if err == nil { n = len(p) } - return; + return } func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err os.Error) { @@ -494,34 +494,34 @@ func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err os. return nil, os.EINVAL } - fd.incref(); - defer fd.decref(); + fd.incref() + defer fd.decref() // See ../syscall/exec.go for description of ForkLock. // It is okay to hold the lock across syscall.Accept // because we have put fd.sysfd into non-blocking mode. - syscall.ForkLock.RLock(); - var s, e int; - var sa syscall.Sockaddr; + syscall.ForkLock.RLock() + var s, e int + var sa syscall.Sockaddr for { - s, sa, e = syscall.Accept(fd.sysfd); + s, sa, e = syscall.Accept(fd.sysfd) if e != syscall.EAGAIN { break } - syscall.ForkLock.RUnlock(); - pollserver.WaitRead(fd); - syscall.ForkLock.RLock(); + syscall.ForkLock.RUnlock() + pollserver.WaitRead(fd) + syscall.ForkLock.RLock() } if e != 0 { - syscall.ForkLock.RUnlock(); - return nil, &OpError{"accept", fd.net, fd.laddr, os.Errno(e)}; + syscall.ForkLock.RUnlock() + return nil, &OpError{"accept", fd.net, fd.laddr, os.Errno(e)} } - syscall.CloseOnExec(s); - syscall.ForkLock.RUnlock(); + syscall.CloseOnExec(s) + syscall.ForkLock.RUnlock() if nfd, err = newFD(s, fd.family, fd.proto, fd.net, fd.laddr, toAddr(sa)); err != nil { - syscall.Close(s); - return nil, err; + syscall.Close(s) + return nil, err } - return nfd, nil; + return nfd, nil } diff --git a/src/pkg/net/fd_darwin.go b/src/pkg/net/fd_darwin.go index 74818581a..a33504f6e 100644 --- a/src/pkg/net/fd_darwin.go +++ b/src/pkg/net/fd_darwin.go @@ -7,46 +7,46 @@ package net import ( - "os"; - "syscall"; + "os" + "syscall" ) type pollster struct { - kq int; - eventbuf [10]syscall.Kevent_t; - events []syscall.Kevent_t; + kq int + eventbuf [10]syscall.Kevent_t + events []syscall.Kevent_t } func newpollster() (p *pollster, err os.Error) { - p = new(pollster); - var e int; + p = new(pollster) + var e int if p.kq, e = syscall.Kqueue(); e != 0 { return nil, os.NewSyscallError("kqueue", e) } - p.events = p.eventbuf[0:0]; - return p, nil; + p.events = p.eventbuf[0:0] + return p, nil } func (p *pollster) AddFD(fd int, mode int, repeat bool) os.Error { - var kmode int; + var kmode int if mode == 'r' { kmode = syscall.EVFILT_READ } else { kmode = syscall.EVFILT_WRITE } - var events [1]syscall.Kevent_t; - ev := &events[0]; + var events [1]syscall.Kevent_t + ev := &events[0] // EV_ADD - add event to kqueue list // EV_RECEIPT - generate fake EV_ERROR as result of add, // rather than waiting for real event // EV_ONESHOT - delete the event the first time it triggers - flags := syscall.EV_ADD | syscall.EV_RECEIPT; + flags := syscall.EV_ADD | syscall.EV_RECEIPT if !repeat { flags |= syscall.EV_ONESHOT } - syscall.SetKevent(ev, fd, kmode, flags); + syscall.SetKevent(ev, fd, kmode, flags) - n, e := syscall.Kevent(p.kq, &events, &events, nil); + n, e := syscall.Kevent(p.kq, &events, &events, nil) if e != 0 { return os.NewSyscallError("kevent", e) } @@ -56,55 +56,55 @@ func (p *pollster) AddFD(fd int, mode int, repeat bool) os.Error { if ev.Data != 0 { return os.Errno(int(ev.Data)) } - return nil; + return nil } func (p *pollster) DelFD(fd int, mode int) { - var kmode int; + var kmode int if mode == 'r' { kmode = syscall.EVFILT_READ } else { kmode = syscall.EVFILT_WRITE } - var events [1]syscall.Kevent_t; - ev := &events[0]; + var events [1]syscall.Kevent_t + ev := &events[0] // EV_DELETE - delete event from kqueue list // EV_RECEIPT - generate fake EV_ERROR as result of add, // rather than waiting for real event - syscall.SetKevent(ev, fd, kmode, syscall.EV_DELETE|syscall.EV_RECEIPT); - syscall.Kevent(p.kq, &events, &events, nil); + syscall.SetKevent(ev, fd, kmode, syscall.EV_DELETE|syscall.EV_RECEIPT) + syscall.Kevent(p.kq, &events, &events, nil) } func (p *pollster) WaitFD(nsec int64) (fd int, mode int, err os.Error) { - var t *syscall.Timespec; + var t *syscall.Timespec for len(p.events) == 0 { if nsec > 0 { if t == nil { t = new(syscall.Timespec) } - *t = syscall.NsecToTimespec(nsec); + *t = syscall.NsecToTimespec(nsec) } - nn, e := syscall.Kevent(p.kq, nil, &p.eventbuf, t); + nn, e := syscall.Kevent(p.kq, nil, &p.eventbuf, t) if e != 0 { if e == syscall.EINTR { continue } - return -1, 0, os.NewSyscallError("kevent", e); + return -1, 0, os.NewSyscallError("kevent", e) } if nn == 0 { return -1, 0, nil } - p.events = p.eventbuf[0:nn]; + p.events = p.eventbuf[0:nn] } - ev := &p.events[0]; - p.events = p.events[1:]; - fd = int(ev.Ident); + ev := &p.events[0] + p.events = p.events[1:] + fd = int(ev.Ident) if ev.Filter == syscall.EVFILT_READ { mode = 'r' } else { mode = 'w' } - return fd, mode, nil; + return fd, mode, nil } -func (p *pollster) Close() os.Error { return os.NewSyscallError("close", syscall.Close(p.kq)) } +func (p *pollster) Close() os.Error { return os.NewSyscallError("close", syscall.Close(p.kq)) } diff --git a/src/pkg/net/fd_freebsd.go b/src/pkg/net/fd_freebsd.go index 12a64014a..01a3c8d72 100644 --- a/src/pkg/net/fd_freebsd.go +++ b/src/pkg/net/fd_freebsd.go @@ -7,44 +7,44 @@ package net import ( - "os"; - "syscall"; + "os" + "syscall" ) type pollster struct { - kq int; - eventbuf [10]syscall.Kevent_t; - events []syscall.Kevent_t; + kq int + eventbuf [10]syscall.Kevent_t + events []syscall.Kevent_t } func newpollster() (p *pollster, err os.Error) { - p = new(pollster); - var e int; + p = new(pollster) + var e int if p.kq, e = syscall.Kqueue(); e != 0 { return nil, os.NewSyscallError("kqueue", e) } - p.events = p.eventbuf[0:0]; - return p, nil; + p.events = p.eventbuf[0:0] + return p, nil } func (p *pollster) AddFD(fd int, mode int, repeat bool) os.Error { - var kmode int; + var kmode int if mode == 'r' { kmode = syscall.EVFILT_READ } else { kmode = syscall.EVFILT_WRITE } - var events [1]syscall.Kevent_t; - ev := &events[0]; + var events [1]syscall.Kevent_t + ev := &events[0] // EV_ADD - add event to kqueue list // EV_ONESHOT - delete the event the first time it triggers - flags := syscall.EV_ADD; + flags := syscall.EV_ADD if !repeat { flags |= syscall.EV_ONESHOT } - syscall.SetKevent(ev, fd, kmode, flags); + syscall.SetKevent(ev, fd, kmode, flags) - n, e := syscall.Kevent(p.kq, &events, nil, nil); + n, e := syscall.Kevent(p.kq, &events, nil, nil) if e != 0 { return os.NewSyscallError("kevent", e) } @@ -54,53 +54,53 @@ func (p *pollster) AddFD(fd int, mode int, repeat bool) os.Error { if ev.Data != 0 { return os.Errno(int(ev.Data)) } - return nil; + return nil } func (p *pollster) DelFD(fd int, mode int) { - var kmode int; + var kmode int if mode == 'r' { kmode = syscall.EVFILT_READ } else { kmode = syscall.EVFILT_WRITE } - var events [1]syscall.Kevent_t; - ev := &events[0]; + var events [1]syscall.Kevent_t + ev := &events[0] // EV_DELETE - delete event from kqueue list - syscall.SetKevent(ev, fd, kmode, syscall.EV_DELETE); - syscall.Kevent(p.kq, &events, nil, nil); + syscall.SetKevent(ev, fd, kmode, syscall.EV_DELETE) + syscall.Kevent(p.kq, &events, nil, nil) } func (p *pollster) WaitFD(nsec int64) (fd int, mode int, err os.Error) { - var t *syscall.Timespec; + var t *syscall.Timespec for len(p.events) == 0 { if nsec > 0 { if t == nil { t = new(syscall.Timespec) } - *t = syscall.NsecToTimespec(nsec); + *t = syscall.NsecToTimespec(nsec) } - nn, e := syscall.Kevent(p.kq, nil, &p.eventbuf, t); + nn, e := syscall.Kevent(p.kq, nil, &p.eventbuf, t) if e != 0 { if e == syscall.EINTR { continue } - return -1, 0, os.NewSyscallError("kevent", e); + return -1, 0, os.NewSyscallError("kevent", e) } if nn == 0 { return -1, 0, nil } - p.events = p.eventbuf[0:nn]; + p.events = p.eventbuf[0:nn] } - ev := &p.events[0]; - p.events = p.events[1:]; - fd = int(ev.Ident); + ev := &p.events[0] + p.events = p.events[1:] + fd = int(ev.Ident) if ev.Filter == syscall.EVFILT_READ { mode = 'r' } else { mode = 'w' } - return fd, mode, nil; + return fd, mode, nil } -func (p *pollster) Close() os.Error { return os.NewSyscallError("close", syscall.Close(p.kq)) } +func (p *pollster) Close() os.Error { return os.NewSyscallError("close", syscall.Close(p.kq)) } diff --git a/src/pkg/net/fd_linux.go b/src/pkg/net/fd_linux.go index 83d66ac89..5024eec02 100644 --- a/src/pkg/net/fd_linux.go +++ b/src/pkg/net/fd_linux.go @@ -7,25 +7,25 @@ package net import ( - "os"; - "syscall"; + "os" + "syscall" ) const ( - readFlags = syscall.EPOLLIN | syscall.EPOLLRDHUP; - writeFlags = syscall.EPOLLOUT; + readFlags = syscall.EPOLLIN | syscall.EPOLLRDHUP + writeFlags = syscall.EPOLLOUT ) type pollster struct { - epfd int; + epfd int // Events we're already waiting for - events map[int]uint32; + events map[int]uint32 } func newpollster() (p *pollster, err os.Error) { - p = new(pollster); - var e int; + p = new(pollster) + var e int // The arg to epoll_create is a hint to the kernel // about the number of FDs we will care about. @@ -33,15 +33,15 @@ func newpollster() (p *pollster, err os.Error) { if p.epfd, e = syscall.EpollCreate(16); e != 0 { return nil, os.NewSyscallError("epoll_create", e) } - p.events = make(map[int]uint32); - return p, nil; + p.events = make(map[int]uint32) + return p, nil } func (p *pollster) AddFD(fd int, mode int, repeat bool) os.Error { - var ev syscall.EpollEvent; - var already bool; - ev.Fd = int32(fd); - ev.Events, already = p.events[fd]; + var ev syscall.EpollEvent + var already bool + ev.Fd = int32(fd) + ev.Events, already = p.events[fd] if !repeat { ev.Events |= syscall.EPOLLONESHOT } @@ -51,7 +51,7 @@ func (p *pollster) AddFD(fd int, mode int, repeat bool) os.Error { ev.Events |= writeFlags } - var op int; + var op int if already { op = syscall.EPOLL_CTL_MOD } else { @@ -60,15 +60,15 @@ func (p *pollster) AddFD(fd int, mode int, repeat bool) os.Error { if e := syscall.EpollCtl(p.epfd, op, fd, &ev); e != 0 { return os.NewSyscallError("epoll_ctl", e) } - p.events[fd] = ev.Events; - return nil; + p.events[fd] = ev.Events + return nil } func (p *pollster) StopWaiting(fd int, bits uint) { - events, already := p.events[fd]; + events, already := p.events[fd] if !already { - print("Epoll unexpected fd=", fd, "\n"); - return; + print("Epoll unexpected fd=", fd, "\n") + return } // If syscall.EPOLLONESHOT is not set, the wait @@ -80,20 +80,20 @@ func (p *pollster) StopWaiting(fd int, bits uint) { // Disable the given bits. // If we're still waiting for other events, modify the fd // event in the kernel. Otherwise, delete it. - events &= ^uint32(bits); + events &= ^uint32(bits) if int32(events)&^syscall.EPOLLONESHOT != 0 { - var ev syscall.EpollEvent; - ev.Fd = int32(fd); - ev.Events = events; + var ev syscall.EpollEvent + ev.Fd = int32(fd) + ev.Events = events if e := syscall.EpollCtl(p.epfd, syscall.EPOLL_CTL_MOD, fd, &ev); e != 0 { print("Epoll modify fd=", fd, ": ", os.Errno(e).String(), "\n") } - p.events[fd] = events; + p.events[fd] = events } else { if e := syscall.EpollCtl(p.epfd, syscall.EPOLL_CTL_DEL, fd, nil); e != 0 { print("Epoll delete fd=", fd, ": ", os.Errno(e).String(), "\n") } - p.events[fd] = 0, false; + p.events[fd] = 0, false } } @@ -107,13 +107,13 @@ func (p *pollster) DelFD(fd int, mode int) { func (p *pollster) WaitFD(nsec int64) (fd int, mode int, err os.Error) { // Get an event. - var evarray [1]syscall.EpollEvent; - ev := &evarray[0]; - var msec int = -1; + var evarray [1]syscall.EpollEvent + ev := &evarray[0] + var msec int = -1 if nsec > 0 { msec = int((nsec + 1e6 - 1) / 1e6) } - n, e := syscall.EpollWait(p.epfd, &evarray, msec); + n, e := syscall.EpollWait(p.epfd, &evarray, msec) for e == syscall.EAGAIN || e == syscall.EINTR { n, e = syscall.EpollWait(p.epfd, &evarray, msec) } @@ -123,25 +123,25 @@ func (p *pollster) WaitFD(nsec int64) (fd int, mode int, err os.Error) { if n == 0 { return -1, 0, nil } - fd = int(ev.Fd); + fd = int(ev.Fd) if ev.Events&writeFlags != 0 { - p.StopWaiting(fd, writeFlags); - return fd, 'w', nil; + p.StopWaiting(fd, writeFlags) + return fd, 'w', nil } if ev.Events&readFlags != 0 { - p.StopWaiting(fd, readFlags); - return fd, 'r', nil; + p.StopWaiting(fd, readFlags) + return fd, 'r', nil } // Other events are error conditions - wake whoever is waiting. - events, _ := p.events[fd]; + events, _ := p.events[fd] if events&writeFlags != 0 { - p.StopWaiting(fd, writeFlags); - return fd, 'w', nil; + p.StopWaiting(fd, writeFlags) + return fd, 'w', nil } - p.StopWaiting(fd, readFlags); - return fd, 'r', nil; + p.StopWaiting(fd, readFlags) + return fd, 'r', nil } func (p *pollster) Close() os.Error { diff --git a/src/pkg/net/fd_nacl.go b/src/pkg/net/fd_nacl.go index 22700fbed..d21db8b3a 100644 --- a/src/pkg/net/fd_nacl.go +++ b/src/pkg/net/fd_nacl.go @@ -5,8 +5,8 @@ package net import ( - "os"; - "syscall"; + "os" + "syscall" ) type pollster struct{} @@ -16,18 +16,18 @@ func newpollster() (p *pollster, err os.Error) { } func (p *pollster) AddFD(fd int, mode int, repeat bool) os.Error { - _, err := newpollster(); - return err; + _, err := newpollster() + return err } func (p *pollster) StopWaiting(fd int, bits uint) { } -func (p *pollster) DelFD(fd int, mode int) {} +func (p *pollster) DelFD(fd int, mode int) {} func (p *pollster) WaitFD(nsec int64) (fd int, mode int, err os.Error) { - _, err = newpollster(); - return; + _, err = newpollster() + return } -func (p *pollster) Close() os.Error { return nil } +func (p *pollster) Close() os.Error { return nil } diff --git a/src/pkg/net/ip.go b/src/pkg/net/ip.go index db1552890..e090d3aa6 100644 --- a/src/pkg/net/ip.go +++ b/src/pkg/net/ip.go @@ -14,8 +14,8 @@ package net // IP address lengths (bytes). const ( - IPv4len = 4; - IPv6len = 16; + IPv4len = 4 + IPv6len = 16 ) // An IP is a single IP address, an array of bytes. @@ -38,30 +38,30 @@ type IPMask []byte // IPv4 returns the IP address (in 16-byte form) of the // IPv4 address a.b.c.d. func IPv4(a, b, c, d byte) IP { - p := make(IP, IPv6len); + p := make(IP, IPv6len) for i := 0; i < 10; i++ { p[i] = 0 } - p[10] = 0xff; - p[11] = 0xff; - p[12] = a; - p[13] = b; - p[14] = c; - p[15] = d; - return p; + p[10] = 0xff + p[11] = 0xff + p[12] = a + p[13] = b + p[14] = c + p[15] = d + return p } // Well-known IPv4 addresses var ( - IPv4bcast = IPv4(255, 255, 255, 255); // broadcast - IPv4allsys = IPv4(224, 0, 0, 1); // all systems - IPv4allrouter = IPv4(224, 0, 0, 2); // all routers - IPv4zero = IPv4(0, 0, 0, 0); // all zeros + IPv4bcast = IPv4(255, 255, 255, 255) // broadcast + IPv4allsys = IPv4(224, 0, 0, 1) // all systems + IPv4allrouter = IPv4(224, 0, 0, 2) // all routers + IPv4zero = IPv4(0, 0, 0, 0) // all zeros ) // Well-known IPv6 addresses var ( - IPzero = make(IP, IPv6len); // all zeros + IPzero = make(IP, IPv6len) // all zeros ) // Is p all zeros? @@ -71,7 +71,7 @@ func isZeros(p IP) bool { return false } } - return true; + return true } // To4 converts the IPv4 address ip to a 4-byte representation. @@ -86,7 +86,7 @@ func (ip IP) To4() IP { ip[11] == 0xff { return ip[12:16] } - return nil; + return nil } // To16 converts the IP address ip to a 16-byte representation. @@ -98,14 +98,14 @@ func (ip IP) To16() IP { if len(ip) == IPv6len { return ip } - return nil; + return nil } // Default route masks for IPv4. var ( - classAMask = IPMask(IPv4(0xff, 0, 0, 0)); - classBMask = IPMask(IPv4(0xff, 0xff, 0, 0)); - classCMask = IPMask(IPv4(0xff, 0xff, 0xff, 0)); + classAMask = IPMask(IPv4(0xff, 0, 0, 0)) + classBMask = IPMask(IPv4(0xff, 0xff, 0, 0)) + classCMask = IPMask(IPv4(0xff, 0xff, 0xff, 0)) ) // DefaultMask returns the default IP mask for the IP address ip. @@ -123,20 +123,20 @@ func (ip IP) DefaultMask() IPMask { default: return classCMask } - return nil; // not reached + return nil // not reached } // Mask returns the result of masking the IP address ip with mask. func (ip IP) Mask(mask IPMask) IP { - n := len(ip); + n := len(ip) if n != len(mask) { return nil } - out := make(IP, n); + out := make(IP, n) for i := 0; i < n; i++ { out[i] = ip[i] & mask[i] } - return out; + return out } // Convert i to decimal string. @@ -146,14 +146,14 @@ func itod(i uint) string { } // Assemble decimal in reverse order. - var b [32]byte; - bp := len(b); + var b [32]byte + bp := len(b) for ; i > 0; i /= 10 { - bp--; - b[bp] = byte(i%10) + '0'; + bp-- + b[bp] = byte(i%10) + '0' } - return string(b[bp:]); + return string(b[bp:]) } // Convert i to hexadecimal string. @@ -163,14 +163,14 @@ func itox(i uint) string { } // Assemble hexadecimal in reverse order. - var b [32]byte; - bp := len(b); + var b [32]byte + bp := len(b) for ; i > 0; i /= 16 { - bp--; - b[bp] = "0123456789abcdef"[byte(i%16)]; + bp-- + b[bp] = "0123456789abcdef"[byte(i%16)] } - return string(b[bp:]); + return string(b[bp:]) } // String returns the string form of the IP address ip. @@ -178,7 +178,7 @@ func itox(i uint) string { // is dotted decimal ("74.125.19.99"). Otherwise the representation // is IPv6 ("2001:4860:0:2001::68"). func (ip IP) String() string { - p := ip; + p := ip if len(ip) == 0 { return "" @@ -196,50 +196,50 @@ func (ip IP) String() string { } // Find longest run of zeros. - e0 := -1; - e1 := -1; + e0 := -1 + e1 := -1 for i := 0; i < 16; i += 2 { - j := i; + j := i for j < 16 && p[j] == 0 && p[j+1] == 0 { j += 2 } if j > i && j-i > e1-e0 { - e0 = i; - e1 = j; + e0 = i + e1 = j } } // Print with possible :: in place of run of zeros - var s string; + var s string for i := 0; i < 16; i += 2 { if i == e0 { - s += "::"; - i = e1; + s += "::" + i = e1 if i >= 16 { break } } else if i > 0 { s += ":" } - s += itox((uint(p[i]) << 8) | uint(p[i+1])); + s += itox((uint(p[i]) << 8) | uint(p[i+1])) } - return s; + return s } // If mask is a sequence of 1 bits followed by 0 bits, // return the number of 1 bits. func simpleMaskLength(mask IPMask) int { - var i int; + var i int for i = 0; i < len(mask); i++ { if mask[i] != 0xFF { break } } - n := 8 * i; - v := mask[i]; + n := 8 * i + v := mask[i] for v&0x80 != 0 { - n++; - v <<= 1; + n++ + v <<= 1 } if v != 0 { return -1 @@ -249,7 +249,7 @@ func simpleMaskLength(mask IPMask) int { return -1 } } - return n; + return n } // String returns the string representation of mask. @@ -260,44 +260,44 @@ func simpleMaskLength(mask IPMask) int { func (mask IPMask) String() string { switch len(mask) { case 4: - n := simpleMaskLength(mask); + n := simpleMaskLength(mask) if n >= 0 { return itod(uint(n + (IPv6len-IPv4len)*8)) } case 16: - n := simpleMaskLength(mask); + n := simpleMaskLength(mask) if n >= 0 { return itod(uint(n)) } } - return IP(mask).String(); + return IP(mask).String() } // Parse IPv4 address (d.d.d.d). func parseIPv4(s string) IP { - var p [IPv4len]byte; - i := 0; + var p [IPv4len]byte + i := 0 for j := 0; j < IPv4len; j++ { if j > 0 { if s[i] != '.' { return nil } - i++; + i++ } var ( - n int; - ok bool; + n int + ok bool ) - n, i, ok = dtoi(s, i); + n, i, ok = dtoi(s, i) if !ok || n > 0xFF { return nil } - p[j] = byte(n); + p[j] = byte(n) } if i != len(s) { return nil } - return IPv4(p[0], p[1], p[2], p[3]); + return IPv4(p[0], p[1], p[2], p[3]) } // Parse IPv6 address. Many forms. @@ -309,14 +309,14 @@ func parseIPv4(s string) IP { // * The last 32 bits can be in IPv4 form. // Thus, ::ffff:1.2.3.4 is the IPv4 address 1.2.3.4. func parseIPv6(s string) IP { - p := make(IP, 16); - ellipsis := -1; // position of ellipsis in p - i := 0; // index in string s + p := make(IP, 16) + ellipsis := -1 // position of ellipsis in p + i := 0 // index in string s // Might have leading ellipsis if len(s) >= 2 && s[0] == ':' && s[1] == ':' { - ellipsis = 0; - i = 2; + ellipsis = 0 + i = 2 // Might be only ellipsis if i == len(s) { return p @@ -324,10 +324,10 @@ func parseIPv6(s string) IP { } // Loop, parsing hex numbers followed by colon. - j := 0; -L: for j < IPv6len { + j := 0 +L: for j < IPv6len { // Hex number. - n, i1, ok := xtoi(s, i); + n, i1, ok := xtoi(s, i) if !ok || n > 0xFFFF { return nil } @@ -342,26 +342,26 @@ L: for j < IPv6len { // Not enough room. return nil } - p4 := parseIPv4(s[i:]); + p4 := parseIPv4(s[i:]) if p4 == nil { return nil } - p[j] = p4[12]; - p[j+1] = p4[13]; - p[j+2] = p4[14]; - p[j+3] = p4[15]; - i = len(s); - j += 4; - break; + p[j] = p4[12] + p[j+1] = p4[13] + p[j+2] = p4[14] + p[j+3] = p4[15] + i = len(s) + j += 4 + break } // Save this 16-bit chunk. - p[j] = byte(n >> 8); - p[j+1] = byte(n); - j += 2; + p[j] = byte(n >> 8) + p[j+1] = byte(n) + j += 2 // Stop at end of string. - i = i1; + i = i1 if i == len(s) { break } @@ -370,15 +370,15 @@ L: for j < IPv6len { if s[i] != ':' && i+1 == len(s) { return nil } - i++; + i++ // Look for ellipsis. if s[i] == ':' { - if ellipsis >= 0 { // already have one + if ellipsis >= 0 { // already have one return nil } - ellipsis = j; - if i++; i == len(s) { // can be at end + ellipsis = j + if i++; i == len(s) { // can be at end break } } @@ -394,7 +394,7 @@ L: for j < IPv6len { if ellipsis < 0 { return nil } - n := IPv6len - j; + n := IPv6len - j for k := j - 1; k >= ellipsis; k-- { p[k+n] = p[k] } @@ -402,7 +402,7 @@ L: for j < IPv6len { p[k] = 0 } } - return p; + return p } // ParseIP parses s as an IP address, returning the result. @@ -411,9 +411,9 @@ L: for j < IPv6len { // If s is not a valid textual representation of an IP address, // ParseIP returns nil. func ParseIP(s string) IP { - p := parseIPv4(s); + p := parseIPv4(s) if p != nil { return p } - return parseIPv6(s); + return parseIPv6(s) } diff --git a/src/pkg/net/ip_test.go b/src/pkg/net/ip_test.go index 7cca831b5..0ea1d9260 100644 --- a/src/pkg/net/ip_test.go +++ b/src/pkg/net/ip_test.go @@ -5,7 +5,7 @@ package net import ( - "testing"; + "testing" ) func isEqual(a, b IP) bool { @@ -20,12 +20,12 @@ func isEqual(a, b IP) bool { return false } } - return true; + return true } type parseIPTest struct { - in string; - out IP; + in string + out IP } var parseiptests = []parseIPTest{ @@ -44,7 +44,7 @@ var parseiptests = []parseIPTest{ func TestParseIP(t *testing.T) { for i := 0; i < len(parseiptests); i++ { - tt := parseiptests[i]; + tt := parseiptests[i] if out := ParseIP(tt.in); !isEqual(out, tt.out) { t.Errorf("ParseIP(%#q) = %v, want %v", tt.in, out, tt.out) } diff --git a/src/pkg/net/ipsock.go b/src/pkg/net/ipsock.go index f61d22ac9..879bae33e 100644 --- a/src/pkg/net/ipsock.go +++ b/src/pkg/net/ipsock.go @@ -7,8 +7,8 @@ package net import ( - "os"; - "syscall"; + "os" + "syscall" ) // Should we try to use the IPv4 socket interface if we're @@ -22,11 +22,11 @@ func kernelSupportsIPv6() bool { if syscall.OS == "freebsd" { return false } - fd, e := syscall.Socket(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_TCP); + fd, e := syscall.Socket(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_TCP) if fd >= 0 { syscall.Close(fd) } - return e == 0; + return e == 0 } var preferIPv4 = !kernelSupportsIPv6() @@ -34,22 +34,22 @@ var preferIPv4 = !kernelSupportsIPv6() // TODO(rsc): if syscall.OS == "linux", we're supposd to read // /proc/sys/net/core/somaxconn, // to take advantage of kernels that have raised the limit. -func listenBacklog() int { return syscall.SOMAXCONN } +func listenBacklog() int { return syscall.SOMAXCONN } // Internet sockets (TCP, UDP) // A sockaddr represents a TCP or UDP network address that can // be converted into a syscall.Sockaddr. type sockaddr interface { - Addr; - sockaddr(family int) (syscall.Sockaddr, os.Error); - family() int; + Addr + sockaddr(family int) (syscall.Sockaddr, os.Error) + family() int } func internetSocket(net string, laddr, raddr sockaddr, proto int, mode string, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err os.Error) { // Figure out IP version. // If network has a suffix like "tcp4", obey it. - family := syscall.AF_INET6; + family := syscall.AF_INET6 switch net[len(net)-1] { case '4': family = syscall.AF_INET @@ -65,7 +65,7 @@ func internetSocket(net string, laddr, raddr sockaddr, proto int, mode string, t } } - var la, ra syscall.Sockaddr; + var la, ra syscall.Sockaddr if laddr != nil { if la, err = laddr.sockaddr(family); err != nil { goto Error @@ -76,25 +76,25 @@ func internetSocket(net string, laddr, raddr sockaddr, proto int, mode string, t goto Error } } - fd, err = socket(net, family, proto, 0, la, ra, toAddr); + fd, err = socket(net, family, proto, 0, la, ra, toAddr) if err != nil { goto Error } - return fd, nil; + return fd, nil Error: - addr := raddr; + addr := raddr if mode == "listen" { addr = laddr } - return nil, &OpError{mode, net, addr, err}; + return nil, &OpError{mode, net, addr, err} } func getip(fd int, remote bool) (ip []byte, port int, ok bool) { // No attempt at error reporting because // there are no possible errors, and the // caller won't report them anyway. - var sa syscall.Sockaddr; + var sa syscall.Sockaddr if remote { sa, _ = syscall.Getpeername(fd) } else { @@ -106,7 +106,7 @@ func getip(fd int, remote bool) (ip []byte, port int, ok bool) { case *syscall.SockaddrInet6: return &sa.Addr, sa.Port, true } - return; + return } func ipToSockaddr(family int, ip IP, port int) (syscall.Sockaddr, os.Error) { @@ -118,12 +118,12 @@ func ipToSockaddr(family int, ip IP, port int) (syscall.Sockaddr, os.Error) { if ip = ip.To4(); ip == nil { return nil, os.EINVAL } - s := new(syscall.SockaddrInet4); + s := new(syscall.SockaddrInet4) for i := 0; i < IPv4len; i++ { s.Addr[i] = ip[i] } - s.Port = port; - return s, nil; + s.Port = port + return s, nil case syscall.AF_INET6: if len(ip) == 0 { ip = IPzero @@ -137,27 +137,27 @@ func ipToSockaddr(family int, ip IP, port int) (syscall.Sockaddr, os.Error) { if ip = ip.To16(); ip == nil { return nil, os.EINVAL } - s := new(syscall.SockaddrInet6); + s := new(syscall.SockaddrInet6) for i := 0; i < IPv6len; i++ { s.Addr[i] = ip[i] } - s.Port = port; - return s, nil; + s.Port = port + return s, nil } - return nil, os.EINVAL; + return nil, os.EINVAL } // Split "host:port" into "host" and "port". // Host cannot contain colons unless it is bracketed. func splitHostPort(hostport string) (host, port string, err os.Error) { // The port starts after the last colon. - i := last(hostport, ':'); + i := last(hostport, ':') if i < 0 { - err = &AddrError{"missing port in address", hostport}; - return; + err = &AddrError{"missing port in address", hostport} + return } - host, port = hostport[0:i], hostport[i+1:]; + host, port = hostport[0:i], hostport[i+1:] // Can put brackets around host ... if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' { @@ -165,11 +165,11 @@ func splitHostPort(hostport string) (host, port string, err os.Error) { } else { // ... but if there are no brackets, no colons. if byteIndex(host, ':') >= 0 { - err = &AddrError{"too many colons in address", hostport}; - return; + err = &AddrError{"too many colons in address", hostport} + return } } - return; + return } // Join "host" and "port" into "host:port". @@ -179,50 +179,50 @@ func joinHostPort(host, port string) string { if byteIndex(host, ':') >= 0 { return "[" + host + "]:" + port } - return host + ":" + port; + return host + ":" + port } // Convert "host:port" into IP address and port. func hostPortToIP(net, hostport string) (ip IP, iport int, err os.Error) { - host, port, err := splitHostPort(hostport); + host, port, err := splitHostPort(hostport) if err != nil { goto Error } - var addr IP; + var addr IP if host != "" { // Try as an IP address. - addr = ParseIP(host); + addr = ParseIP(host) if addr == nil { // Not an IP address. Try as a DNS name. - _, addrs, err1 := LookupHost(host); + _, addrs, err1 := LookupHost(host) if err1 != nil { - err = err1; - goto Error; + err = err1 + goto Error } - addr = ParseIP(addrs[0]); + addr = ParseIP(addrs[0]) if addr == nil { // should not happen - err = &AddrError{"LookupHost returned invalid address", addrs[0]}; - goto Error; + err = &AddrError{"LookupHost returned invalid address", addrs[0]} + goto Error } } } - p, i, ok := dtoi(port, 0); + p, i, ok := dtoi(port, 0) if !ok || i != len(port) { - p, err = LookupPort(net, port); + p, err = LookupPort(net, port) if err != nil { goto Error } } if p < 0 || p > 0xFFFF { - err = &AddrError{"invalid port", port}; - goto Error; + err = &AddrError{"invalid port", port} + goto Error } - return addr, p, nil; + return addr, p, nil Error: - return nil, 0, err; + return nil, 0, err } diff --git a/src/pkg/net/net.go b/src/pkg/net/net.go index c72f5c1fd..5e6ba8c20 100644 --- a/src/pkg/net/net.go +++ b/src/pkg/net/net.go @@ -15,8 +15,8 @@ import "os" // Addr represents a network end point address. type Addr interface { - Network() string; // name of the network - String() string; // string form of address + Network() string // name of the network + String() string // string form of address } // Conn is a generic stream-oriented network connection. @@ -24,37 +24,37 @@ type Conn interface { // Read reads data from the connection. // Read can be made to time out and return err == os.EAGAIN // after a fixed time limit; see SetTimeout and SetReadTimeout. - Read(b []byte) (n int, err os.Error); + Read(b []byte) (n int, err os.Error) // Write writes data to the connection. // Write can be made to time out and return err == os.EAGAIN // after a fixed time limit; see SetTimeout and SetReadTimeout. - Write(b []byte) (n int, err os.Error); + Write(b []byte) (n int, err os.Error) // Close closes the connection. - Close() os.Error; + Close() os.Error // LocalAddr returns the local network address. - LocalAddr() Addr; + LocalAddr() Addr // RemoteAddr returns the remote network address. - RemoteAddr() Addr; + RemoteAddr() Addr // SetTimeout sets the read and write deadlines associated // with the connection. - SetTimeout(nsec int64) os.Error; + SetTimeout(nsec int64) os.Error // SetReadTimeout sets the time (in nanoseconds) that // Read will wait for data before returning os.EAGAIN. // Setting nsec == 0 (the default) disables the deadline. - SetReadTimeout(nsec int64) os.Error; + SetReadTimeout(nsec int64) os.Error // SetWriteTimeout sets the time (in nanoseconds) that // Write will wait to send its data before returning os.EAGAIN. // Setting nsec == 0 (the default) disables the deadline. // Even if write times out, it may return n > 0, indicating that // some of the data was successfully written. - SetWriteTimeout(nsec int64) os.Error; + SetWriteTimeout(nsec int64) os.Error } // PacketConn is a generic packet-oriented network connection. @@ -65,43 +65,43 @@ type PacketConn interface { // was on the packet. // ReadFrom can be made to time out and return err == os.EAGAIN // after a fixed time limit; see SetTimeout and SetReadTimeout. - ReadFrom(b []byte) (n int, addr Addr, err os.Error); + ReadFrom(b []byte) (n int, addr Addr, err os.Error) // WriteTo writes a packet with payload b to addr. // WriteTo can be made to time out and return err == os.EAGAIN // after a fixed time limit; see SetTimeout and SetWriteTimeout. // On packet-oriented connections, write timeouts are rare. - WriteTo(b []byte, addr Addr) (n int, err os.Error); + WriteTo(b []byte, addr Addr) (n int, err os.Error) // Close closes the connection. - Close() os.Error; + Close() os.Error // LocalAddr returns the local network address. - LocalAddr() Addr; + LocalAddr() Addr // SetTimeout sets the read and write deadlines associated // with the connection. - SetTimeout(nsec int64) os.Error; + SetTimeout(nsec int64) os.Error // SetReadTimeout sets the time (in nanoseconds) that // Read will wait for data before returning os.EAGAIN. // Setting nsec == 0 (the default) disables the deadline. - SetReadTimeout(nsec int64) os.Error; + SetReadTimeout(nsec int64) os.Error // SetWriteTimeout sets the time (in nanoseconds) that // Write will wait to send its data before returning os.EAGAIN. // Setting nsec == 0 (the default) disables the deadline. // Even if write times out, it may return n > 0, indicating that // some of the data was successfully written. - SetWriteTimeout(nsec int64) os.Error; + SetWriteTimeout(nsec int64) os.Error } // A Listener is a generic network listener for stream-oriented protocols. // Accept waits for the next connection and Close closes the connection. type Listener interface { - Accept() (c Conn, err os.Error); - Close() os.Error; - Addr() Addr; // Listener's network address + Accept() (c Conn, err os.Error) + Close() os.Error + Addr() Addr // Listener's network address } // Dial connects to the remote address raddr on the network net. @@ -123,7 +123,7 @@ type Listener interface { func Dial(net, laddr, raddr string) (c Conn, err os.Error) { switch net { case "tcp", "tcp4", "tcp6": - var la, ra *TCPAddr; + var la, ra *TCPAddr if laddr != "" { if la, err = ResolveTCPAddr(laddr); err != nil { goto Error @@ -134,9 +134,9 @@ func Dial(net, laddr, raddr string) (c Conn, err os.Error) { goto Error } } - return DialTCP(net, la, ra); + return DialTCP(net, la, ra) case "udp", "udp4", "upd6": - var la, ra *UDPAddr; + var la, ra *UDPAddr if laddr != "" { if la, err = ResolveUDPAddr(laddr); err != nil { goto Error @@ -147,9 +147,9 @@ func Dial(net, laddr, raddr string) (c Conn, err os.Error) { goto Error } } - return DialUDP(net, la, ra); + return DialUDP(net, la, ra) case "unix", "unixgram": - var la, ra *UnixAddr; + var la, ra *UnixAddr if raddr != "" { if ra, err = ResolveUnixAddr(net, raddr); err != nil { goto Error @@ -160,11 +160,11 @@ func Dial(net, laddr, raddr string) (c Conn, err os.Error) { goto Error } } - return DialUnix(net, la, ra); + return DialUnix(net, la, ra) } - err = UnknownNetworkError(net); + err = UnknownNetworkError(net) Error: - return nil, &OpError{"dial", net + " " + raddr, nil, err}; + return nil, &OpError{"dial", net + " " + raddr, nil, err} } // Listen announces on the local network address laddr. @@ -173,31 +173,31 @@ Error: func Listen(net, laddr string) (l Listener, err os.Error) { switch net { case "tcp", "tcp4", "tcp6": - var la *TCPAddr; + var la *TCPAddr if laddr != "" { if la, err = ResolveTCPAddr(laddr); err != nil { return nil, err } } - l, err := ListenTCP(net, la); + l, err := ListenTCP(net, la) if err != nil { return nil, err } - return l, nil; + return l, nil case "unix": - var la *UnixAddr; + var la *UnixAddr if laddr != "" { if la, err = ResolveUnixAddr(net, laddr); err != nil { return nil, err } } - l, err := ListenUnix(net, la); + l, err := ListenUnix(net, la) if err != nil { return nil, err } - return l, nil; + return l, nil } - return nil, UnknownNetworkError(net); + return nil, UnknownNetworkError(net) } // ListenPacket announces on the local network address laddr. @@ -206,67 +206,67 @@ func Listen(net, laddr string) (l Listener, err os.Error) { func ListenPacket(net, laddr string) (c PacketConn, err os.Error) { switch net { case "udp", "udp4", "udp6": - var la *UDPAddr; + var la *UDPAddr if laddr != "" { if la, err = ResolveUDPAddr(laddr); err != nil { return nil, err } } - c, err := ListenUDP(net, la); + c, err := ListenUDP(net, la) if err != nil { return nil, err } - return c, nil; + return c, nil case "unixgram": - var la *UnixAddr; + var la *UnixAddr if laddr != "" { if la, err = ResolveUnixAddr(net, laddr); err != nil { return nil, err } } - c, err := DialUnix(net, la, nil); + c, err := DialUnix(net, la, nil) if err != nil { return nil, err } - return c, nil; + return c, nil } - return nil, UnknownNetworkError(net); + return nil, UnknownNetworkError(net) } var errMissingAddress = os.ErrorString("missing address") type OpError struct { - Op string; - Net string; - Addr Addr; - Error os.Error; + Op string + Net string + Addr Addr + Error os.Error } func (e *OpError) String() string { - s := e.Op; + s := e.Op if e.Net != "" { s += " " + e.Net } if e.Addr != nil { s += " " + e.Addr.String() } - s += ": " + e.Error.String(); - return s; + s += ": " + e.Error.String() + return s } type AddrError struct { - Error string; - Addr string; + Error string + Addr string } func (e *AddrError) String() string { - s := e.Error; + s := e.Error if e.Addr != "" { s += " " + e.Addr } - return s; + return s } type UnknownNetworkError string -func (e UnknownNetworkError) String() string { return "unknown network " + string(e) } +func (e UnknownNetworkError) String() string { return "unknown network " + string(e) } diff --git a/src/pkg/net/net_test.go b/src/pkg/net/net_test.go index 43c10f1d0..72f7303ea 100644 --- a/src/pkg/net/net_test.go +++ b/src/pkg/net/net_test.go @@ -5,18 +5,18 @@ package net import ( - "flag"; - "regexp"; - "testing"; + "flag" + "regexp" + "testing" ) var runErrorTest = flag.Bool("run_error_test", false, "let TestDialError check for dns errors") type DialErrorTest struct { - Net string; - Laddr string; - Raddr string; - Pattern string; + Net string + Laddr string + Raddr string + Pattern string } var dialErrorTests = []DialErrorTest{ @@ -56,20 +56,20 @@ var dialErrorTests = []DialErrorTest{ func TestDialError(t *testing.T) { if !*runErrorTest { - t.Logf("test disabled; use --run_error_test to enable"); - return; + t.Logf("test disabled; use --run_error_test to enable") + return } for i, tt := range dialErrorTests { - c, e := Dial(tt.Net, tt.Laddr, tt.Raddr); + c, e := Dial(tt.Net, tt.Laddr, tt.Raddr) if c != nil { c.Close() } if e == nil { - t.Errorf("#%d: nil error, want match for %#q", i, tt.Pattern); - continue; + t.Errorf("#%d: nil error, want match for %#q", i, tt.Pattern) + continue } - s := e.String(); - match, _ := regexp.MatchString(tt.Pattern, s); + s := e.String() + match, _ := regexp.MatchString(tt.Pattern, s) if !match { t.Errorf("#%d: %q, want match for %#q", i, s, tt.Pattern) } diff --git a/src/pkg/net/parse.go b/src/pkg/net/parse.go index c93f8335c..a7dcb35f0 100644 --- a/src/pkg/net/parse.go +++ b/src/pkg/net/parse.go @@ -8,34 +8,34 @@ package net import ( - "io"; - "os"; + "io" + "os" ) type file struct { - file *os.File; - data []byte; + file *os.File + data []byte } -func (f *file) close() { f.file.Close() } +func (f *file) close() { f.file.Close() } func (f *file) getLineFromData() (s string, ok bool) { - data := f.data; + data := f.data for i := 0; i < len(data); i++ { if data[i] == '\n' { - s = string(data[0:i]); - ok = true; + s = string(data[0:i]) + ok = true // move data - i++; - n := len(data) - i; + i++ + n := len(data) - i for j := 0; j < n; j++ { data[j] = data[i+j] } - f.data = data[0:n]; - return; + f.data = data[0:n] + return } } - return; + return } func (f *file) readLine() (s string, ok bool) { @@ -43,22 +43,22 @@ func (f *file) readLine() (s string, ok bool) { return } if len(f.data) < cap(f.data) { - ln := len(f.data); - n, _ := io.ReadFull(f.file, f.data[ln:cap(f.data)]); + ln := len(f.data) + n, _ := io.ReadFull(f.file, f.data[ln:cap(f.data)]) if n >= 0 { f.data = f.data[0 : ln+n] } } - s, ok = f.getLineFromData(); - return; + s, ok = f.getLineFromData() + return } func open(name string) (*file, os.Error) { - fd, err := os.Open(name, os.O_RDONLY, 0); + fd, err := os.Open(name, os.O_RDONLY, 0) if err != nil { return nil, err } - return &file{fd, make([]byte, 1024)[0:0]}, nil; + return &file{fd, make([]byte, 1024)[0:0]}, nil } func byteIndex(s string, c byte) int { @@ -67,42 +67,42 @@ func byteIndex(s string, c byte) int { return i } } - return -1; + return -1 } // Count occurrences in s of any bytes in t. func countAnyByte(s string, t string) int { - n := 0; + n := 0 for i := 0; i < len(s); i++ { if byteIndex(t, s[i]) >= 0 { n++ } } - return n; + return n } // Split s at any bytes in t. func splitAtBytes(s string, t string) []string { - a := make([]string, 1+countAnyByte(s, t)); - n := 0; - last := 0; + a := make([]string, 1+countAnyByte(s, t)) + n := 0 + last := 0 for i := 0; i < len(s); i++ { if byteIndex(t, s[i]) >= 0 { if last < i { - a[n] = string(s[last:i]); - n++; + a[n] = string(s[last:i]) + n++ } - last = i + 1; + last = i + 1 } } if last < len(s) { - a[n] = string(s[last:]); - n++; + a[n] = string(s[last:]) + n++ } - return a[0:n]; + return a[0:n] } -func getFields(s string) []string { return splitAtBytes(s, " \r\t\n") } +func getFields(s string) []string { return splitAtBytes(s, " \r\t\n") } // Bigger than we need, not too big to worry about overflow const big = 0xFFFFFF @@ -110,9 +110,9 @@ const big = 0xFFFFFF // Decimal to integer starting at &s[i0]. // Returns number, new offset, success. func dtoi(s string, i0 int) (n int, i int, ok bool) { - n = 0; + n = 0 for i = i0; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ { - n = n*10 + int(s[i]-'0'); + n = n*10 + int(s[i]-'0') if n >= big { return 0, i, false } @@ -120,23 +120,23 @@ func dtoi(s string, i0 int) (n int, i int, ok bool) { if i == i0 { return 0, i, false } - return n, i, true; + return n, i, true } // Hexadecimal to integer starting at &s[i0]. // Returns number, new offset, success. func xtoi(s string, i0 int) (n int, i int, ok bool) { - n = 0; + n = 0 for i = i0; i < len(s); i++ { if '0' <= s[i] && s[i] <= '9' { - n *= 16; - n += int(s[i] - '0'); + n *= 16 + n += int(s[i] - '0') } else if 'a' <= s[i] && s[i] <= 'f' { - n *= 16; - n += int(s[i]-'a') + 10; + n *= 16 + n += int(s[i]-'a') + 10 } else if 'A' <= s[i] && s[i] <= 'F' { - n *= 16; - n += int(s[i]-'A') + 10; + n *= 16 + n += int(s[i]-'A') + 10 } else { break } @@ -147,49 +147,49 @@ func xtoi(s string, i0 int) (n int, i int, ok bool) { if i == i0 { return 0, i, false } - return n, i, true; + return n, i, true } // Integer to decimal. func itoa(i int) string { - var buf [30]byte; - n := len(buf); - neg := false; + var buf [30]byte + n := len(buf) + neg := false if i < 0 { - i = -i; - neg = true; + i = -i + neg = true } - ui := uint(i); + ui := uint(i) for ui > 0 || n == len(buf) { - n--; - buf[n] = byte('0' + ui%10); - ui /= 10; + n-- + buf[n] = byte('0' + ui%10) + ui /= 10 } if neg { - n--; - buf[n] = '-'; + n-- + buf[n] = '-' } - return string(buf[n:]); + return string(buf[n:]) } // Number of occurrences of b in s. func count(s string, b byte) int { - n := 0; + n := 0 for i := 0; i < len(s); i++ { if s[i] == b { n++ } } - return n; + return n } // Index of rightmost occurrence of b in s. func last(s string, b byte) int { - i := len(s); + i := len(s) for i--; i >= 0; i-- { if s[i] == b { break } } - return i; + return i } diff --git a/src/pkg/net/parse_test.go b/src/pkg/net/parse_test.go index 29b0fc0ce..d011c0076 100644 --- a/src/pkg/net/parse_test.go +++ b/src/pkg/net/parse_test.go @@ -5,34 +5,34 @@ package net import ( - "bufio"; - "os"; - "testing"; + "bufio" + "os" + "testing" ) func TestReadLine(t *testing.T) { - filename := "/etc/services"; // a nice big file + filename := "/etc/services" // a nice big file - fd, err := os.Open(filename, os.O_RDONLY, 0); + fd, err := os.Open(filename, os.O_RDONLY, 0) if err != nil { t.Fatalf("open %s: %v", filename, err) } - br := bufio.NewReader(fd); + br := bufio.NewReader(fd) - var file *file; - file, err = open(filename); + var file *file + file, err = open(filename) if file == nil { t.Fatalf("net.open(%s) = nil", filename) } - lineno := 1; - byteno := 0; + lineno := 1 + byteno := 0 for { - bline, berr := br.ReadString('\n'); + bline, berr := br.ReadString('\n') if n := len(bline); n > 0 { bline = bline[0 : n-1] } - line, ok := file.readLine(); + line, ok := file.readLine() if (berr != nil) != !ok || bline != line { t.Fatalf("%s:%d (#%d)\nbufio => %q, %v\nnet => %q, %v", filename, lineno, byteno, bline, berr, line, ok) @@ -40,7 +40,7 @@ func TestReadLine(t *testing.T) { if !ok { break } - lineno++; - byteno += len(line) + 1; + lineno++ + byteno += len(line) + 1 } } diff --git a/src/pkg/net/port.go b/src/pkg/net/port.go index b496f5308..5f182d0d1 100644 --- a/src/pkg/net/port.go +++ b/src/pkg/net/port.go @@ -7,49 +7,49 @@ package net import ( - "once"; - "os"; + "once" + "os" ) var services map[string]map[string]int var servicesError os.Error func readServices() { - services = make(map[string]map[string]int); - var file *file; - file, servicesError = open("/etc/services"); + services = make(map[string]map[string]int) + var file *file + file, servicesError = open("/etc/services") for line, ok := file.readLine(); ok; line, ok = file.readLine() { // "http 80/tcp www www-http # World Wide Web HTTP" if i := byteIndex(line, '#'); i >= 0 { line = line[0:i] } - f := getFields(line); + f := getFields(line) if len(f) < 2 { continue } - portnet := f[1]; // "tcp/80" - port, j, ok := dtoi(portnet, 0); + portnet := f[1] // "tcp/80" + port, j, ok := dtoi(portnet, 0) if !ok || port <= 0 || j >= len(portnet) || portnet[j] != '/' { continue } - netw := portnet[j+1:]; // "tcp" - m, ok1 := services[netw]; + netw := portnet[j+1:] // "tcp" + m, ok1 := services[netw] if !ok1 { - m = make(map[string]int); - services[netw] = m; + m = make(map[string]int) + services[netw] = m } for i := 0; i < len(f); i++ { - if i != 1 { // f[1] was port/net + if i != 1 { // f[1] was port/net m[f[i]] = port } } } - file.close(); + file.close() } // LookupPort looks up the port for the given network and service. func LookupPort(network, service string) (port int, err os.Error) { - once.Do(readServices); + once.Do(readServices) switch network { case "tcp4", "tcp6": @@ -63,5 +63,5 @@ func LookupPort(network, service string) (port int, err os.Error) { return } } - return 0, &AddrError{"unknown port", network + "/" + service}; + return 0, &AddrError{"unknown port", network + "/" + service} } diff --git a/src/pkg/net/port_test.go b/src/pkg/net/port_test.go index 9a58d3731..4eb53dc93 100644 --- a/src/pkg/net/port_test.go +++ b/src/pkg/net/port_test.go @@ -5,14 +5,14 @@ package net import ( - "testing"; + "testing" ) type portTest struct { - netw string; - name string; - port int; - ok bool; + netw string + name string + port int + ok bool } var porttests = []portTest{ @@ -49,7 +49,7 @@ var porttests = []portTest{ func TestLookupPort(t *testing.T) { for i := 0; i < len(porttests); i++ { - tt := porttests[i]; + tt := porttests[i] if port, err := LookupPort(tt.netw, tt.name); port != tt.port || (err == nil) != tt.ok { t.Errorf("LookupPort(%q, %q) = %v, %s; want %v", tt.netw, tt.name, port, err, tt.port) diff --git a/src/pkg/net/server_test.go b/src/pkg/net/server_test.go index 404108106..3b8f1c935 100644 --- a/src/pkg/net/server_test.go +++ b/src/pkg/net/server_test.go @@ -5,12 +5,12 @@ package net import ( - "flag"; - "io"; - "os"; - "strings"; - "syscall"; - "testing"; + "flag" + "io" + "os" + "strings" + "syscall" + "testing" ) // Do not test empty datagrams by default. @@ -20,97 +20,97 @@ import ( var testEmptyDatagrams = flag.Bool("empty_datagrams", false, "whether to test empty datagrams") func runEcho(fd io.ReadWriter, done chan<- int) { - var buf [1024]byte; + var buf [1024]byte for { - n, err := fd.Read(&buf); + n, err := fd.Read(&buf) if err != nil || n == 0 { break } - fd.Write(buf[0:n]); + fd.Write(buf[0:n]) } - done <- 1; + done <- 1 } func runServe(t *testing.T, network, addr string, listening chan<- string, done chan<- int) { - l, err := Listen(network, addr); + l, err := Listen(network, addr) if err != nil { t.Fatalf("net.Listen(%q, %q) = _, %v", network, addr, err) } - listening <- l.Addr().String(); + listening <- l.Addr().String() for { - fd, err := l.Accept(); + fd, err := l.Accept() if err != nil { break } - echodone := make(chan int); - go runEcho(fd, echodone); - <-echodone; // make sure Echo stops - l.Close(); + echodone := make(chan int) + go runEcho(fd, echodone) + <-echodone // make sure Echo stops + l.Close() } - done <- 1; + done <- 1 } func connect(t *testing.T, network, addr string, isEmpty bool) { - var laddr string; + var laddr string if network == "unixgram" { laddr = addr + ".local" } - fd, err := Dial(network, laddr, addr); + fd, err := Dial(network, laddr, addr) if err != nil { t.Fatalf("net.Dial(%q, %q, %q) = _, %v", network, laddr, addr, err) } - fd.SetReadTimeout(1e9); // 1s + fd.SetReadTimeout(1e9) // 1s - var b []byte; + var b []byte if !isEmpty { b = strings.Bytes("hello, world\n") } - var b1 [100]byte; + var b1 [100]byte - n, err := fd.Write(b); + n, err := fd.Write(b) if n != len(b) { t.Fatalf("fd.Write(%q) = %d, %v", b, n, err) } - n, err = fd.Read(&b1); + n, err = fd.Read(&b1) if n != len(b) || err != nil { t.Fatalf("fd.Read() = %d, %v (want %d, nil)", n, err, len(b)) } - fd.Close(); + fd.Close() } func doTest(t *testing.T, network, listenaddr, dialaddr string) { - t.Logf("Test %s %s %s\n", network, listenaddr, dialaddr); - listening := make(chan string); - done := make(chan int); + t.Logf("Test %s %s %s\n", network, listenaddr, dialaddr) + listening := make(chan string) + done := make(chan int) if network == "tcp" { - listenaddr += ":0" // any available port + listenaddr += ":0" // any available port } - go runServe(t, network, listenaddr, listening, done); - addr := <-listening; // wait for server to start + go runServe(t, network, listenaddr, listening, done) + addr := <-listening // wait for server to start if network == "tcp" { dialaddr += addr[strings.LastIndex(addr, ":"):] } - connect(t, network, dialaddr, false); - <-done; // make sure server stopped + connect(t, network, dialaddr, false) + <-done // make sure server stopped } func TestTCPServer(t *testing.T) { - doTest(t, "tcp", "0.0.0.0", "127.0.0.1"); - doTest(t, "tcp", "", "127.0.0.1"); + doTest(t, "tcp", "0.0.0.0", "127.0.0.1") + doTest(t, "tcp", "", "127.0.0.1") if kernelSupportsIPv6() { - doTest(t, "tcp", "[::]", "[::ffff:127.0.0.1]"); - doTest(t, "tcp", "[::]", "127.0.0.1"); - doTest(t, "tcp", "0.0.0.0", "[::ffff:127.0.0.1]"); + doTest(t, "tcp", "[::]", "[::ffff:127.0.0.1]") + doTest(t, "tcp", "[::]", "127.0.0.1") + doTest(t, "tcp", "0.0.0.0", "[::ffff:127.0.0.1]") } } func TestUnixServer(t *testing.T) { - os.Remove("/tmp/gotest.net"); - doTest(t, "unix", "/tmp/gotest.net", "/tmp/gotest.net"); - os.Remove("/tmp/gotest.net"); + os.Remove("/tmp/gotest.net") + doTest(t, "unix", "/tmp/gotest.net", "/tmp/gotest.net") + os.Remove("/tmp/gotest.net") if syscall.OS == "linux" { // Test abstract unix domain socket, a Linux-ism doTest(t, "unix", "@gotest/net", "@gotest/net") @@ -118,20 +118,20 @@ func TestUnixServer(t *testing.T) { } func runPacket(t *testing.T, network, addr string, listening chan<- string, done chan<- int) { - c, err := ListenPacket(network, addr); + c, err := ListenPacket(network, addr) if err != nil { t.Fatalf("net.ListenPacket(%q, %q) = _, %v", network, addr, err) } - listening <- c.LocalAddr().String(); - c.SetReadTimeout(10e6); // 10ms - var buf [1000]byte; + listening <- c.LocalAddr().String() + c.SetReadTimeout(10e6) // 10ms + var buf [1000]byte for { - n, addr, err := c.ReadFrom(&buf); + n, addr, err := c.ReadFrom(&buf) if isEAGAIN(err) { if done <- 1 { break } - continue; + continue } if err != nil { break @@ -140,46 +140,46 @@ func runPacket(t *testing.T, network, addr string, listening chan<- string, done t.Fatalf("WriteTo %v: %v", addr, err) } } - c.Close(); - done <- 1; + c.Close() + done <- 1 } func doTestPacket(t *testing.T, network, listenaddr, dialaddr string, isEmpty bool) { - t.Logf("TestPacket %s %s %s\n", network, listenaddr, dialaddr); - listening := make(chan string); - done := make(chan int); + t.Logf("TestPacket %s %s %s\n", network, listenaddr, dialaddr) + listening := make(chan string) + done := make(chan int) if network == "udp" { - listenaddr += ":0" // any available port + listenaddr += ":0" // any available port } - go runPacket(t, network, listenaddr, listening, done); - addr := <-listening; // wait for server to start + go runPacket(t, network, listenaddr, listening, done) + addr := <-listening // wait for server to start if network == "udp" { dialaddr += addr[strings.LastIndex(addr, ":"):] } - connect(t, network, dialaddr, isEmpty); - <-done; // tell server to stop - <-done; // wait for stop + connect(t, network, dialaddr, isEmpty) + <-done // tell server to stop + <-done // wait for stop } func TestUDPServer(t *testing.T) { for _, isEmpty := range []bool{false, *testEmptyDatagrams} { - doTestPacket(t, "udp", "0.0.0.0", "127.0.0.1", isEmpty); - doTestPacket(t, "udp", "", "127.0.0.1", isEmpty); + doTestPacket(t, "udp", "0.0.0.0", "127.0.0.1", isEmpty) + doTestPacket(t, "udp", "", "127.0.0.1", isEmpty) if kernelSupportsIPv6() { - doTestPacket(t, "udp", "[::]", "[::ffff:127.0.0.1]", isEmpty); - doTestPacket(t, "udp", "[::]", "127.0.0.1", isEmpty); - doTestPacket(t, "udp", "0.0.0.0", "[::ffff:127.0.0.1]", isEmpty); + doTestPacket(t, "udp", "[::]", "[::ffff:127.0.0.1]", isEmpty) + doTestPacket(t, "udp", "[::]", "127.0.0.1", isEmpty) + doTestPacket(t, "udp", "0.0.0.0", "[::ffff:127.0.0.1]", isEmpty) } } } func TestUnixDatagramServer(t *testing.T) { for _, isEmpty := range []bool{false, *testEmptyDatagrams} { - os.Remove("/tmp/gotest1.net"); - os.Remove("/tmp/gotest1.net.local"); - doTestPacket(t, "unixgram", "/tmp/gotest1.net", "/tmp/gotest1.net", isEmpty); - os.Remove("/tmp/gotest1.net"); - os.Remove("/tmp/gotest1.net.local"); + os.Remove("/tmp/gotest1.net") + os.Remove("/tmp/gotest1.net.local") + doTestPacket(t, "unixgram", "/tmp/gotest1.net", "/tmp/gotest1.net", isEmpty) + os.Remove("/tmp/gotest1.net") + os.Remove("/tmp/gotest1.net.local") if syscall.OS == "linux" { // Test abstract unix domain socket, a Linux-ism doTestPacket(t, "unixgram", "@gotest1/net", "@gotest1/net", isEmpty) diff --git a/src/pkg/net/sock.go b/src/pkg/net/sock.go index 336c96866..dbb87d36f 100644 --- a/src/pkg/net/sock.go +++ b/src/pkg/net/sock.go @@ -7,9 +7,9 @@ package net import ( - "os"; - "reflect"; - "syscall"; + "os" + "reflect" + "syscall" ) // Boolean to int. @@ -17,52 +17,52 @@ func boolint(b bool) int { if b { return 1 } - return 0; + return 0 } // Generic socket creation. func socket(net string, f, p, t int, la, ra syscall.Sockaddr, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err os.Error) { // See ../syscall/exec.go for description of ForkLock. - syscall.ForkLock.RLock(); - s, e := syscall.Socket(f, p, t); + syscall.ForkLock.RLock() + s, e := syscall.Socket(f, p, t) if e != 0 { - syscall.ForkLock.RUnlock(); - return nil, os.Errno(e); + syscall.ForkLock.RUnlock() + return nil, os.Errno(e) } - syscall.CloseOnExec(s); - syscall.ForkLock.RUnlock(); + syscall.CloseOnExec(s) + syscall.ForkLock.RUnlock() // Allow reuse of recently-used addresses. - syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); + syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1) if la != nil { - e = syscall.Bind(s, la); + e = syscall.Bind(s, la) if e != 0 { - syscall.Close(s); - return nil, os.Errno(e); + syscall.Close(s) + return nil, os.Errno(e) } } if ra != nil { - e = syscall.Connect(s, ra); + e = syscall.Connect(s, ra) if e != 0 { - syscall.Close(s); - return nil, os.Errno(e); + syscall.Close(s) + return nil, os.Errno(e) } } - sa, _ := syscall.Getsockname(s); - laddr := toAddr(sa); - sa, _ = syscall.Getpeername(s); - raddr := toAddr(sa); + sa, _ := syscall.Getsockname(s) + laddr := toAddr(sa) + sa, _ = syscall.Getpeername(s) + raddr := toAddr(sa) - fd, err = newFD(s, f, p, net, laddr, raddr); + fd, err = newFD(s, f, p, net, laddr, raddr) if err != nil { - syscall.Close(s); - return nil, err; + syscall.Close(s) + return nil, err } - return fd, nil; + return fd, nil } func setsockoptInt(fd, level, opt int, value int) os.Error { @@ -70,43 +70,43 @@ func setsockoptInt(fd, level, opt int, value int) os.Error { } func setsockoptNsec(fd, level, opt int, nsec int64) os.Error { - var tv = syscall.NsecToTimeval(nsec); - return os.NewSyscallError("setsockopt", syscall.SetsockoptTimeval(fd, level, opt, &tv)); + var tv = syscall.NsecToTimeval(nsec) + return os.NewSyscallError("setsockopt", syscall.SetsockoptTimeval(fd, level, opt, &tv)) } func setReadBuffer(fd *netFD, bytes int) os.Error { - fd.incref(); - defer fd.decref(); - return setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, bytes); + fd.incref() + defer fd.decref() + return setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, bytes) } func setWriteBuffer(fd *netFD, bytes int) os.Error { - fd.incref(); - defer fd.decref(); - return setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, bytes); + fd.incref() + defer fd.decref() + return setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, bytes) } func setReadTimeout(fd *netFD, nsec int64) os.Error { - fd.rdeadline_delta = nsec; - return nil; + fd.rdeadline_delta = nsec + return nil } func setWriteTimeout(fd *netFD, nsec int64) os.Error { - fd.wdeadline_delta = nsec; - return nil; + fd.wdeadline_delta = nsec + return nil } func setTimeout(fd *netFD, nsec int64) os.Error { if e := setReadTimeout(fd, nsec); e != nil { return e } - return setWriteTimeout(fd, nsec); + return setWriteTimeout(fd, nsec) } func setReuseAddr(fd *netFD, reuse bool) os.Error { - fd.incref(); - defer fd.decref(); - return setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, boolint(reuse)); + fd.incref() + defer fd.decref() + return setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, boolint(reuse)) } func bindToDevice(fd *netFD, dev string) os.Error { @@ -115,34 +115,34 @@ func bindToDevice(fd *netFD, dev string) os.Error { } func setDontRoute(fd *netFD, dontroute bool) os.Error { - fd.incref(); - defer fd.decref(); - return setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_DONTROUTE, boolint(dontroute)); + fd.incref() + defer fd.decref() + return setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_DONTROUTE, boolint(dontroute)) } func setKeepAlive(fd *netFD, keepalive bool) os.Error { - fd.incref(); - defer fd.decref(); - return setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, boolint(keepalive)); + fd.incref() + defer fd.decref() + return setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, boolint(keepalive)) } func setLinger(fd *netFD, sec int) os.Error { - var l syscall.Linger; + var l syscall.Linger if sec >= 0 { - l.Onoff = 1; - l.Linger = int32(sec); + l.Onoff = 1 + l.Linger = int32(sec) } else { - l.Onoff = 0; - l.Linger = 0; + l.Onoff = 0 + l.Linger = 0 } - fd.incref(); - defer fd.decref(); - e := syscall.SetsockoptLinger(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_LINGER, &l); - return os.NewSyscallError("setsockopt", e); + fd.incref() + defer fd.decref() + e := syscall.SetsockoptLinger(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_LINGER, &l) + return os.NewSyscallError("setsockopt", e) } type UnknownSocketError struct { - sa syscall.Sockaddr; + sa syscall.Sockaddr } func (e *UnknownSocketError) String() string { @@ -159,5 +159,5 @@ func sockaddrToString(sa syscall.Sockaddr) (name string, err os.Error) { return a.Name, nil } - return "", &UnknownSocketError{sa}; + return "", &UnknownSocketError{sa} } diff --git a/src/pkg/net/tcpsock.go b/src/pkg/net/tcpsock.go index 680ed3021..cb9e29afc 100644 --- a/src/pkg/net/tcpsock.go +++ b/src/pkg/net/tcpsock.go @@ -7,8 +7,8 @@ package net import ( - "os"; - "syscall"; + "os" + "syscall" ) func sockaddrToTCP(sa syscall.Sockaddr) Addr { @@ -18,19 +18,19 @@ func sockaddrToTCP(sa syscall.Sockaddr) Addr { case *syscall.SockaddrInet6: return &TCPAddr{&sa.Addr, sa.Port} } - return nil; + return nil } // TCPAddr represents the address of a TCP end point. type TCPAddr struct { - IP IP; - Port int; + IP IP + Port int } // Network returns the address's network name, "tcp". -func (a *TCPAddr) Network() string { return "tcp" } +func (a *TCPAddr) Network() string { return "tcp" } -func (a *TCPAddr) String() string { return joinHostPort(a.IP.String(), itoa(a.Port)) } +func (a *TCPAddr) String() string { return joinHostPort(a.IP.String(), itoa(a.Port)) } func (a *TCPAddr) family() int { if a == nil || len(a.IP) <= 4 { @@ -39,7 +39,7 @@ func (a *TCPAddr) family() int { if ip := a.IP.To4(); ip != nil { return syscall.AF_INET } - return syscall.AF_INET6; + return syscall.AF_INET6 } func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) { @@ -47,10 +47,10 @@ func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) { } func (a *TCPAddr) toAddr() sockaddr { - if a == nil { // nil *TCPAddr - return nil // nil interface + if a == nil { // nil *TCPAddr + return nil // nil interface } - return a; + return a } // ResolveTCPAddr parses addr as a TCP address of the form @@ -58,26 +58,26 @@ func (a *TCPAddr) toAddr() sockaddr { // numeric addresses. A literal IPv6 host address must be // enclosed in square brackets, as in "[::]:80". func ResolveTCPAddr(addr string) (*TCPAddr, os.Error) { - ip, port, err := hostPortToIP("tcp", addr); + ip, port, err := hostPortToIP("tcp", addr) if err != nil { return nil, err } - return &TCPAddr{ip, port}, nil; + return &TCPAddr{ip, port}, nil } // TCPConn is an implementation of the Conn interface // for TCP network connections. type TCPConn struct { - fd *netFD; + fd *netFD } func newTCPConn(fd *netFD) *TCPConn { - c := &TCPConn{fd}; - setsockoptInt(fd.sysfd, syscall.IPPROTO_TCP, syscall.TCP_NODELAY, 1); - return c; + c := &TCPConn{fd} + setsockoptInt(fd.sysfd, syscall.IPPROTO_TCP, syscall.TCP_NODELAY, 1) + return c } -func (c *TCPConn) ok() bool { return c != nil && c.fd != nil } +func (c *TCPConn) ok() bool { return c != nil && c.fd != nil } // Implementation of the Conn interface - see Conn for documentation. @@ -89,7 +89,7 @@ func (c *TCPConn) Read(b []byte) (n int, err os.Error) { if !c.ok() { return 0, os.EINVAL } - return c.fd.Read(b); + return c.fd.Read(b) } // Write writes data to the TCP connection. @@ -100,7 +100,7 @@ func (c *TCPConn) Write(b []byte) (n int, err os.Error) { if !c.ok() { return 0, os.EINVAL } - return c.fd.Write(b); + return c.fd.Write(b) } // Close closes the TCP connection. @@ -108,9 +108,9 @@ func (c *TCPConn) Close() os.Error { if !c.ok() { return os.EINVAL } - err := c.fd.Close(); - c.fd = nil; - return err; + err := c.fd.Close() + c.fd = nil + return err } // LocalAddr returns the local network address, a *TCPAddr. @@ -118,7 +118,7 @@ func (c *TCPConn) LocalAddr() Addr { if !c.ok() { return nil } - return c.fd.laddr; + return c.fd.laddr } // RemoteAddr returns the remote network address, a *TCPAddr. @@ -126,7 +126,7 @@ func (c *TCPConn) RemoteAddr() Addr { if !c.ok() { return nil } - return c.fd.raddr; + return c.fd.raddr } // SetTimeout sets the read and write deadlines associated @@ -135,7 +135,7 @@ func (c *TCPConn) SetTimeout(nsec int64) os.Error { if !c.ok() { return os.EINVAL } - return setTimeout(c.fd, nsec); + return setTimeout(c.fd, nsec) } // SetReadTimeout sets the time (in nanoseconds) that @@ -145,7 +145,7 @@ func (c *TCPConn) SetReadTimeout(nsec int64) os.Error { if !c.ok() { return os.EINVAL } - return setReadTimeout(c.fd, nsec); + return setReadTimeout(c.fd, nsec) } // SetWriteTimeout sets the time (in nanoseconds) that @@ -157,7 +157,7 @@ func (c *TCPConn) SetWriteTimeout(nsec int64) os.Error { if !c.ok() { return os.EINVAL } - return setWriteTimeout(c.fd, nsec); + return setWriteTimeout(c.fd, nsec) } // SetReadBuffer sets the size of the operating system's @@ -166,7 +166,7 @@ func (c *TCPConn) SetReadBuffer(bytes int) os.Error { if !c.ok() { return os.EINVAL } - return setReadBuffer(c.fd, bytes); + return setReadBuffer(c.fd, bytes) } // SetWriteBuffer sets the size of the operating system's @@ -175,7 +175,7 @@ func (c *TCPConn) SetWriteBuffer(bytes int) os.Error { if !c.ok() { return os.EINVAL } - return setWriteBuffer(c.fd, bytes); + return setWriteBuffer(c.fd, bytes) } // SetLinger sets the behavior of Close() on a connection @@ -193,7 +193,7 @@ func (c *TCPConn) SetLinger(sec int) os.Error { if !c.ok() { return os.EINVAL } - return setLinger(c.fd, sec); + return setLinger(c.fd, sec) } // SetKeepAlive sets whether the operating system should send @@ -202,7 +202,7 @@ func (c *TCPConn) SetKeepAlive(keepalive bool) os.Error { if !c.ok() { return os.EINVAL } - return setKeepAlive(c.fd, keepalive); + return setKeepAlive(c.fd, keepalive) } // DialTCP is like Dial but can only connect to TCP networks @@ -211,18 +211,18 @@ func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err os.Error) { if raddr == nil { return nil, &OpError{"dial", "tcp", nil, errMissingAddress} } - fd, e := internetSocket(net, laddr.toAddr(), raddr.toAddr(), syscall.SOCK_STREAM, "dial", sockaddrToTCP); + fd, e := internetSocket(net, laddr.toAddr(), raddr.toAddr(), syscall.SOCK_STREAM, "dial", sockaddrToTCP) if e != nil { return nil, e } - return newTCPConn(fd), nil; + return newTCPConn(fd), nil } // TCPListener is a TCP network listener. // Clients should typically use variables of type Listener // instead of assuming TCP. type TCPListener struct { - fd *netFD; + fd *netFD } // ListenTCP announces on the TCP address laddr and returns a TCP listener. @@ -230,18 +230,18 @@ type TCPListener struct { // If laddr has a port of 0, it means to listen on some available port. // The caller can use l.Addr() to retrieve the chosen address. func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err os.Error) { - fd, err := internetSocket(net, laddr.toAddr(), nil, syscall.SOCK_STREAM, "listen", sockaddrToTCP); + fd, err := internetSocket(net, laddr.toAddr(), nil, syscall.SOCK_STREAM, "listen", sockaddrToTCP) if err != nil { return nil, err } - errno := syscall.Listen(fd.sysfd, listenBacklog()); + errno := syscall.Listen(fd.sysfd, listenBacklog()) if errno != 0 { - syscall.Close(fd.sysfd); - return nil, &OpError{"listen", "tcp", laddr, os.Errno(errno)}; + syscall.Close(fd.sysfd) + return nil, &OpError{"listen", "tcp", laddr, os.Errno(errno)} } - l = new(TCPListener); - l.fd = fd; - return l, nil; + l = new(TCPListener) + l.fd = fd + return l, nil } // AcceptTCP accepts the next incoming call and returns the new connection @@ -250,21 +250,21 @@ func (l *TCPListener) AcceptTCP() (c *TCPConn, err os.Error) { if l == nil || l.fd == nil || l.fd.sysfd < 0 { return nil, os.EINVAL } - fd, err := l.fd.accept(sockaddrToTCP); + fd, err := l.fd.accept(sockaddrToTCP) if err != nil { return nil, err } - return newTCPConn(fd), nil; + return newTCPConn(fd), nil } // Accept implements the Accept method in the Listener interface; // it waits for the next call and returns a generic Conn. func (l *TCPListener) Accept() (c Conn, err os.Error) { - c1, err := l.AcceptTCP(); + c1, err := l.AcceptTCP() if err != nil { return nil, err } - return c1, nil; + return c1, nil } // Close stops listening on the TCP address. @@ -273,8 +273,8 @@ func (l *TCPListener) Close() os.Error { if l == nil || l.fd == nil { return os.EINVAL } - return l.fd.Close(); + return l.fd.Close() } // Addr returns the listener's network address, a *TCPAddr. -func (l *TCPListener) Addr() Addr { return l.fd.laddr } +func (l *TCPListener) Addr() Addr { return l.fd.laddr } diff --git a/src/pkg/net/timeout_test.go b/src/pkg/net/timeout_test.go index c1ba39942..f5ec5730f 100644 --- a/src/pkg/net/timeout_test.go +++ b/src/pkg/net/timeout_test.go @@ -5,29 +5,29 @@ package net import ( - "os"; - "testing"; - "time"; + "os" + "testing" + "time" ) func testTimeout(t *testing.T, network, addr string, readFrom bool) { - fd, err := Dial(network, "", addr); - defer fd.Close(); + fd, err := Dial(network, "", addr) + defer fd.Close() if err != nil { t.Errorf("dial %s %s failed: %v", network, addr, err) } - t0 := time.Nanoseconds(); - fd.SetReadTimeout(1e8); // 100ms - var b [100]byte; - var n int; - var err1 os.Error; + t0 := time.Nanoseconds() + fd.SetReadTimeout(1e8) // 100ms + var b [100]byte + var n int + var err1 os.Error if readFrom { n, _, err1 = fd.(PacketConn).ReadFrom(&b) } else { n, err1 = fd.Read(&b) } - t1 := time.Nanoseconds(); - what := "Read"; + t1 := time.Nanoseconds() + what := "Read" if readFrom { what = "ReadFrom" } @@ -40,8 +40,8 @@ func testTimeout(t *testing.T, network, addr string, readFrom bool) { } func TestTimeoutUDP(t *testing.T) { - testTimeout(t, "udp", "127.0.0.1:53", false); - testTimeout(t, "udp", "127.0.0.1:53", true); + testTimeout(t, "udp", "127.0.0.1:53", false) + testTimeout(t, "udp", "127.0.0.1:53", true) } func TestTimeoutTCP(t *testing.T) { diff --git a/src/pkg/net/udpsock.go b/src/pkg/net/udpsock.go index d74a38078..1891f2f8c 100644 --- a/src/pkg/net/udpsock.go +++ b/src/pkg/net/udpsock.go @@ -7,8 +7,8 @@ package net import ( - "os"; - "syscall"; + "os" + "syscall" ) func sockaddrToUDP(sa syscall.Sockaddr) Addr { @@ -18,19 +18,19 @@ func sockaddrToUDP(sa syscall.Sockaddr) Addr { case *syscall.SockaddrInet6: return &UDPAddr{&sa.Addr, sa.Port} } - return nil; + return nil } // UDPAddr represents the address of a UDP end point. type UDPAddr struct { - IP IP; - Port int; + IP IP + Port int } // Network returns the address's network name, "udp". -func (a *UDPAddr) Network() string { return "udp" } +func (a *UDPAddr) Network() string { return "udp" } -func (a *UDPAddr) String() string { return joinHostPort(a.IP.String(), itoa(a.Port)) } +func (a *UDPAddr) String() string { return joinHostPort(a.IP.String(), itoa(a.Port)) } func (a *UDPAddr) family() int { if a == nil || len(a.IP) <= 4 { @@ -39,7 +39,7 @@ func (a *UDPAddr) family() int { if ip := a.IP.To4(); ip != nil { return syscall.AF_INET } - return syscall.AF_INET6; + return syscall.AF_INET6 } func (a *UDPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) { @@ -47,10 +47,10 @@ func (a *UDPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) { } func (a *UDPAddr) toAddr() sockaddr { - if a == nil { // nil *UDPAddr - return nil // nil interface + if a == nil { // nil *UDPAddr + return nil // nil interface } - return a; + return a } // ResolveUDPAddr parses addr as a UDP address of the form @@ -58,26 +58,26 @@ func (a *UDPAddr) toAddr() sockaddr { // numeric addresses. A literal IPv6 host address must be // enclosed in square brackets, as in "[::]:80". func ResolveUDPAddr(addr string) (*UDPAddr, os.Error) { - ip, port, err := hostPortToIP("udp", addr); + ip, port, err := hostPortToIP("udp", addr) if err != nil { return nil, err } - return &UDPAddr{ip, port}, nil; + return &UDPAddr{ip, port}, nil } // UDPConn is the implementation of the Conn and PacketConn // interfaces for UDP network connections. type UDPConn struct { - fd *netFD; + fd *netFD } func newUDPConn(fd *netFD) *UDPConn { - c := &UDPConn{fd}; - setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1); - return c; + c := &UDPConn{fd} + setsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1) + return c } -func (c *UDPConn) ok() bool { return c != nil && c.fd != nil } +func (c *UDPConn) ok() bool { return c != nil && c.fd != nil } // Implementation of the Conn interface - see Conn for documentation. @@ -91,7 +91,7 @@ func (c *UDPConn) Read(b []byte) (n int, err os.Error) { if !c.ok() { return 0, os.EINVAL } - return c.fd.Read(b); + return c.fd.Read(b) } // Write writes data to the connection as a single UDP packet. @@ -102,7 +102,7 @@ func (c *UDPConn) Write(b []byte) (n int, err os.Error) { if !c.ok() { return 0, os.EINVAL } - return c.fd.Write(b); + return c.fd.Write(b) } // Close closes the UDP connection. @@ -110,9 +110,9 @@ func (c *UDPConn) Close() os.Error { if !c.ok() { return os.EINVAL } - err := c.fd.Close(); - c.fd = nil; - return err; + err := c.fd.Close() + c.fd = nil + return err } // LocalAddr returns the local network address. @@ -120,7 +120,7 @@ func (c *UDPConn) LocalAddr() Addr { if !c.ok() { return nil } - return c.fd.laddr; + return c.fd.laddr } // RemoteAddr returns the remote network address, a *UDPAddr. @@ -128,7 +128,7 @@ func (c *UDPConn) RemoteAddr() Addr { if !c.ok() { return nil } - return c.fd.raddr; + return c.fd.raddr } // SetTimeout sets the read and write deadlines associated @@ -137,7 +137,7 @@ func (c *UDPConn) SetTimeout(nsec int64) os.Error { if !c.ok() { return os.EINVAL } - return setTimeout(c.fd, nsec); + return setTimeout(c.fd, nsec) } // SetReadTimeout sets the time (in nanoseconds) that @@ -147,7 +147,7 @@ func (c *UDPConn) SetReadTimeout(nsec int64) os.Error { if !c.ok() { return os.EINVAL } - return setReadTimeout(c.fd, nsec); + return setReadTimeout(c.fd, nsec) } // SetWriteTimeout sets the time (in nanoseconds) that @@ -159,7 +159,7 @@ func (c *UDPConn) SetWriteTimeout(nsec int64) os.Error { if !c.ok() { return os.EINVAL } - return setWriteTimeout(c.fd, nsec); + return setWriteTimeout(c.fd, nsec) } // SetReadBuffer sets the size of the operating system's @@ -168,7 +168,7 @@ func (c *UDPConn) SetReadBuffer(bytes int) os.Error { if !c.ok() { return os.EINVAL } - return setReadBuffer(c.fd, bytes); + return setReadBuffer(c.fd, bytes) } // SetWriteBuffer sets the size of the operating system's @@ -177,7 +177,7 @@ func (c *UDPConn) SetWriteBuffer(bytes int) os.Error { if !c.ok() { return os.EINVAL } - return setWriteBuffer(c.fd, bytes); + return setWriteBuffer(c.fd, bytes) } // UDP-specific methods. @@ -192,14 +192,14 @@ func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err os.Error) { if !c.ok() { return 0, nil, os.EINVAL } - n, sa, err := c.fd.ReadFrom(b); + n, sa, err := c.fd.ReadFrom(b) switch sa := sa.(type) { case *syscall.SockaddrInet4: addr = &UDPAddr{&sa.Addr, sa.Port} case *syscall.SockaddrInet6: addr = &UDPAddr{&sa.Addr, sa.Port} } - return; + return } // ReadFrom reads a UDP packet from c, copying the payload into b. @@ -212,8 +212,8 @@ func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { if !c.ok() { return 0, nil, os.EINVAL } - n, uaddr, err := c.ReadFromUDP(b); - return n, uaddr.toAddr(), err; + n, uaddr, err := c.ReadFromUDP(b) + return n, uaddr.toAddr(), err } // WriteToUDP writes a UDP packet to addr via c, copying the payload from b. @@ -225,11 +225,11 @@ func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err os.Error) { if !c.ok() { return 0, os.EINVAL } - sa, err := addr.sockaddr(c.fd.family); + sa, err := addr.sockaddr(c.fd.family) if err != nil { return 0, err } - return c.fd.WriteTo(b, sa); + return c.fd.WriteTo(b, sa) } // WriteTo writes a UDP packet with payload b to addr via c. @@ -241,11 +241,11 @@ func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { if !c.ok() { return 0, os.EINVAL } - a, ok := addr.(*UDPAddr); + a, ok := addr.(*UDPAddr) if !ok { return 0, &OpError{"writeto", "udp", addr, os.EINVAL} } - return c.WriteToUDP(b, a); + return c.WriteToUDP(b, a) } // DialUDP connects to the remote address raddr on the network net, @@ -260,11 +260,11 @@ func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err os.Error) { if raddr == nil { return nil, &OpError{"dial", "udp", nil, errMissingAddress} } - fd, e := internetSocket(net, laddr.toAddr(), raddr.toAddr(), syscall.SOCK_DGRAM, "dial", sockaddrToUDP); + fd, e := internetSocket(net, laddr.toAddr(), raddr.toAddr(), syscall.SOCK_DGRAM, "dial", sockaddrToUDP) if e != nil { return nil, e } - return newUDPConn(fd), nil; + return newUDPConn(fd), nil } // ListenUDP listens for incoming UDP packets addressed to the @@ -280,9 +280,9 @@ func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err os.Error) { if laddr == nil { return nil, &OpError{"listen", "udp", nil, errMissingAddress} } - fd, e := internetSocket(net, laddr.toAddr(), nil, syscall.SOCK_DGRAM, "dial", sockaddrToUDP); + fd, e := internetSocket(net, laddr.toAddr(), nil, syscall.SOCK_DGRAM, "dial", sockaddrToUDP) if e != nil { return nil, e } - return newUDPConn(fd), nil; + return newUDPConn(fd), nil } diff --git a/src/pkg/net/unixsock.go b/src/pkg/net/unixsock.go index 4ac3be54a..8f642210f 100644 --- a/src/pkg/net/unixsock.go +++ b/src/pkg/net/unixsock.go @@ -7,12 +7,12 @@ package net import ( - "os"; - "syscall"; + "os" + "syscall" ) func unixSocket(net string, laddr, raddr *UnixAddr, mode string) (fd *netFD, err os.Error) { - var proto int; + var proto int switch net { default: return nil, UnknownNetworkError(net) @@ -22,7 +22,7 @@ func unixSocket(net string, laddr, raddr *UnixAddr, mode string) (fd *netFD, err proto = syscall.SOCK_DGRAM } - var la, ra syscall.Sockaddr; + var la, ra syscall.Sockaddr switch mode { default: panic("unixSocket", mode) @@ -41,48 +41,48 @@ func unixSocket(net string, laddr, raddr *UnixAddr, mode string) (fd *netFD, err if laddr == nil { return nil, &OpError{mode, net, nil, errMissingAddress} } - la = &syscall.SockaddrUnix{Name: laddr.Name}; + la = &syscall.SockaddrUnix{Name: laddr.Name} if raddr != nil { return nil, &OpError{mode, net, raddr, &AddrError{"unexpected remote address", raddr.String()}} } } - f := sockaddrToUnix; + f := sockaddrToUnix if proto != syscall.SOCK_STREAM { f = sockaddrToUnixgram } - fd, err = socket(net, syscall.AF_UNIX, proto, 0, la, ra, f); + fd, err = socket(net, syscall.AF_UNIX, proto, 0, la, ra, f) if err != nil { goto Error } - return fd, nil; + return fd, nil Error: - addr := raddr; + addr := raddr if mode == "listen" { addr = laddr } - return nil, &OpError{mode, net, addr, err}; + return nil, &OpError{mode, net, addr, err} } // UnixAddr represents the address of a Unix domain socket end point. type UnixAddr struct { - Name string; - Datagram bool; + Name string + Datagram bool } func sockaddrToUnix(sa syscall.Sockaddr) Addr { if s, ok := sa.(*syscall.SockaddrUnix); ok { return &UnixAddr{s.Name, false} } - return nil; + return nil } func sockaddrToUnixgram(sa syscall.Sockaddr) Addr { if s, ok := sa.(*syscall.SockaddrUnix); ok { return &UnixAddr{s.Name, true} } - return nil; + return nil } // Network returns the address's network name, "unix" or "unixgram". @@ -90,27 +90,27 @@ func (a *UnixAddr) Network() string { if a == nil || !a.Datagram { return "unix" } - return "unixgram"; + return "unixgram" } func (a *UnixAddr) String() string { if a == nil { return "<nil>" } - return a.Name; + return a.Name } func (a *UnixAddr) toAddr() Addr { - if a == nil { // nil *UnixAddr - return nil // nil interface + if a == nil { // nil *UnixAddr + return nil // nil interface } - return a; + return a } // ResolveUnixAddr parses addr as a Unix domain socket address. // The string net gives the network name, "unix" or "unixgram". func ResolveUnixAddr(net, addr string) (*UnixAddr, os.Error) { - var datagram bool; + var datagram bool switch net { case "unix": case "unixgram": @@ -118,18 +118,18 @@ func ResolveUnixAddr(net, addr string) (*UnixAddr, os.Error) { default: return nil, UnknownNetworkError(net) } - return &UnixAddr{addr, datagram}, nil; + return &UnixAddr{addr, datagram}, nil } // UnixConn is an implementation of the Conn interface // for connections to Unix domain sockets. type UnixConn struct { - fd *netFD; + fd *netFD } -func newUnixConn(fd *netFD) *UnixConn { return &UnixConn{fd} } +func newUnixConn(fd *netFD) *UnixConn { return &UnixConn{fd} } -func (c *UnixConn) ok() bool { return c != nil && c.fd != nil } +func (c *UnixConn) ok() bool { return c != nil && c.fd != nil } // Implementation of the Conn interface - see Conn for documentation. @@ -141,7 +141,7 @@ func (c *UnixConn) Read(b []byte) (n int, err os.Error) { if !c.ok() { return 0, os.EINVAL } - return c.fd.Read(b); + return c.fd.Read(b) } // Write writes data to the Unix domain connection. @@ -152,7 +152,7 @@ func (c *UnixConn) Write(b []byte) (n int, err os.Error) { if !c.ok() { return 0, os.EINVAL } - return c.fd.Write(b); + return c.fd.Write(b) } // Close closes the Unix domain connection. @@ -160,9 +160,9 @@ func (c *UnixConn) Close() os.Error { if !c.ok() { return os.EINVAL } - err := c.fd.Close(); - c.fd = nil; - return err; + err := c.fd.Close() + c.fd = nil + return err } // LocalAddr returns the local network address, a *UnixAddr. @@ -171,7 +171,7 @@ func (c *UnixConn) LocalAddr() Addr { if !c.ok() { return nil } - return c.fd.laddr; + return c.fd.laddr } // RemoteAddr returns the remote network address, a *UnixAddr. @@ -181,7 +181,7 @@ func (c *UnixConn) RemoteAddr() Addr { if !c.ok() { return nil } - return c.fd.raddr; + return c.fd.raddr } // SetTimeout sets the read and write deadlines associated @@ -190,7 +190,7 @@ func (c *UnixConn) SetTimeout(nsec int64) os.Error { if !c.ok() { return os.EINVAL } - return setTimeout(c.fd, nsec); + return setTimeout(c.fd, nsec) } // SetReadTimeout sets the time (in nanoseconds) that @@ -200,7 +200,7 @@ func (c *UnixConn) SetReadTimeout(nsec int64) os.Error { if !c.ok() { return os.EINVAL } - return setReadTimeout(c.fd, nsec); + return setReadTimeout(c.fd, nsec) } // SetWriteTimeout sets the time (in nanoseconds) that @@ -212,7 +212,7 @@ func (c *UnixConn) SetWriteTimeout(nsec int64) os.Error { if !c.ok() { return os.EINVAL } - return setWriteTimeout(c.fd, nsec); + return setWriteTimeout(c.fd, nsec) } // SetReadBuffer sets the size of the operating system's @@ -221,7 +221,7 @@ func (c *UnixConn) SetReadBuffer(bytes int) os.Error { if !c.ok() { return os.EINVAL } - return setReadBuffer(c.fd, bytes); + return setReadBuffer(c.fd, bytes) } // SetWriteBuffer sets the size of the operating system's @@ -230,7 +230,7 @@ func (c *UnixConn) SetWriteBuffer(bytes int) os.Error { if !c.ok() { return os.EINVAL } - return setWriteBuffer(c.fd, bytes); + return setWriteBuffer(c.fd, bytes) } // ReadFromUnix reads a packet from c, copying the payload into b. @@ -243,12 +243,12 @@ func (c *UnixConn) ReadFromUnix(b []byte) (n int, addr *UnixAddr, err os.Error) if !c.ok() { return 0, nil, os.EINVAL } - n, sa, err := c.fd.ReadFrom(b); + n, sa, err := c.fd.ReadFrom(b) switch sa := sa.(type) { case *syscall.SockaddrUnix: addr = &UnixAddr{sa.Name, c.fd.proto == syscall.SOCK_DGRAM} } - return; + return } // ReadFrom reads a packet from c, copying the payload into b. @@ -261,8 +261,8 @@ func (c *UnixConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { if !c.ok() { return 0, nil, os.EINVAL } - n, uaddr, err := c.ReadFromUnix(b); - return n, uaddr.toAddr(), err; + n, uaddr, err := c.ReadFromUnix(b) + return n, uaddr.toAddr(), err } // WriteToUnix writes a packet to addr via c, copying the payload from b. @@ -277,8 +277,8 @@ func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (n int, err os.Error) { if addr.Datagram != (c.fd.proto == syscall.SOCK_DGRAM) { return 0, os.EAFNOSUPPORT } - sa := &syscall.SockaddrUnix{Name: addr.Name}; - return c.fd.WriteTo(b, sa); + sa := &syscall.SockaddrUnix{Name: addr.Name} + return c.fd.WriteTo(b, sa) } // WriteTo writes a packet to addr via c, copying the payload from b. @@ -290,30 +290,30 @@ func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { if !c.ok() { return 0, os.EINVAL } - a, ok := addr.(*UnixAddr); + a, ok := addr.(*UnixAddr) if !ok { return 0, &OpError{"writeto", "unix", addr, os.EINVAL} } - return c.WriteToUnix(b, a); + return c.WriteToUnix(b, a) } // DialUDP connects to the remote address raddr on the network net, // which must be "unix" or "unixdgram". If laddr is not nil, it is used // as the local address for the connection. func DialUnix(net string, laddr, raddr *UnixAddr) (c *UnixConn, err os.Error) { - fd, e := unixSocket(net, laddr, raddr, "dial"); + fd, e := unixSocket(net, laddr, raddr, "dial") if e != nil { return nil, e } - return newUnixConn(fd), nil; + return newUnixConn(fd), nil } // UnixListener is a Unix domain socket listener. // Clients should typically use variables of type Listener // instead of assuming Unix domain sockets. type UnixListener struct { - fd *netFD; - path string; + fd *netFD + path string } // ListenUnix announces on the Unix domain socket laddr and returns a Unix listener. @@ -323,21 +323,21 @@ func ListenUnix(net string, laddr *UnixAddr) (l *UnixListener, err os.Error) { return nil, UnknownNetworkError(net) } if laddr != nil { - laddr = &UnixAddr{laddr.Name, net == "unixgram"} // make our own copy + laddr = &UnixAddr{laddr.Name, net == "unixgram"} // make our own copy } - fd, e := unixSocket(net, laddr, nil, "listen"); + fd, e := unixSocket(net, laddr, nil, "listen") if e != nil { if pe, ok := e.(*os.PathError); ok { e = pe.Error } - return nil, e; + return nil, e } - e1 := syscall.Listen(fd.sysfd, 8); // listenBacklog()); + e1 := syscall.Listen(fd.sysfd, 8) // listenBacklog()); if e1 != 0 { - syscall.Close(fd.sysfd); - return nil, &OpError{"listen", "unix", laddr, os.Errno(e1)}; + syscall.Close(fd.sysfd) + return nil, &OpError{"listen", "unix", laddr, os.Errno(e1)} } - return &UnixListener{fd, laddr.Name}, nil; + return &UnixListener{fd, laddr.Name}, nil } // AcceptUnix accepts the next incoming call and returns the new connection @@ -346,22 +346,22 @@ func (l *UnixListener) AcceptUnix() (c *UnixConn, err os.Error) { if l == nil || l.fd == nil { return nil, os.EINVAL } - fd, e := l.fd.accept(sockaddrToUnix); + fd, e := l.fd.accept(sockaddrToUnix) if e != nil { return nil, e } - c = newUnixConn(fd); - return c, nil; + c = newUnixConn(fd) + return c, nil } // Accept implements the Accept method in the Listener interface; // it waits for the next call and returns a generic Conn. func (l *UnixListener) Accept() (c Conn, err os.Error) { - c1, err := l.AcceptUnix(); + c1, err := l.AcceptUnix() if err != nil { return nil, err } - return c1, nil; + return c1, nil } // Close stops listening on the Unix address. @@ -384,13 +384,13 @@ func (l *UnixListener) Close() os.Error { if l.path[0] != '@' { syscall.Unlink(l.path) } - err := l.fd.Close(); - l.fd = nil; - return err; + err := l.fd.Close() + l.fd = nil + return err } // Addr returns the listener's network address. -func (l *UnixListener) Addr() Addr { return l.fd.laddr } +func (l *UnixListener) Addr() Addr { return l.fd.laddr } // ListenUnixgram listens for incoming Unix datagram packets addressed to the // local address laddr. The returned connection c's ReadFrom @@ -405,9 +405,9 @@ func ListenUnixgram(net string, laddr *UnixAddr) (c *UDPConn, err os.Error) { if laddr == nil { return nil, &OpError{"listen", "unixgram", nil, errMissingAddress} } - fd, e := unixSocket(net, laddr, nil, "listen"); + fd, e := unixSocket(net, laddr, nil, "listen") if e != nil { return nil, e } - return newUDPConn(fd), nil; + return newUDPConn(fd), nil } |