diff options
Diffstat (limited to 'src/pkg/go')
-rw-r--r-- | src/pkg/go/ast/ast.go | 720 | ||||
-rw-r--r-- | src/pkg/go/ast/filter.go | 116 | ||||
-rw-r--r-- | src/pkg/go/ast/scope.go | 12 | ||||
-rw-r--r-- | src/pkg/go/ast/walk.go | 160 | ||||
-rw-r--r-- | src/pkg/go/doc/comment.go | 152 | ||||
-rw-r--r-- | src/pkg/go/doc/doc.go | 390 | ||||
-rw-r--r-- | src/pkg/go/parser/interface.go | 82 | ||||
-rw-r--r-- | src/pkg/go/parser/parser.go | 1050 | ||||
-rw-r--r-- | src/pkg/go/parser/parser_test.go | 18 | ||||
-rw-r--r-- | src/pkg/go/printer/nodes.go | 796 | ||||
-rw-r--r-- | src/pkg/go/printer/printer.go | 472 | ||||
-rw-r--r-- | src/pkg/go/printer/printer_test.go | 82 | ||||
-rw-r--r-- | src/pkg/go/scanner/errors.go | 62 | ||||
-rw-r--r-- | src/pkg/go/scanner/scanner.go | 342 | ||||
-rw-r--r-- | src/pkg/go/scanner/scanner_test.go | 154 | ||||
-rw-r--r-- | src/pkg/go/token/token.go | 242 |
16 files changed, 2425 insertions, 2425 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 } |