diff options
Diffstat (limited to 'gcc-4.8.1/libgo/go/go')
149 files changed, 0 insertions, 40082 deletions
diff --git a/gcc-4.8.1/libgo/go/go/ast/ast.go b/gcc-4.8.1/libgo/go/go/ast/ast.go deleted file mode 100644 index bf533d1d2..000000000 --- a/gcc-4.8.1/libgo/go/go/ast/ast.go +++ /dev/null @@ -1,993 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ast declares the types used to represent syntax trees for Go -// packages. -// -package ast - -import ( - "go/token" - "strings" - "unicode" - "unicode/utf8" -) - -// ---------------------------------------------------------------------------- -// Interfaces -// -// There are 3 main classes of nodes: Expressions and type nodes, -// statement nodes, and declaration nodes. The node names usually -// match the corresponding Go spec production names to which they -// correspond. The node fields correspond to the individual parts -// of the respective productions. -// -// All nodes contain position information marking the beginning of -// the corresponding source text segment; it is accessible via the -// Pos accessor method. Nodes may contain additional position info -// for language constructs where comments may be found between parts -// of the construct (typically any larger, parenthesized subpart). -// That position information is needed to properly position comments -// when printing the construct. - -// All node types implement the Node interface. -type Node interface { - Pos() token.Pos // position of first character belonging to the node - End() token.Pos // position of first character immediately after the node -} - -// All expression nodes implement the Expr interface. -type Expr interface { - Node - exprNode() -} - -// All statement nodes implement the Stmt interface. -type Stmt interface { - Node - stmtNode() -} - -// All declaration nodes implement the Decl interface. -type Decl interface { - Node - declNode() -} - -// ---------------------------------------------------------------------------- -// Comments - -// A Comment node represents a single //-style or /*-style comment. -type Comment struct { - Slash token.Pos // position of "/" starting the comment - Text string // comment text (excluding '\n' for //-style comments) -} - -func (c *Comment) Pos() token.Pos { return c.Slash } -func (c *Comment) End() token.Pos { return token.Pos(int(c.Slash) + len(c.Text)) } - -// A CommentGroup represents a sequence of comments -// with no other tokens and no empty lines between. -// -type CommentGroup struct { - List []*Comment // len(List) > 0 -} - -func (g *CommentGroup) Pos() token.Pos { return g.List[0].Pos() } -func (g *CommentGroup) End() token.Pos { return g.List[len(g.List)-1].End() } - -func isWhitespace(ch byte) bool { return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' } - -func stripTrailingWhitespace(s string) string { - i := len(s) - for i > 0 && isWhitespace(s[i-1]) { - i-- - } - return s[0:i] -} - -// Text returns the text of the comment. -// Comment markers (//, /*, and */), the first space of a line comment, and -// leading and trailing empty lines are removed. Multiple empty lines are -// reduced to one, and trailing space on lines is trimmed. Unless the result -// is empty, it is newline-terminated. -// -func (g *CommentGroup) Text() string { - if g == nil { - return "" - } - comments := make([]string, len(g.List)) - for i, c := range g.List { - comments[i] = string(c.Text) - } - - lines := make([]string, 0, 10) // most comments are less than 10 lines - for _, c := range comments { - // Remove comment markers. - // The parser has given us exactly the comment text. - switch c[1] { - case '/': - //-style comment (no newline at the end) - c = c[2:] - // strip first space - required for Example tests - if len(c) > 0 && c[0] == ' ' { - c = c[1:] - } - case '*': - /*-style comment */ - c = c[2 : len(c)-2] - } - - // Split on newlines. - cl := strings.Split(c, "\n") - - // Walk lines, stripping trailing white space and adding to list. - for _, l := range cl { - lines = append(lines, stripTrailingWhitespace(l)) - } - } - - // Remove leading blank lines; convert runs of - // interior blank lines to a single blank line. - n := 0 - for _, line := range lines { - if line != "" || n > 0 && lines[n-1] != "" { - lines[n] = line - n++ - } - } - lines = lines[0:n] - - // Add final "" entry to get trailing newline from Join. - if n > 0 && lines[n-1] != "" { - lines = append(lines, "") - } - - return strings.Join(lines, "\n") -} - -// ---------------------------------------------------------------------------- -// Expressions and types - -// A Field represents a Field declaration list in a struct type, -// a method list in an interface type, or a parameter/result declaration -// 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 -} - -func (f *Field) Pos() token.Pos { - if len(f.Names) > 0 { - return f.Names[0].Pos() - } - return f.Type.Pos() -} - -func (f *Field) End() token.Pos { - if f.Tag != nil { - return f.Tag.End() - } - return f.Type.End() -} - -// A FieldList represents a list of Fields, enclosed by parentheses or braces. -type FieldList struct { - Opening token.Pos // position of opening parenthesis/brace, if any - List []*Field // field list; or nil - Closing token.Pos // position of closing parenthesis/brace, if any -} - -func (f *FieldList) Pos() token.Pos { - if f.Opening.IsValid() { - return f.Opening - } - // the list should not be empty in this case; - // be conservative and guard against bad ASTs - if len(f.List) > 0 { - return f.List[0].Pos() - } - return token.NoPos -} - -func (f *FieldList) End() token.Pos { - if f.Closing.IsValid() { - return f.Closing + 1 - } - // the list should not be empty in this case; - // be conservative and guard against bad ASTs - if n := len(f.List); n > 0 { - return f.List[n-1].End() - } - return token.NoPos -} - -// NumFields returns the number of (named and anonymous fields) in a FieldList. -func (f *FieldList) NumFields() int { - n := 0 - if f != nil { - for _, g := range f.List { - m := len(g.Names) - if m == 0 { - m = 1 // anonymous field - } - n += m - } - } - return n -} - -// An expression is represented by a tree consisting of one -// or more of the following concrete expression nodes. -// -type ( - // A BadExpr node is a placeholder for expressions containing - // syntax errors for which no correct expression nodes can be - // created. - // - BadExpr struct { - From, To token.Pos // position range of bad expression - } - - // An Ident node represents an identifier. - Ident struct { - NamePos token.Pos // identifier position - Name string // identifier name - Obj *Object // denoted object; or nil - } - - // An Ellipsis node stands for the "..." type in a - // parameter list or the "..." length in an array type. - // - Ellipsis struct { - Ellipsis token.Pos // position of "..." - Elt Expr // ellipsis element type (parameter lists only); or nil - } - - // A BasicLit node represents a literal of basic type. - BasicLit struct { - ValuePos token.Pos // literal position - Kind token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING - Value string // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo" or `\m\n\o` - } - - // A FuncLit node represents a function literal. - FuncLit struct { - Type *FuncType // function type - Body *BlockStmt // function body - } - - // A CompositeLit node represents a composite literal. - CompositeLit struct { - Type Expr // literal type; or nil - Lbrace token.Pos // position of "{" - Elts []Expr // list of composite elements; or nil - Rbrace token.Pos // position of "}" - } - - // A ParenExpr node represents a parenthesized expression. - ParenExpr struct { - Lparen token.Pos // position of "(" - X Expr // parenthesized expression - Rparen token.Pos // position of ")" - } - - // A SelectorExpr node represents an expression followed by a 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 - Lbrack token.Pos // position of "[" - Index Expr // index expression - Rbrack token.Pos // position of "]" - } - - // An SliceExpr node represents an expression followed by slice indices. - SliceExpr struct { - X Expr // expression - Lbrack token.Pos // position of "[" - Low Expr // begin of slice range; or nil - High Expr // end of slice range; or nil - Rbrack token.Pos // position of "]" - } - - // 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) - } - - // A CallExpr node represents an expression followed by an argument list. - CallExpr struct { - Fun Expr // function expression - Lparen token.Pos // position of "(" - Args []Expr // function arguments; or nil - Ellipsis token.Pos // position of "...", if any - Rparen token.Pos // position of ")" - } - - // A StarExpr node represents an expression of the form "*" Expression. - // Semantically it could be a unary "*" expression, or a pointer type. - // - StarExpr struct { - Star token.Pos // position of "*" - X Expr // operand - } - - // A UnaryExpr node represents a unary expression. - // Unary "*" expressions are represented via StarExpr nodes. - // - UnaryExpr struct { - OpPos token.Pos // 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.Pos // 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.Pos // position of ":" - Value Expr - } -) - -// The direction of a channel type is indicated by one -// of the following constants. -// -type ChanDir int - -const ( - SEND ChanDir = 1 << iota - RECV -) - -// A type is represented by a tree consisting of one -// or more of the following type-specific expression -// nodes. -// -type ( - // An ArrayType node represents an array or slice type. - ArrayType struct { - Lbrack token.Pos // 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 { - Struct token.Pos // position of "struct" keyword - Fields *FieldList // list of field declarations - 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 { - Func token.Pos // position of "func" keyword - Params *FieldList // (incoming) parameters; or nil - Results *FieldList // (outgoing) results; or nil - } - - // An InterfaceType node represents an interface type. - InterfaceType struct { - Interface token.Pos // position of "interface" keyword - Methods *FieldList // list of methods - Incomplete bool // true if (source) methods are missing in the Methods list - } - - // A MapType node represents a map type. - MapType struct { - Map token.Pos // position of "map" keyword - Key Expr - Value Expr - } - - // A ChanType node represents a channel type. - ChanType struct { - Begin token.Pos // position of "chan" keyword or "<-" (whichever comes first) - Arrow token.Pos // position of "<-" (noPos if there is no "<-") - Dir ChanDir // channel direction - Value Expr // value type - } -) - -// Pos and End implementations for expression/type nodes. -// -func (x *BadExpr) Pos() token.Pos { return x.From } -func (x *Ident) Pos() token.Pos { return x.NamePos } -func (x *Ellipsis) Pos() token.Pos { return x.Ellipsis } -func (x *BasicLit) Pos() token.Pos { return x.ValuePos } -func (x *FuncLit) Pos() token.Pos { return x.Type.Pos() } -func (x *CompositeLit) Pos() token.Pos { - if x.Type != nil { - return x.Type.Pos() - } - return x.Lbrace -} -func (x *ParenExpr) Pos() token.Pos { return x.Lparen } -func (x *SelectorExpr) Pos() token.Pos { return x.X.Pos() } -func (x *IndexExpr) Pos() token.Pos { return x.X.Pos() } -func (x *SliceExpr) Pos() token.Pos { return x.X.Pos() } -func (x *TypeAssertExpr) Pos() token.Pos { return x.X.Pos() } -func (x *CallExpr) Pos() token.Pos { return x.Fun.Pos() } -func (x *StarExpr) Pos() token.Pos { return x.Star } -func (x *UnaryExpr) Pos() token.Pos { return x.OpPos } -func (x *BinaryExpr) Pos() token.Pos { return x.X.Pos() } -func (x *KeyValueExpr) Pos() token.Pos { return x.Key.Pos() } -func (x *ArrayType) Pos() token.Pos { return x.Lbrack } -func (x *StructType) Pos() token.Pos { return x.Struct } -func (x *FuncType) Pos() token.Pos { return x.Func } -func (x *InterfaceType) Pos() token.Pos { return x.Interface } -func (x *MapType) Pos() token.Pos { return x.Map } -func (x *ChanType) Pos() token.Pos { return x.Begin } - -func (x *BadExpr) End() token.Pos { return x.To } -func (x *Ident) End() token.Pos { return token.Pos(int(x.NamePos) + len(x.Name)) } -func (x *Ellipsis) End() token.Pos { - if x.Elt != nil { - return x.Elt.End() - } - return x.Ellipsis + 3 // len("...") -} -func (x *BasicLit) End() token.Pos { return token.Pos(int(x.ValuePos) + len(x.Value)) } -func (x *FuncLit) End() token.Pos { return x.Body.End() } -func (x *CompositeLit) End() token.Pos { return x.Rbrace + 1 } -func (x *ParenExpr) End() token.Pos { return x.Rparen + 1 } -func (x *SelectorExpr) End() token.Pos { return x.Sel.End() } -func (x *IndexExpr) End() token.Pos { return x.Rbrack + 1 } -func (x *SliceExpr) End() token.Pos { return x.Rbrack + 1 } -func (x *TypeAssertExpr) End() token.Pos { - if x.Type != nil { - return x.Type.End() - } - return x.X.End() -} -func (x *CallExpr) End() token.Pos { return x.Rparen + 1 } -func (x *StarExpr) End() token.Pos { return x.X.End() } -func (x *UnaryExpr) End() token.Pos { return x.X.End() } -func (x *BinaryExpr) End() token.Pos { return x.Y.End() } -func (x *KeyValueExpr) End() token.Pos { return x.Value.End() } -func (x *ArrayType) End() token.Pos { return x.Elt.End() } -func (x *StructType) End() token.Pos { return x.Fields.End() } -func (x *FuncType) End() token.Pos { - if x.Results != nil { - return x.Results.End() - } - return x.Params.End() -} -func (x *InterfaceType) End() token.Pos { return x.Methods.End() } -func (x *MapType) End() token.Pos { return x.Value.End() } -func (x *ChanType) End() token.Pos { return x.Value.End() } - -// exprNode() ensures that only expression/type nodes can be -// assigned to an ExprNode. -// -func (*BadExpr) exprNode() {} -func (*Ident) exprNode() {} -func (*Ellipsis) exprNode() {} -func (*BasicLit) exprNode() {} -func (*FuncLit) exprNode() {} -func (*CompositeLit) exprNode() {} -func (*ParenExpr) exprNode() {} -func (*SelectorExpr) exprNode() {} -func (*IndexExpr) exprNode() {} -func (*SliceExpr) exprNode() {} -func (*TypeAssertExpr) exprNode() {} -func (*CallExpr) exprNode() {} -func (*StarExpr) exprNode() {} -func (*UnaryExpr) exprNode() {} -func (*BinaryExpr) exprNode() {} -func (*KeyValueExpr) exprNode() {} - -func (*ArrayType) exprNode() {} -func (*StructType) exprNode() {} -func (*FuncType) exprNode() {} -func (*InterfaceType) exprNode() {} -func (*MapType) exprNode() {} -func (*ChanType) exprNode() {} - -// ---------------------------------------------------------------------------- -// Convenience functions for Idents - -var noPos token.Pos - -// NewIdent creates a new Ident without position. -// Useful for ASTs generated by code other than the Go parser. -// -func NewIdent(name string) *Ident { return &Ident{noPos, name, nil} } - -// IsExported returns whether name is an exported Go symbol -// (i.e., whether it begins with an uppercase letter). -// -func IsExported(name string) bool { - ch, _ := utf8.DecodeRuneInString(name) - return unicode.IsUpper(ch) -} - -// IsExported returns whether id is an exported Go symbol -// (i.e., whether it begins with an uppercase letter). -// -func (id *Ident) IsExported() bool { return IsExported(id.Name) } - -func (id *Ident) String() string { - if id != nil { - return id.Name - } - return "<nil>" -} - -// ---------------------------------------------------------------------------- -// Statements - -// A statement is represented by a tree consisting of one -// or more of the following concrete statement nodes. -// -type ( - // A BadStmt node is a placeholder for statements containing - // syntax errors for which no correct statement nodes can be - // created. - // - BadStmt struct { - From, To token.Pos // position range of bad statement - } - - // A DeclStmt node represents a declaration in a statement list. - DeclStmt struct { - Decl Decl // *GenDecl with CONST, TYPE, or VAR token - } - - // An EmptyStmt node represents an empty statement. - // The "position" of the empty statement is the position - // of the immediately preceding semicolon. - // - EmptyStmt struct { - Semicolon token.Pos // position of preceding ";" - } - - // A LabeledStmt node represents a labeled statement. - LabeledStmt struct { - Label *Ident - Colon token.Pos // position of ":" - Stmt Stmt - } - - // An ExprStmt node represents a (stand-alone) expression - // in a statement list. - // - ExprStmt struct { - X Expr // expression - } - - // A SendStmt node represents a send statement. - SendStmt struct { - Chan Expr - Arrow token.Pos // position of "<-" - Value Expr - } - - // An IncDecStmt node represents an increment or decrement statement. - IncDecStmt struct { - X Expr - TokPos token.Pos // position of Tok - Tok token.Token // INC or DEC - } - - // An AssignStmt node represents an assignment or - // a short variable declaration. - // - AssignStmt struct { - Lhs []Expr - TokPos token.Pos // position of Tok - Tok token.Token // assignment token, DEFINE - Rhs []Expr - } - - // A GoStmt node represents a go statement. - GoStmt struct { - Go token.Pos // position of "go" keyword - Call *CallExpr - } - - // A DeferStmt node represents a defer statement. - DeferStmt struct { - Defer token.Pos // position of "defer" keyword - Call *CallExpr - } - - // A ReturnStmt node represents a return statement. - ReturnStmt struct { - Return token.Pos // position of "return" keyword - Results []Expr // result expressions; or nil - } - - // A BranchStmt node represents a break, continue, goto, - // or fallthrough statement. - // - BranchStmt struct { - TokPos token.Pos // position of Tok - Tok token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH) - Label *Ident // label name; or nil - } - - // A BlockStmt node represents a braced statement list. - BlockStmt struct { - Lbrace token.Pos // position of "{" - List []Stmt - Rbrace token.Pos // position of "}" - } - - // An IfStmt node represents an if statement. - IfStmt struct { - If token.Pos // position of "if" keyword - Init Stmt // initialization statement; or nil - Cond Expr // condition - Body *BlockStmt - Else Stmt // else branch; or nil - } - - // A CaseClause represents a case of an expression or type switch statement. - CaseClause struct { - Case token.Pos // position of "case" or "default" keyword - List []Expr // list of expressions or types; nil means default case - Colon token.Pos // position of ":" - Body []Stmt // statement list; or nil - } - - // A SwitchStmt node represents an expression switch statement. - SwitchStmt struct { - Switch token.Pos // position of "switch" keyword - Init Stmt // initialization statement; or nil - Tag Expr // tag expression; or nil - Body *BlockStmt // CaseClauses only - } - - // An TypeSwitchStmt node represents a type switch statement. - TypeSwitchStmt struct { - Switch token.Pos // position of "switch" keyword - Init Stmt // initialization statement; or nil - Assign Stmt // x := y.(type) or y.(type) - Body *BlockStmt // CaseClauses only - } - - // A CommClause node represents a case of a select statement. - CommClause struct { - Case token.Pos // position of "case" or "default" keyword - Comm Stmt // send or receive statement; nil means default case - Colon token.Pos // position of ":" - Body []Stmt // statement list; or nil - } - - // An SelectStmt node represents a select statement. - SelectStmt struct { - Select token.Pos // position of "select" keyword - Body *BlockStmt // CommClauses only - } - - // A ForStmt represents a for statement. - ForStmt struct { - For token.Pos // position of "for" keyword - Init Stmt // initialization statement; or nil - Cond Expr // condition; or nil - Post Stmt // post iteration statement; or nil - Body *BlockStmt - } - - // A RangeStmt represents a for statement with a range clause. - RangeStmt struct { - For token.Pos // position of "for" keyword - Key, Value Expr // Value may be nil - TokPos token.Pos // position of Tok - Tok token.Token // ASSIGN, DEFINE - X Expr // value to range over - Body *BlockStmt - } -) - -// Pos and End implementations for statement nodes. -// -func (s *BadStmt) Pos() token.Pos { return s.From } -func (s *DeclStmt) Pos() token.Pos { return s.Decl.Pos() } -func (s *EmptyStmt) Pos() token.Pos { return s.Semicolon } -func (s *LabeledStmt) Pos() token.Pos { return s.Label.Pos() } -func (s *ExprStmt) Pos() token.Pos { return s.X.Pos() } -func (s *SendStmt) Pos() token.Pos { return s.Chan.Pos() } -func (s *IncDecStmt) Pos() token.Pos { return s.X.Pos() } -func (s *AssignStmt) Pos() token.Pos { return s.Lhs[0].Pos() } -func (s *GoStmt) Pos() token.Pos { return s.Go } -func (s *DeferStmt) Pos() token.Pos { return s.Defer } -func (s *ReturnStmt) Pos() token.Pos { return s.Return } -func (s *BranchStmt) Pos() token.Pos { return s.TokPos } -func (s *BlockStmt) Pos() token.Pos { return s.Lbrace } -func (s *IfStmt) Pos() token.Pos { return s.If } -func (s *CaseClause) Pos() token.Pos { return s.Case } -func (s *SwitchStmt) Pos() token.Pos { return s.Switch } -func (s *TypeSwitchStmt) Pos() token.Pos { return s.Switch } -func (s *CommClause) Pos() token.Pos { return s.Case } -func (s *SelectStmt) Pos() token.Pos { return s.Select } -func (s *ForStmt) Pos() token.Pos { return s.For } -func (s *RangeStmt) Pos() token.Pos { return s.For } - -func (s *BadStmt) End() token.Pos { return s.To } -func (s *DeclStmt) End() token.Pos { return s.Decl.End() } -func (s *EmptyStmt) End() token.Pos { - return s.Semicolon + 1 /* len(";") */ -} -func (s *LabeledStmt) End() token.Pos { return s.Stmt.End() } -func (s *ExprStmt) End() token.Pos { return s.X.End() } -func (s *SendStmt) End() token.Pos { return s.Value.End() } -func (s *IncDecStmt) End() token.Pos { - return s.TokPos + 2 /* len("++") */ -} -func (s *AssignStmt) End() token.Pos { return s.Rhs[len(s.Rhs)-1].End() } -func (s *GoStmt) End() token.Pos { return s.Call.End() } -func (s *DeferStmt) End() token.Pos { return s.Call.End() } -func (s *ReturnStmt) End() token.Pos { - if n := len(s.Results); n > 0 { - return s.Results[n-1].End() - } - return s.Return + 6 // len("return") -} -func (s *BranchStmt) End() token.Pos { - if s.Label != nil { - return s.Label.End() - } - return token.Pos(int(s.TokPos) + len(s.Tok.String())) -} -func (s *BlockStmt) End() token.Pos { return s.Rbrace + 1 } -func (s *IfStmt) End() token.Pos { - if s.Else != nil { - return s.Else.End() - } - return s.Body.End() -} -func (s *CaseClause) End() token.Pos { - if n := len(s.Body); n > 0 { - return s.Body[n-1].End() - } - return s.Colon + 1 -} -func (s *SwitchStmt) End() token.Pos { return s.Body.End() } -func (s *TypeSwitchStmt) End() token.Pos { return s.Body.End() } -func (s *CommClause) End() token.Pos { - if n := len(s.Body); n > 0 { - return s.Body[n-1].End() - } - return s.Colon + 1 -} -func (s *SelectStmt) End() token.Pos { return s.Body.End() } -func (s *ForStmt) End() token.Pos { return s.Body.End() } -func (s *RangeStmt) End() token.Pos { return s.Body.End() } - -// stmtNode() ensures that only statement nodes can be -// assigned to a StmtNode. -// -func (*BadStmt) stmtNode() {} -func (*DeclStmt) stmtNode() {} -func (*EmptyStmt) stmtNode() {} -func (*LabeledStmt) stmtNode() {} -func (*ExprStmt) stmtNode() {} -func (*SendStmt) stmtNode() {} -func (*IncDecStmt) stmtNode() {} -func (*AssignStmt) stmtNode() {} -func (*GoStmt) stmtNode() {} -func (*DeferStmt) stmtNode() {} -func (*ReturnStmt) stmtNode() {} -func (*BranchStmt) stmtNode() {} -func (*BlockStmt) stmtNode() {} -func (*IfStmt) stmtNode() {} -func (*CaseClause) stmtNode() {} -func (*SwitchStmt) stmtNode() {} -func (*TypeSwitchStmt) stmtNode() {} -func (*CommClause) stmtNode() {} -func (*SelectStmt) stmtNode() {} -func (*ForStmt) stmtNode() {} -func (*RangeStmt) stmtNode() {} - -// ---------------------------------------------------------------------------- -// Declarations - -// A Spec node represents a single (non-parenthesized) import, -// constant, type, or variable declaration. -// -type ( - // The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec. - 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 // import path - Comment *CommentGroup // line comments; or nil - EndPos token.Pos // end of spec (overrides Path.Pos if nonzero) - } - - // 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 (len(Names) > 0) - 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 // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes - Comment *CommentGroup // line comments; or nil - } -) - -// Pos and End implementations for spec nodes. -// -func (s *ImportSpec) Pos() token.Pos { - if s.Name != nil { - return s.Name.Pos() - } - return s.Path.Pos() -} -func (s *ValueSpec) Pos() token.Pos { return s.Names[0].Pos() } -func (s *TypeSpec) Pos() token.Pos { return s.Name.Pos() } - -func (s *ImportSpec) End() token.Pos { - if s.EndPos != 0 { - return s.EndPos - } - return s.Path.End() -} - -func (s *ValueSpec) End() token.Pos { - if n := len(s.Values); n > 0 { - return s.Values[n-1].End() - } - if s.Type != nil { - return s.Type.End() - } - return s.Names[len(s.Names)-1].End() -} -func (s *TypeSpec) End() token.Pos { return s.Type.End() } - -// specNode() ensures that only spec nodes can be -// assigned to a Spec. -// -func (*ImportSpec) specNode() {} -func (*ValueSpec) specNode() {} -func (*TypeSpec) specNode() {} - -// A declaration is represented by one of the following declaration nodes. -// -type ( - // A BadDecl node is a placeholder for declarations containing - // syntax errors for which no correct declaration nodes can be - // created. - // - BadDecl struct { - From, To token.Pos // position range of bad declaration - } - - // A GenDecl node (generic declaration node) represents an import, - // constant, type or variable declaration. A valid Lparen position - // (Lparen.Line > 0) indicates a parenthesized declaration. - // - // Relationship between Tok value and Specs element type: - // - // token.IMPORT *ImportSpec - // token.CONST *ValueSpec - // token.TYPE *TypeSpec - // token.VAR *ValueSpec - // - GenDecl struct { - Doc *CommentGroup // associated documentation; or nil - TokPos token.Pos // position of Tok - Tok token.Token // IMPORT, CONST, TYPE, VAR - Lparen token.Pos // position of '(', if any - Specs []Spec - Rparen token.Pos // position of ')', if any - } - - // A FuncDecl node represents a function declaration. - FuncDecl struct { - Doc *CommentGroup // associated documentation; or nil - Recv *FieldList // 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) - } -) - -// Pos and End implementations for declaration nodes. -// -func (d *BadDecl) Pos() token.Pos { return d.From } -func (d *GenDecl) Pos() token.Pos { return d.TokPos } -func (d *FuncDecl) Pos() token.Pos { return d.Type.Pos() } - -func (d *BadDecl) End() token.Pos { return d.To } -func (d *GenDecl) End() token.Pos { - if d.Rparen.IsValid() { - return d.Rparen + 1 - } - return d.Specs[0].End() -} -func (d *FuncDecl) End() token.Pos { - if d.Body != nil { - return d.Body.End() - } - return d.Type.End() -} - -// declNode() ensures that only declaration nodes can be -// assigned to a DeclNode. -// -func (*BadDecl) declNode() {} -func (*GenDecl) declNode() {} -func (*FuncDecl) declNode() {} - -// ---------------------------------------------------------------------------- -// Files and packages - -// A File node represents a Go source file. -// -// The Comments list contains all comments in the source file in order of -// appearance, including the comments that are pointed to from other nodes -// via Doc and Comment fields. -// -type File struct { - Doc *CommentGroup // associated documentation; or nil - Package token.Pos // position of "package" keyword - Name *Ident // package name - Decls []Decl // top-level declarations; or nil - Scope *Scope // package scope (this file only) - Imports []*ImportSpec // imports in this file - Unresolved []*Ident // unresolved identifiers in this file - Comments []*CommentGroup // list of all comments in the source file -} - -func (f *File) Pos() token.Pos { return f.Package } -func (f *File) End() token.Pos { - if n := len(f.Decls); n > 0 { - return f.Decls[n-1].End() - } - return f.Name.End() -} - -// A Package node represents a set of source files -// collectively building a Go package. -// -type Package struct { - Name string // package name - Scope *Scope // package scope across all files - Imports map[string]*Object // map of package id -> package object - Files map[string]*File // Go source files by filename -} - -func (p *Package) Pos() token.Pos { return token.NoPos } -func (p *Package) End() token.Pos { return token.NoPos } diff --git a/gcc-4.8.1/libgo/go/go/ast/ast_test.go b/gcc-4.8.1/libgo/go/go/ast/ast_test.go deleted file mode 100644 index 1a6a283f2..000000000 --- a/gcc-4.8.1/libgo/go/go/ast/ast_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ast - -import ( - "testing" -) - -var comments = []struct { - list []string - text string -}{ - {[]string{"//"}, ""}, - {[]string{"// "}, ""}, - {[]string{"//", "//", "// "}, ""}, - {[]string{"// foo "}, "foo\n"}, - {[]string{"//", "//", "// foo"}, "foo\n"}, - {[]string{"// foo bar "}, "foo bar\n"}, - {[]string{"// foo", "// bar"}, "foo\nbar\n"}, - {[]string{"// foo", "//", "//", "//", "// bar"}, "foo\n\nbar\n"}, - {[]string{"// foo", "/* bar */"}, "foo\n bar\n"}, - {[]string{"//", "//", "//", "// foo", "//", "//", "//"}, "foo\n"}, - - {[]string{"/**/"}, ""}, - {[]string{"/* */"}, ""}, - {[]string{"/**/", "/**/", "/* */"}, ""}, - {[]string{"/* Foo */"}, " Foo\n"}, - {[]string{"/* Foo Bar */"}, " Foo Bar\n"}, - {[]string{"/* Foo*/", "/* Bar*/"}, " Foo\n Bar\n"}, - {[]string{"/* Foo*/", "/**/", "/**/", "/**/", "// Bar"}, " Foo\n\nBar\n"}, - {[]string{"/* Foo*/", "/*\n*/", "//", "/*\n*/", "// Bar"}, " Foo\n\nBar\n"}, - {[]string{"/* Foo*/", "// Bar"}, " Foo\nBar\n"}, - {[]string{"/* Foo\n Bar*/"}, " Foo\n Bar\n"}, -} - -func TestCommentText(t *testing.T) { - for i, c := range comments { - list := make([]*Comment, len(c.list)) - for i, s := range c.list { - list[i] = &Comment{Text: s} - } - - text := (&CommentGroup{list}).Text() - if text != c.text { - t.Errorf("case %d: got %q; expected %q", i, text, c.text) - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/ast/commentmap.go b/gcc-4.8.1/libgo/go/go/ast/commentmap.go deleted file mode 100644 index 252d460af..000000000 --- a/gcc-4.8.1/libgo/go/go/ast/commentmap.go +++ /dev/null @@ -1,332 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ast - -import ( - "bytes" - "fmt" - "go/token" - "sort" -) - -type byPos []*CommentGroup - -func (a byPos) Len() int { return len(a) } -func (a byPos) Less(i, j int) bool { return a[i].Pos() < a[j].Pos() } -func (a byPos) Swap(i, j int) { a[i], a[j] = a[j], a[i] } - -// sortComments sorts the list of comment groups in source order. -// -func sortComments(list []*CommentGroup) { - // TODO(gri): Does it make sense to check for sorted-ness - // first (because we know that sorted-ness is - // very likely)? - if orderedList := byPos(list); !sort.IsSorted(orderedList) { - sort.Sort(orderedList) - } -} - -// A CommentMap maps an AST node to a list of comment groups -// associated with it. See NewCommentMap for a description of -// the association. -// -type CommentMap map[Node][]*CommentGroup - -func (cmap CommentMap) addComment(n Node, c *CommentGroup) { - list := cmap[n] - if len(list) == 0 { - list = []*CommentGroup{c} - } else { - list = append(list, c) - } - cmap[n] = list -} - -type byInterval []Node - -func (a byInterval) Len() int { return len(a) } -func (a byInterval) Less(i, j int) bool { - pi, pj := a[i].Pos(), a[j].Pos() - return pi < pj || pi == pj && a[i].End() > a[j].End() -} -func (a byInterval) Swap(i, j int) { a[i], a[j] = a[j], a[i] } - -// nodeList returns the list of nodes of the AST n in source order. -// -func nodeList(n Node) []Node { - var list []Node - Inspect(n, func(n Node) bool { - // don't collect comments - switch n.(type) { - case nil, *CommentGroup, *Comment: - return false - } - list = append(list, n) - return true - }) - // Note: The current implementation assumes that Inspect traverses the - // AST in depth-first and thus _source_ order. If AST traversal - // does not follow source order, the sorting call below will be - // required. - // sort.Sort(byInterval(list)) - return list -} - -// A commentListReader helps iterating through a list of comment groups. -// -type commentListReader struct { - fset *token.FileSet - list []*CommentGroup - index int - comment *CommentGroup // comment group at current index - pos, end token.Position // source interval of comment group at current index -} - -func (r *commentListReader) eol() bool { - return r.index >= len(r.list) -} - -func (r *commentListReader) next() { - if !r.eol() { - r.comment = r.list[r.index] - r.pos = r.fset.Position(r.comment.Pos()) - r.end = r.fset.Position(r.comment.End()) - r.index++ - } -} - -// A nodeStack keeps track of nested nodes. -// A node lower on the stack lexically contains the nodes higher on the stack. -// -type nodeStack []Node - -// push pops all nodes that appear lexically before n -// and then pushes n on the stack. -// -func (s *nodeStack) push(n Node) { - s.pop(n.Pos()) - *s = append((*s), n) -} - -// pop pops all nodes that appear lexically before pos -// (i.e., whose lexical extent has ended before or at pos). -// It returns the last node popped. -// -func (s *nodeStack) pop(pos token.Pos) (top Node) { - i := len(*s) - for i > 0 && (*s)[i-1].End() <= pos { - top = (*s)[i-1] - i-- - } - *s = (*s)[0:i] - return top -} - -// NewCommentMap creates a new comment map by associating comment groups -// of the comments list with the nodes of the AST specified by node. -// -// A comment group g is associated with a node n if: -// -// - g starts on the same line as n ends -// - g starts on the line immediately following n, and there is -// at least one empty line after g and before the next node -// - g starts before n and is not associated to the node before n -// via the previous rules -// -// NewCommentMap tries to associate a comment group to the "largest" -// node possible: For instance, if the comment is a line comment -// trailing an assignment, the comment is associated with the entire -// assignment rather than just the last operand in the assignment. -// -func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap { - if len(comments) == 0 { - return nil // no comments to map - } - - cmap := make(CommentMap) - - // set up comment reader r - tmp := make([]*CommentGroup, len(comments)) - copy(tmp, comments) // don't change incomming comments - sortComments(tmp) - r := commentListReader{fset: fset, list: tmp} // !r.eol() because len(comments) > 0 - r.next() - - // create node list in lexical order - nodes := nodeList(node) - nodes = append(nodes, nil) // append sentinel - - // set up iteration variables - var ( - p Node // previous node - pend token.Position // end of p - pg Node // previous node group (enclosing nodes of "importance") - pgend token.Position // end of pg - stack nodeStack // stack of node groups - ) - - for _, q := range nodes { - var qpos token.Position - if q != nil { - qpos = fset.Position(q.Pos()) // current node position - } else { - // set fake sentinel position to infinity so that - // all comments get processed before the sentinel - const infinity = 1 << 30 - qpos.Offset = infinity - qpos.Line = infinity - } - - // process comments before current node - for r.end.Offset <= qpos.Offset { - // determine recent node group - if top := stack.pop(r.comment.Pos()); top != nil { - pg = top - pgend = fset.Position(pg.End()) - } - // Try to associate a comment first with a node group - // (i.e., a node of "importance" such as a declaration); - // if that fails, try to associate it with the most recent - // node. - // TODO(gri) try to simplify the logic below - var assoc Node - switch { - case pg != nil && - (pgend.Line == r.pos.Line || - pgend.Line+1 == r.pos.Line && r.end.Line+1 < qpos.Line): - // 1) comment starts on same line as previous node group ends, or - // 2) comment starts on the line immediately after the - // previous node group and there is an empty line before - // the current node - // => associate comment with previous node group - assoc = pg - case p != nil && - (pend.Line == r.pos.Line || - pend.Line+1 == r.pos.Line && r.end.Line+1 < qpos.Line || - q == nil): - // same rules apply as above for p rather than pg, - // but also associate with p if we are at the end (q == nil) - assoc = p - default: - // otherwise, associate comment with current node - if q == nil { - // we can only reach here if there was no p - // which would imply that there were no nodes - panic("internal error: no comments should be associated with sentinel") - } - assoc = q - } - cmap.addComment(assoc, r.comment) - if r.eol() { - return cmap - } - r.next() - } - - // update previous node - p = q - pend = fset.Position(p.End()) - - // update previous node group if we see an "important" node - switch q.(type) { - case *File, *Field, Decl, Spec, Stmt: - stack.push(q) - } - } - - return cmap -} - -// Update replaces an old node in the comment map with the new node -// and returns the new node. Comments that were associated with the -// old node are associated with the new node. -// -func (cmap CommentMap) Update(old, new Node) Node { - if list := cmap[old]; len(list) > 0 { - delete(cmap, old) - cmap[new] = append(cmap[new], list...) - } - return new -} - -// Filter returns a new comment map consisting of only those -// entries of cmap for which a corresponding node exists in -// the AST specified by node. -// -func (cmap CommentMap) Filter(node Node) CommentMap { - umap := make(CommentMap) - Inspect(node, func(n Node) bool { - if g := cmap[n]; len(g) > 0 { - umap[n] = g - } - return true - }) - return umap -} - -// Comments returns the list of comment groups in the comment map. -// The result is sorted is source order. -// -func (cmap CommentMap) Comments() []*CommentGroup { - list := make([]*CommentGroup, 0, len(cmap)) - for _, e := range cmap { - list = append(list, e...) - } - sortComments(list) - return list -} - -func summary(list []*CommentGroup) string { - const maxLen = 40 - var buf bytes.Buffer - - // collect comments text -loop: - for _, group := range list { - // Note: CommentGroup.Text() does too much work for what we - // need and would only replace this innermost loop. - // Just do it explicitly. - for _, comment := range group.List { - if buf.Len() >= maxLen { - break loop - } - buf.WriteString(comment.Text) - } - } - - // truncate if too long - if buf.Len() > maxLen { - buf.Truncate(maxLen - 3) - buf.WriteString("...") - } - - // replace any invisibles with blanks - bytes := buf.Bytes() - for i, b := range bytes { - switch b { - case '\t', '\n', '\r': - bytes[i] = ' ' - } - } - - return string(bytes) -} - -func (cmap CommentMap) String() string { - var buf bytes.Buffer - fmt.Fprintln(&buf, "CommentMap {") - for node, comment := range cmap { - // print name of identifiers; print node type for other nodes - var s string - if ident, ok := node.(*Ident); ok { - s = ident.Name - } else { - s = fmt.Sprintf("%T", node) - } - fmt.Fprintf(&buf, "\t%p %20s: %s\n", node, s, summary(comment)) - } - fmt.Fprintln(&buf, "}") - return buf.String() -} diff --git a/gcc-4.8.1/libgo/go/go/ast/commentmap_test.go b/gcc-4.8.1/libgo/go/go/ast/commentmap_test.go deleted file mode 100644 index e372eab74..000000000 --- a/gcc-4.8.1/libgo/go/go/ast/commentmap_test.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// To avoid a cyclic dependency with go/parser, this file is in a separate package. - -package ast_test - -import ( - "bytes" - "fmt" - . "go/ast" - "go/parser" - "go/token" - "sort" - "testing" -) - -const src = ` -// the very first comment - -// package p -package p /* the name is p */ - -// imports -import ( - "bytes" // bytes - "fmt" // fmt - "go/ast" - "go/parser" -) - -// T -type T struct { - a, b, c int // associated with a, b, c - // associated with x, y - x, y float64 // float values - z complex128 // complex value -} -// also associated with T - -// x -var x = 0 // x = 0 -// also associated with x - -// f1 -func f1() { - /* associated with s1 */ - s1() - // also associated with s1 - - // associated with s2 - - // also associated with s2 - s2() // line comment for s2 -} -// associated with f1 -// also associated with f1 - -// associated with f2 - -// f2 -func f2() { -} - -func f3() { - i := 1 /* 1 */ + 2 // addition - _ = i -} - -// the very last comment -` - -// res maps a key of the form "line number: node type" -// to the associated comments' text. -// -var res = map[string]string{ - " 5: *ast.File": "the very first comment\npackage p\n", - " 5: *ast.Ident": " the name is p\n", - " 8: *ast.GenDecl": "imports\n", - " 9: *ast.ImportSpec": "bytes\n", - "10: *ast.ImportSpec": "fmt\n", - "16: *ast.GenDecl": "T\nalso associated with T\n", - "17: *ast.Field": "associated with a, b, c\n", - "19: *ast.Field": "associated with x, y\nfloat values\n", - "20: *ast.Field": "complex value\n", - "25: *ast.GenDecl": "x\nx = 0\nalso associated with x\n", - "29: *ast.FuncDecl": "f1\nassociated with f1\nalso associated with f1\n", - "31: *ast.ExprStmt": " associated with s1\nalso associated with s1\n", - "37: *ast.ExprStmt": "associated with s2\nalso associated with s2\nline comment for s2\n", - "45: *ast.FuncDecl": "associated with f2\nf2\n", - "49: *ast.AssignStmt": "addition\n", - "49: *ast.BasicLit": " 1\n", - "50: *ast.Ident": "the very last comment\n", -} - -func ctext(list []*CommentGroup) string { - var buf bytes.Buffer - for _, g := range list { - buf.WriteString(g.Text()) - } - return buf.String() -} - -func TestCommentMap(t *testing.T) { - fset := token.NewFileSet() - f, err := parser.ParseFile(fset, "", src, parser.ParseComments) - if err != nil { - t.Fatal(err) - } - cmap := NewCommentMap(fset, f, f.Comments) - - // very correct association of comments - for n, list := range cmap { - key := fmt.Sprintf("%2d: %T", fset.Position(n.Pos()).Line, n) - got := ctext(list) - want := res[key] - if got != want { - t.Errorf("%s: got %q; want %q", key, got, want) - } - } - - // verify that no comments got lost - if n := len(cmap.Comments()); n != len(f.Comments) { - t.Errorf("got %d comment groups in map; want %d", n, len(f.Comments)) - } - - // support code to update test: - // set genMap to true to generate res map - const genMap = false - if genMap { - out := make([]string, 0, len(cmap)) - for n, list := range cmap { - out = append(out, fmt.Sprintf("\t\"%2d: %T\":\t%q,", fset.Position(n.Pos()).Line, n, ctext(list))) - } - sort.Strings(out) - for _, s := range out { - fmt.Println(s) - } - } -} - -// TODO(gri): add tests for Filter. diff --git a/gcc-4.8.1/libgo/go/go/ast/filter.go b/gcc-4.8.1/libgo/go/go/ast/filter.go deleted file mode 100644 index 4db5814cb..000000000 --- a/gcc-4.8.1/libgo/go/go/ast/filter.go +++ /dev/null @@ -1,445 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ast - -import ( - "go/token" - "sort" -) - -// ---------------------------------------------------------------------------- -// Export filtering - -// exportFilter is a special filter function to extract exported nodes. -func exportFilter(name string) bool { - return IsExported(name) -} - -// FileExports trims the AST for a Go source file in place such that -// only exported nodes remain: all top-level identifiers which are not exported -// and their associated information (such as type, initial value, or function -// body) are removed. Non-exported fields and methods of exported types are -// stripped. The File.Comments list is not changed. -// -// FileExports returns true if there are exported declarations; -// it returns false otherwise. -// -func FileExports(src *File) bool { - return filterFile(src, exportFilter, true) -} - -// PackageExports trims the AST for a Go package in place such that -// only exported nodes remain. The pkg.Files list is not changed, so that -// file names and top-level package comments don't get lost. -// -// PackageExports returns true if there are exported declarations; -// it returns false otherwise. -// -func PackageExports(pkg *Package) bool { - return filterPackage(pkg, exportFilter, true) -} - -// ---------------------------------------------------------------------------- -// General filtering - -type Filter func(string) bool - -func filterIdentList(list []*Ident, f Filter) []*Ident { - j := 0 - for _, x := range list { - if f(x.Name) { - list[j] = x - j++ - } - } - return list[0:j] -} - -// fieldName assumes that x is the type of an anonymous field and -// returns the corresponding field name. If x is not an acceptable -// anonymous field, the result is nil. -// -func fieldName(x Expr) *Ident { - switch t := x.(type) { - case *Ident: - return t - case *SelectorExpr: - if _, ok := t.X.(*Ident); ok { - return t.Sel - } - case *StarExpr: - return fieldName(t.X) - } - return nil -} - -func filterFieldList(fields *FieldList, filter Filter, export bool) (removedFields bool) { - if fields == nil { - return false - } - list := fields.List - j := 0 - for _, f := range list { - keepField := false - if len(f.Names) == 0 { - // anonymous field - name := fieldName(f.Type) - keepField = name != nil && filter(name.Name) - } else { - n := len(f.Names) - f.Names = filterIdentList(f.Names, filter) - if len(f.Names) < n { - removedFields = true - } - keepField = len(f.Names) > 0 - } - if keepField { - if export { - filterType(f.Type, filter, export) - } - list[j] = f - j++ - } - } - if j < len(list) { - removedFields = true - } - fields.List = list[0:j] - return -} - -func filterParamList(fields *FieldList, filter Filter, export bool) bool { - if fields == nil { - return false - } - var b bool - for _, f := range fields.List { - if filterType(f.Type, filter, export) { - b = true - } - } - return b -} - -func filterType(typ Expr, f Filter, export bool) bool { - switch t := typ.(type) { - case *Ident: - return f(t.Name) - case *ParenExpr: - return filterType(t.X, f, export) - case *ArrayType: - return filterType(t.Elt, f, export) - case *StructType: - if filterFieldList(t.Fields, f, export) { - t.Incomplete = true - } - return len(t.Fields.List) > 0 - case *FuncType: - b1 := filterParamList(t.Params, f, export) - b2 := filterParamList(t.Results, f, export) - return b1 || b2 - case *InterfaceType: - if filterFieldList(t.Methods, f, export) { - t.Incomplete = true - } - return len(t.Methods.List) > 0 - case *MapType: - b1 := filterType(t.Key, f, export) - b2 := filterType(t.Value, f, export) - return b1 || b2 - case *ChanType: - return filterType(t.Value, f, export) - } - return false -} - -func filterSpec(spec Spec, f Filter, export bool) bool { - switch s := spec.(type) { - case *ValueSpec: - s.Names = filterIdentList(s.Names, f) - if len(s.Names) > 0 { - if export { - filterType(s.Type, f, export) - } - return true - } - case *TypeSpec: - if f(s.Name.Name) { - if export { - filterType(s.Type, f, export) - } - return true - } - if !export { - // For general filtering (not just exports), - // filter type even if name is not filtered - // out. - // If the type contains filtered elements, - // keep the declaration. - return filterType(s.Type, f, export) - } - } - return false -} - -func filterSpecList(list []Spec, f Filter, export bool) []Spec { - j := 0 - for _, s := range list { - if filterSpec(s, f, export) { - list[j] = s - j++ - } - } - return list[0:j] -} - -// FilterDecl trims the AST for a Go declaration in place by removing -// all names (including struct field and interface method names, but -// not from parameter lists) that don't pass through the filter f. -// -// FilterDecl returns true if there are any declared names left after -// filtering; it returns false otherwise. -// -func FilterDecl(decl Decl, f Filter) bool { - return filterDecl(decl, f, false) -} - -func filterDecl(decl Decl, f Filter, export bool) bool { - switch d := decl.(type) { - case *GenDecl: - d.Specs = filterSpecList(d.Specs, f, export) - return len(d.Specs) > 0 - case *FuncDecl: - return f(d.Name.Name) - } - return false -} - -// FilterFile trims the AST for a Go file in place by removing all -// names from top-level declarations (including struct field and -// interface method names, but not from parameter lists) that don't -// pass through the filter f. If the declaration is empty afterwards, -// the declaration is removed from the AST. The File.Comments list -// is not changed. -// -// FilterFile returns true if there are any top-level declarations -// left after filtering; it returns false otherwise. -// -func FilterFile(src *File, f Filter) bool { - return filterFile(src, f, false) -} - -func filterFile(src *File, f Filter, export bool) bool { - j := 0 - for _, d := range src.Decls { - if filterDecl(d, f, export) { - src.Decls[j] = d - j++ - } - } - src.Decls = src.Decls[0:j] - return j > 0 -} - -// FilterPackage trims the AST for a Go package in place by removing -// all names from top-level declarations (including struct field and -// interface method names, but not from parameter lists) that don't -// pass through the filter f. If the declaration is empty afterwards, -// the declaration is removed from the AST. The pkg.Files list is not -// changed, so that file names and top-level package comments don't get -// lost. -// -// FilterPackage returns true if there are any top-level declarations -// left after filtering; it returns false otherwise. -// -func FilterPackage(pkg *Package, f Filter) bool { - return filterPackage(pkg, f, false) -} - -func filterPackage(pkg *Package, f Filter, export bool) bool { - hasDecls := false - for _, src := range pkg.Files { - if filterFile(src, f, export) { - hasDecls = true - } - } - return hasDecls -} - -// ---------------------------------------------------------------------------- -// Merging of package files - -// The MergeMode flags control the behavior of MergePackageFiles. -type MergeMode uint - -const ( - // If set, duplicate function declarations are excluded. - FilterFuncDuplicates MergeMode = 1 << iota - // If set, comments that are not associated with a specific - // AST node (as Doc or Comment) are excluded. - FilterUnassociatedComments - // If set, duplicate import declarations are excluded. - FilterImportDuplicates -) - -// separator is an empty //-style comment that is interspersed between -// different comment groups when they are concatenated into a single group -// -var separator = &Comment{noPos, "//"} - -// MergePackageFiles creates a file AST by merging the ASTs of the -// files belonging to a package. The mode flags control merging behavior. -// -func MergePackageFiles(pkg *Package, mode MergeMode) *File { - // Count the number of package docs, comments and declarations across - // all package files. Also, compute sorted list of filenames, so that - // subsequent iterations can always iterate in the same order. - ndocs := 0 - ncomments := 0 - ndecls := 0 - filenames := make([]string, len(pkg.Files)) - i := 0 - for filename, f := range pkg.Files { - filenames[i] = filename - i++ - if f.Doc != nil { - ndocs += len(f.Doc.List) + 1 // +1 for separator - } - ncomments += len(f.Comments) - ndecls += len(f.Decls) - } - sort.Strings(filenames) - - // Collect package comments from all package files into a single - // CommentGroup - the collected package documentation. 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 pos token.Pos - if ndocs > 0 { - list := make([]*Comment, ndocs-1) // -1: no separator before first group - i := 0 - for _, filename := range filenames { - f := pkg.Files[filename] - if f.Doc != nil { - if i > 0 { - // not the first group - add separator - list[i] = separator - i++ - } - for _, c := range f.Doc.List { - list[i] = c - i++ - } - if f.Package > pos { - // Keep the maximum package clause position as - // position for the package clause of the merged - // files. - pos = f.Package - } - } - } - doc = &CommentGroup{list} - } - - // Collect declarations from all package files. - var decls []Decl - if ndecls > 0 { - decls = make([]Decl, ndecls) - funcs := make(map[string]int) // map of global function name -> decls index - i := 0 // current index - n := 0 // number of filtered entries - for _, filename := range filenames { - f := pkg.Files[filename] - for _, d := range f.Decls { - if mode&FilterFuncDuplicates != 0 { - // A language entity may be declared multiple - // times in different package files; only at - // build time declarations must be unique. - // For now, exclude multiple declarations of - // functions - keep the one with documentation. - // - // TODO(gri): Expand this filtering to other - // entities (const, type, vars) if - // multiple declarations are common. - if f, isFun := d.(*FuncDecl); isFun { - name := f.Name.Name - if j, exists := funcs[name]; exists { - // function declared already - if decls[j] != nil && decls[j].(*FuncDecl).Doc == nil { - // existing declaration has no documentation; - // ignore the existing declaration - decls[j] = nil - } else { - // ignore the new declaration - d = nil - } - n++ // filtered an entry - } else { - funcs[name] = i - } - } - } - decls[i] = d - i++ - } - } - - // Eliminate nil entries from the decls list if entries were - // filtered. We do this using a 2nd pass in order to not disturb - // the original declaration order in the source (otherwise, this - // would also invalidate the monotonically increasing position - // info within a single file). - if n > 0 { - i = 0 - for _, d := range decls { - if d != nil { - decls[i] = d - i++ - } - } - decls = decls[0:i] - } - } - - // Collect import specs from all package files. - var imports []*ImportSpec - if mode&FilterImportDuplicates != 0 { - seen := make(map[string]bool) - for _, filename := range filenames { - f := pkg.Files[filename] - for _, imp := range f.Imports { - if path := imp.Path.Value; !seen[path] { - // TODO: consider handling cases where: - // - 2 imports exist with the same import path but - // have different local names (one should probably - // keep both of them) - // - 2 imports exist but only one has a comment - // - 2 imports exist and they both have (possibly - // different) comments - imports = append(imports, imp) - seen[path] = true - } - } - } - } else { - for _, f := range pkg.Files { - imports = append(imports, f.Imports...) - } - } - - // Collect comments from all package files. - var comments []*CommentGroup - if mode&FilterUnassociatedComments == 0 { - comments = make([]*CommentGroup, ncomments) - i := 0 - for _, f := range pkg.Files { - i += copy(comments[i:], f.Comments) - } - } - - // TODO(gri) need to compute unresolved identifiers! - return &File{doc, pos, NewIdent(pkg.Name), decls, pkg.Scope, imports, nil, comments} -} diff --git a/gcc-4.8.1/libgo/go/go/ast/import.go b/gcc-4.8.1/libgo/go/go/ast/import.go deleted file mode 100644 index a68a4840f..000000000 --- a/gcc-4.8.1/libgo/go/go/ast/import.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ast - -import ( - "go/token" - "sort" - "strconv" -) - -// SortImports sorts runs of consecutive import lines in import blocks in f. -func SortImports(fset *token.FileSet, f *File) { - for _, d := range f.Decls { - d, ok := d.(*GenDecl) - if !ok || d.Tok != token.IMPORT { - // Not an import declaration, so we're done. - // Imports are always first. - break - } - - if !d.Lparen.IsValid() { - // Not a block: sorted by default. - continue - } - - // Identify and sort runs of specs on successive lines. - i := 0 - for j, s := range d.Specs { - if j > i && fset.Position(s.Pos()).Line > 1+fset.Position(d.Specs[j-1].End()).Line { - // j begins a new run. End this one. - sortSpecs(fset, f, d.Specs[i:j]) - i = j - } - } - sortSpecs(fset, f, d.Specs[i:]) - } -} - -func importPath(s Spec) string { - t, err := strconv.Unquote(s.(*ImportSpec).Path.Value) - if err == nil { - return t - } - return "" -} - -type posSpan struct { - Start token.Pos - End token.Pos -} - -func sortSpecs(fset *token.FileSet, f *File, specs []Spec) { - // Avoid work if already sorted (also catches < 2 entries). - sorted := true - for i, s := range specs { - if i > 0 && importPath(specs[i-1]) > importPath(s) { - sorted = false - break - } - } - if sorted { - return - } - - // Record positions for specs. - pos := make([]posSpan, len(specs)) - for i, s := range specs { - pos[i] = posSpan{s.Pos(), s.End()} - } - - // Identify comments in this range. - // Any comment from pos[0].Start to the final line counts. - lastLine := fset.Position(pos[len(pos)-1].End).Line - cstart := len(f.Comments) - cend := len(f.Comments) - for i, g := range f.Comments { - if g.Pos() < pos[0].Start { - continue - } - if i < cstart { - cstart = i - } - if fset.Position(g.End()).Line > lastLine { - cend = i - break - } - } - comments := f.Comments[cstart:cend] - - // Assign each comment to the import spec preceding it. - importComment := map[*ImportSpec][]*CommentGroup{} - specIndex := 0 - for _, g := range comments { - for specIndex+1 < len(specs) && pos[specIndex+1].Start <= g.Pos() { - specIndex++ - } - s := specs[specIndex].(*ImportSpec) - importComment[s] = append(importComment[s], g) - } - - // Sort the import specs by import path. - // Reassign the import paths to have the same position sequence. - // Reassign each comment to abut the end of its spec. - // Sort the comments by new position. - sort.Sort(byImportPath(specs)) - for i, s := range specs { - s := s.(*ImportSpec) - if s.Name != nil { - s.Name.NamePos = pos[i].Start - } - s.Path.ValuePos = pos[i].Start - s.EndPos = pos[i].End - for _, g := range importComment[s] { - for _, c := range g.List { - c.Slash = pos[i].End - } - } - } - sort.Sort(byCommentPos(comments)) -} - -type byImportPath []Spec // slice of *ImportSpec - -func (x byImportPath) Len() int { return len(x) } -func (x byImportPath) Swap(i, j int) { x[i], x[j] = x[j], x[i] } -func (x byImportPath) Less(i, j int) bool { return importPath(x[i]) < importPath(x[j]) } - -type byCommentPos []*CommentGroup - -func (x byCommentPos) Len() int { return len(x) } -func (x byCommentPos) Swap(i, j int) { x[i], x[j] = x[j], x[i] } -func (x byCommentPos) Less(i, j int) bool { return x[i].Pos() < x[j].Pos() } diff --git a/gcc-4.8.1/libgo/go/go/ast/print.go b/gcc-4.8.1/libgo/go/go/ast/print.go deleted file mode 100644 index 4a1ce480f..000000000 --- a/gcc-4.8.1/libgo/go/go/ast/print.go +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains printing support for ASTs. - -package ast - -import ( - "fmt" - "go/token" - "io" - "os" - "reflect" -) - -// A FieldFilter may be provided to Fprint to control the output. -type FieldFilter func(name string, value reflect.Value) bool - -// NotNilFilter returns true for field values that are not nil; -// it returns false otherwise. -func NotNilFilter(_ string, v reflect.Value) bool { - switch v.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return !v.IsNil() - } - return true -} - -// Fprint prints the (sub-)tree starting at AST node x to w. -// If fset != nil, position information is interpreted relative -// to that file set. Otherwise positions are printed as integer -// values (file set specific offsets). -// -// A non-nil FieldFilter f may be provided to control the output: -// struct fields for which f(fieldname, fieldvalue) is true are -// are printed; all others are filtered from the output. Unexported -// struct fields are never printed. -// -func Fprint(w io.Writer, fset *token.FileSet, x interface{}, f FieldFilter) (err error) { - // setup printer - p := printer{ - output: w, - fset: fset, - filter: f, - ptrmap: make(map[interface{}]int), - last: '\n', // force printing of line number on first line - } - - // install error handler - defer func() { - if e := recover(); e != nil { - err = e.(localError).err // re-panics if it's not a localError - } - }() - - // print x - if x == nil { - p.printf("nil\n") - return - } - p.print(reflect.ValueOf(x)) - p.printf("\n") - - return -} - -// Print prints x to standard output, skipping nil fields. -// Print(fset, x) is the same as Fprint(os.Stdout, fset, x, NotNilFilter). -func Print(fset *token.FileSet, x interface{}) error { - return Fprint(os.Stdout, fset, x, NotNilFilter) -} - -type printer struct { - output io.Writer - fset *token.FileSet - filter FieldFilter - ptrmap map[interface{}]int // *T -> line number - indent int // current indentation level - last byte // the last byte processed by Write - line int // current line number -} - -var indent = []byte(". ") - -func (p *printer) Write(data []byte) (n int, err error) { - var m int - for i, b := range data { - // invariant: data[0:n] has been written - if b == '\n' { - m, err = p.output.Write(data[n : i+1]) - n += m - if err != nil { - return - } - p.line++ - } else if p.last == '\n' { - _, err = fmt.Fprintf(p.output, "%6d ", p.line) - if err != nil { - return - } - for j := p.indent; j > 0; j-- { - _, err = p.output.Write(indent) - if err != nil { - return - } - } - } - p.last = b - } - if len(data) > n { - m, err = p.output.Write(data[n:]) - n += m - } - return -} - -// localError wraps locally caught errors so we can distinguish -// them from genuine panics which we don't want to return as errors. -type localError struct { - err error -} - -// printf is a convenience wrapper that takes care of print errors. -func (p *printer) printf(format string, args ...interface{}) { - if _, err := fmt.Fprintf(p, format, args...); err != nil { - panic(localError{err}) - } -} - -// Implementation note: Print is written for AST nodes but could be -// used to print arbitrary data structures; such a version should -// probably be in a different package. -// -// Note: This code detects (some) cycles created via pointers but -// not cycles that are created via slices or maps containing the -// same slice or map. Code for general data structures probably -// should catch those as well. - -func (p *printer) print(x reflect.Value) { - if !NotNilFilter("", x) { - p.printf("nil") - return - } - - switch x.Kind() { - case reflect.Interface: - p.print(x.Elem()) - - case reflect.Map: - p.printf("%s (len = %d) {", x.Type(), x.Len()) - if x.Len() > 0 { - p.indent++ - p.printf("\n") - for _, key := range x.MapKeys() { - p.print(key) - p.printf(": ") - p.print(x.MapIndex(key)) - p.printf("\n") - } - p.indent-- - } - p.printf("}") - - case reflect.Ptr: - p.printf("*") - // type-checked ASTs may contain cycles - use ptrmap - // to keep track of objects that have been printed - // already and print the respective line number instead - ptr := x.Interface() - if line, exists := p.ptrmap[ptr]; exists { - p.printf("(obj @ %d)", line) - } else { - p.ptrmap[ptr] = p.line - p.print(x.Elem()) - } - - case reflect.Array: - p.printf("%s {", x.Type()) - if x.Len() > 0 { - p.indent++ - p.printf("\n") - for i, n := 0, x.Len(); i < n; i++ { - p.printf("%d: ", i) - p.print(x.Index(i)) - p.printf("\n") - } - p.indent-- - } - p.printf("}") - - case reflect.Slice: - if s, ok := x.Interface().([]byte); ok { - p.printf("%#q", s) - return - } - p.printf("%s (len = %d) {", x.Type(), x.Len()) - if x.Len() > 0 { - p.indent++ - p.printf("\n") - for i, n := 0, x.Len(); i < n; i++ { - p.printf("%d: ", i) - p.print(x.Index(i)) - p.printf("\n") - } - p.indent-- - } - p.printf("}") - - case reflect.Struct: - t := x.Type() - p.printf("%s {", t) - p.indent++ - first := true - for i, n := 0, t.NumField(); i < n; i++ { - // exclude non-exported fields because their - // values cannot be accessed via reflection - if name := t.Field(i).Name; IsExported(name) { - value := x.Field(i) - if p.filter == nil || p.filter(name, value) { - if first { - p.printf("\n") - first = false - } - p.printf("%s: ", name) - p.print(value) - p.printf("\n") - } - } - } - p.indent-- - p.printf("}") - - default: - v := x.Interface() - switch v := v.(type) { - case string: - // print strings in quotes - p.printf("%q", v) - return - case token.Pos: - // position values can be printed nicely if we have a file set - if p.fset != nil { - p.printf("%s", p.fset.Position(v)) - return - } - } - // default - p.printf("%v", v) - } -} diff --git a/gcc-4.8.1/libgo/go/go/ast/print_test.go b/gcc-4.8.1/libgo/go/go/ast/print_test.go deleted file mode 100644 index 210f16430..000000000 --- a/gcc-4.8.1/libgo/go/go/ast/print_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ast - -import ( - "bytes" - "strings" - "testing" -) - -var tests = []struct { - x interface{} // x is printed as s - s string -}{ - // basic types - {nil, "0 nil"}, - {true, "0 true"}, - {42, "0 42"}, - {3.14, "0 3.14"}, - {1 + 2.718i, "0 (1+2.718i)"}, - {"foobar", "0 \"foobar\""}, - - // maps - {map[Expr]string{}, `0 map[ast.Expr]string (len = 0) {}`}, - {map[string]int{"a": 1}, - `0 map[string]int (len = 1) { - 1 . "a": 1 - 2 }`}, - - // pointers - {new(int), "0 *0"}, - - // arrays - {[0]int{}, `0 [0]int {}`}, - {[3]int{1, 2, 3}, - `0 [3]int { - 1 . 0: 1 - 2 . 1: 2 - 3 . 2: 3 - 4 }`}, - {[...]int{42}, - `0 [1]int { - 1 . 0: 42 - 2 }`}, - - // slices - {[]int{}, `0 []int (len = 0) {}`}, - {[]int{1, 2, 3}, - `0 []int (len = 3) { - 1 . 0: 1 - 2 . 1: 2 - 3 . 2: 3 - 4 }`}, - - // structs - {struct{}{}, `0 struct {} {}`}, - {struct{ x int }{007}, `0 struct { x int } {}`}, - {struct{ X, y int }{42, 991}, - `0 struct { X int; y int } { - 1 . X: 42 - 2 }`}, - {struct{ X, Y int }{42, 991}, - `0 struct { X int; Y int } { - 1 . X: 42 - 2 . Y: 991 - 3 }`}, -} - -// Split s into lines, trim whitespace from all lines, and return -// the concatenated non-empty lines. -func trim(s string) string { - lines := strings.Split(s, "\n") - i := 0 - for _, line := range lines { - line = strings.TrimSpace(line) - if line != "" { - lines[i] = line - i++ - } - } - return strings.Join(lines[0:i], "\n") -} - -func TestPrint(t *testing.T) { - var buf bytes.Buffer - for _, test := range tests { - buf.Reset() - if err := Fprint(&buf, nil, test.x, nil); err != nil { - t.Errorf("Fprint failed: %s", err) - } - if s, ts := trim(buf.String()), trim(test.s); s != ts { - t.Errorf("got:\n%s\nexpected:\n%s\n", s, ts) - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/ast/resolve.go b/gcc-4.8.1/libgo/go/go/ast/resolve.go deleted file mode 100644 index 0406bfc58..000000000 --- a/gcc-4.8.1/libgo/go/go/ast/resolve.go +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements NewPackage. - -package ast - -import ( - "fmt" - "go/scanner" - "go/token" - "strconv" -) - -type pkgBuilder struct { - fset *token.FileSet - errors scanner.ErrorList -} - -func (p *pkgBuilder) error(pos token.Pos, msg string) { - p.errors.Add(p.fset.Position(pos), msg) -} - -func (p *pkgBuilder) errorf(pos token.Pos, format string, args ...interface{}) { - p.error(pos, fmt.Sprintf(format, args...)) -} - -func (p *pkgBuilder) declare(scope, altScope *Scope, obj *Object) { - alt := scope.Insert(obj) - if alt == nil && altScope != nil { - // see if there is a conflicting declaration in altScope - alt = altScope.Lookup(obj.Name) - } - if alt != nil { - prevDecl := "" - if pos := alt.Pos(); pos.IsValid() { - prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", p.fset.Position(pos)) - } - p.error(obj.Pos(), fmt.Sprintf("%s redeclared in this block%s", obj.Name, prevDecl)) - } -} - -func resolve(scope *Scope, ident *Ident) bool { - for ; scope != nil; scope = scope.Outer { - if obj := scope.Lookup(ident.Name); obj != nil { - ident.Obj = obj - return true - } - } - return false -} - -// An Importer resolves import paths to package Objects. -// The imports map records the packages already imported, -// indexed by package id (canonical import path). -// An Importer must determine the canonical import path and -// check the map to see if it is already present in the imports map. -// If so, the Importer can return the map entry. Otherwise, the -// Importer should load the package data for the given path into -// a new *Object (pkg), record pkg in the imports map, and then -// return pkg. -type Importer func(imports map[string]*Object, path string) (pkg *Object, err error) - -// NewPackage creates a new Package node from a set of File nodes. It resolves -// unresolved identifiers across files and updates each file's Unresolved list -// accordingly. If a non-nil importer and universe scope are provided, they are -// used to resolve identifiers not declared in any of the package files. Any -// remaining unresolved identifiers are reported as undeclared. If the files -// belong to different packages, one package name is selected and files with -// different package names are reported and then ignored. -// The result is a package node and a scanner.ErrorList if there were errors. -// -func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error) { - var p pkgBuilder - p.fset = fset - - // complete package scope - pkgName := "" - pkgScope := NewScope(universe) - for _, file := range files { - // package names must match - switch name := file.Name.Name; { - case pkgName == "": - pkgName = name - case name != pkgName: - p.errorf(file.Package, "package %s; expected %s", name, pkgName) - continue // ignore this file - } - - // collect top-level file objects in package scope - for _, obj := range file.Scope.Objects { - p.declare(pkgScope, nil, obj) - } - } - - // package global mapping of imported package ids to package objects - imports := make(map[string]*Object) - - // complete file scopes with imports and resolve identifiers - for _, file := range files { - // ignore file if it belongs to a different package - // (error has already been reported) - if file.Name.Name != pkgName { - continue - } - - // build file scope by processing all imports - importErrors := false - fileScope := NewScope(pkgScope) - for _, spec := range file.Imports { - if importer == nil { - importErrors = true - continue - } - path, _ := strconv.Unquote(spec.Path.Value) - pkg, err := importer(imports, path) - if err != nil { - p.errorf(spec.Path.Pos(), "could not import %s (%s)", path, err) - importErrors = true - continue - } - // TODO(gri) If a local package name != "." is provided, - // global identifier resolution could proceed even if the - // import failed. Consider adjusting the logic here a bit. - - // local name overrides imported package name - name := pkg.Name - if spec.Name != nil { - name = spec.Name.Name - } - - // add import to file scope - if name == "." { - // merge imported scope with file scope - for _, obj := range pkg.Data.(*Scope).Objects { - p.declare(fileScope, pkgScope, obj) - } - } else if name != "_" { - // declare imported package object in file scope - // (do not re-use pkg in the file scope but create - // a new object instead; the Decl field is different - // for different files) - obj := NewObj(Pkg, name) - obj.Decl = spec - obj.Data = pkg.Data - p.declare(fileScope, pkgScope, obj) - } - } - - // resolve identifiers - if importErrors { - // don't use the universe scope without correct imports - // (objects in the universe may be shadowed by imports; - // with missing imports, identifiers might get resolved - // incorrectly to universe objects) - pkgScope.Outer = nil - } - i := 0 - for _, ident := range file.Unresolved { - if !resolve(fileScope, ident) { - p.errorf(ident.Pos(), "undeclared name: %s", ident.Name) - file.Unresolved[i] = ident - i++ - } - - } - file.Unresolved = file.Unresolved[0:i] - pkgScope.Outer = universe // reset universe scope - } - - p.errors.Sort() - return &Package{pkgName, pkgScope, imports, files}, p.errors.Err() -} diff --git a/gcc-4.8.1/libgo/go/go/ast/scope.go b/gcc-4.8.1/libgo/go/go/ast/scope.go deleted file mode 100644 index 8df5b2c65..000000000 --- a/gcc-4.8.1/libgo/go/go/ast/scope.go +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements scopes and the objects they contain. - -package ast - -import ( - "bytes" - "fmt" - "go/token" -) - -// A Scope maintains the set of named language entities declared -// in the scope and a link to the immediately surrounding (outer) -// scope. -// -type Scope struct { - Outer *Scope - Objects map[string]*Object -} - -// NewScope creates a new scope nested in the outer scope. -func NewScope(outer *Scope) *Scope { - const n = 4 // initial scope capacity - return &Scope{outer, make(map[string]*Object, n)} -} - -// Lookup returns the object with the given name if it is -// found in scope s, otherwise it returns nil. Outer scopes -// are ignored. -// -func (s *Scope) Lookup(name string) *Object { - return s.Objects[name] -} - -// Insert attempts to insert a named object obj into the scope s. -// If the scope already contains an object alt with the same name, -// Insert leaves the scope unchanged and returns alt. Otherwise -// it inserts obj and returns nil." -// -func (s *Scope) Insert(obj *Object) (alt *Object) { - if alt = s.Objects[obj.Name]; alt == nil { - s.Objects[obj.Name] = obj - } - return -} - -// Debugging support -func (s *Scope) String() string { - var buf bytes.Buffer - fmt.Fprintf(&buf, "scope %p {", s) - if s != nil && len(s.Objects) > 0 { - fmt.Fprintln(&buf) - for _, obj := range s.Objects { - fmt.Fprintf(&buf, "\t%s %s\n", obj.Kind, obj.Name) - } - } - fmt.Fprintf(&buf, "}\n") - return buf.String() -} - -// ---------------------------------------------------------------------------- -// Objects - -// An Object describes a named language entity such as a package, -// constant, type, variable, function (incl. methods), or label. -// -// The Data fields contains object-specific data: -// -// Kind Data type Data value -// Pkg *types.Package package scope -// Con int iota for the respective declaration -// Con != nil constant value -// Typ *Scope (used as method scope during type checking - transient) -// -type Object struct { - Kind ObjKind - Name string // declared name - Decl interface{} // corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nil - Data interface{} // object-specific data; or nil - Type interface{} // place holder for type information; may be nil -} - -// NewObj creates a new object of a given kind and name. -func NewObj(kind ObjKind, name string) *Object { - return &Object{Kind: kind, Name: name} -} - -// Pos computes the source position of the declaration of an object name. -// The result may be an invalid position if it cannot be computed -// (obj.Decl may be nil or not correct). -func (obj *Object) Pos() token.Pos { - name := obj.Name - switch d := obj.Decl.(type) { - case *Field: - for _, n := range d.Names { - if n.Name == name { - return n.Pos() - } - } - case *ImportSpec: - if d.Name != nil && d.Name.Name == name { - return d.Name.Pos() - } - return d.Path.Pos() - case *ValueSpec: - for _, n := range d.Names { - if n.Name == name { - return n.Pos() - } - } - case *TypeSpec: - if d.Name.Name == name { - return d.Name.Pos() - } - case *FuncDecl: - if d.Name.Name == name { - return d.Name.Pos() - } - case *LabeledStmt: - if d.Label.Name == name { - return d.Label.Pos() - } - case *AssignStmt: - for _, x := range d.Lhs { - if ident, isIdent := x.(*Ident); isIdent && ident.Name == name { - return ident.Pos() - } - } - case *Scope: - // predeclared object - nothing to do for now - } - return token.NoPos -} - -// ObjKind describes what an object represents. -type ObjKind int - -// The list of possible Object kinds. -const ( - Bad ObjKind = iota // for error handling - Pkg // package - Con // constant - Typ // type - Var // variable - Fun // function or method - Lbl // label -) - -var objKindStrings = [...]string{ - Bad: "bad", - Pkg: "package", - Con: "const", - Typ: "type", - Var: "var", - Fun: "func", - Lbl: "label", -} - -func (kind ObjKind) String() string { return objKindStrings[kind] } diff --git a/gcc-4.8.1/libgo/go/go/ast/walk.go b/gcc-4.8.1/libgo/go/go/ast/walk.go deleted file mode 100644 index fef2503c3..000000000 --- a/gcc-4.8.1/libgo/go/go/ast/walk.go +++ /dev/null @@ -1,381 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ast - -import "fmt" - -// A Visitor's Visit method is invoked for each node encountered by Walk. -// 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 Node) (w Visitor) -} - -// Helper functions for common node lists. They may be empty. - -func walkIdentList(v Visitor, list []*Ident) { - for _, x := range list { - Walk(v, x) - } -} - -func walkExprList(v Visitor, list []Expr) { - for _, x := range list { - Walk(v, x) - } -} - -func walkStmtList(v Visitor, list []Stmt) { - for _, x := range list { - Walk(v, x) - } -} - -func walkDeclList(v Visitor, list []Decl) { - for _, x := range list { - Walk(v, x) - } -} - -// TODO(gri): Investigate if providing a closure to Walk leads to -// simpler use (and may help eliminate Inspect in turn). - -// Walk traverses an AST in depth-first order: It starts by calling -// v.Visit(node); node must not be nil. If the visitor w returned by -// v.Visit(node) is not nil, Walk is invoked recursively with visitor -// w for each of the non-nil children of node, followed by a call of -// w.Visit(nil). -// -func Walk(v Visitor, node Node) { - if v = v.Visit(node); v == nil { - return - } - - // walk children - // (the order of the cases matches the order - // of the corresponding node types in ast.go) - switch n := node.(type) { - // Comments and fields - case *Comment: - // nothing to do - - case *CommentGroup: - for _, c := range n.List { - Walk(v, c) - } - - case *Field: - if n.Doc != nil { - Walk(v, n.Doc) - } - walkIdentList(v, n.Names) - Walk(v, n.Type) - if n.Tag != nil { - Walk(v, n.Tag) - } - if n.Comment != nil { - Walk(v, n.Comment) - } - - case *FieldList: - for _, f := range n.List { - Walk(v, f) - } - - // Expressions - case *BadExpr, *Ident, *BasicLit: - // nothing to do - - case *Ellipsis: - if n.Elt != nil { - Walk(v, n.Elt) - } - - case *FuncLit: - Walk(v, n.Type) - Walk(v, n.Body) - - case *CompositeLit: - if n.Type != nil { - Walk(v, n.Type) - } - walkExprList(v, n.Elts) - - case *ParenExpr: - Walk(v, n.X) - - case *SelectorExpr: - Walk(v, n.X) - Walk(v, n.Sel) - - case *IndexExpr: - Walk(v, n.X) - Walk(v, n.Index) - - case *SliceExpr: - Walk(v, n.X) - if n.Low != nil { - Walk(v, n.Low) - } - if n.High != nil { - Walk(v, n.High) - } - - case *TypeAssertExpr: - Walk(v, n.X) - if n.Type != nil { - Walk(v, n.Type) - } - - case *CallExpr: - Walk(v, n.Fun) - walkExprList(v, n.Args) - - case *StarExpr: - Walk(v, n.X) - - case *UnaryExpr: - Walk(v, n.X) - - case *BinaryExpr: - Walk(v, n.X) - Walk(v, n.Y) - - case *KeyValueExpr: - Walk(v, n.Key) - Walk(v, n.Value) - - // Types - case *ArrayType: - if n.Len != nil { - Walk(v, n.Len) - } - Walk(v, n.Elt) - - case *StructType: - Walk(v, n.Fields) - - case *FuncType: - if n.Params != nil { - Walk(v, n.Params) - } - if n.Results != nil { - Walk(v, n.Results) - } - - case *InterfaceType: - Walk(v, n.Methods) - - case *MapType: - Walk(v, n.Key) - Walk(v, n.Value) - - case *ChanType: - Walk(v, n.Value) - - // Statements - case *BadStmt: - // nothing to do - - case *DeclStmt: - Walk(v, n.Decl) - - case *EmptyStmt: - // nothing to do - - case *LabeledStmt: - Walk(v, n.Label) - Walk(v, n.Stmt) - - case *ExprStmt: - Walk(v, n.X) - - case *SendStmt: - Walk(v, n.Chan) - Walk(v, n.Value) - - case *IncDecStmt: - Walk(v, n.X) - - case *AssignStmt: - walkExprList(v, n.Lhs) - walkExprList(v, n.Rhs) - - case *GoStmt: - Walk(v, n.Call) - - case *DeferStmt: - Walk(v, n.Call) - - case *ReturnStmt: - walkExprList(v, n.Results) - - case *BranchStmt: - if n.Label != nil { - Walk(v, n.Label) - } - - case *BlockStmt: - walkStmtList(v, n.List) - - case *IfStmt: - if n.Init != nil { - Walk(v, n.Init) - } - Walk(v, n.Cond) - Walk(v, n.Body) - if n.Else != nil { - Walk(v, n.Else) - } - - case *CaseClause: - walkExprList(v, n.List) - walkStmtList(v, n.Body) - - case *SwitchStmt: - if n.Init != nil { - Walk(v, n.Init) - } - if n.Tag != nil { - Walk(v, n.Tag) - } - Walk(v, n.Body) - - case *TypeSwitchStmt: - if n.Init != nil { - Walk(v, n.Init) - } - Walk(v, n.Assign) - Walk(v, n.Body) - - case *CommClause: - if n.Comm != nil { - Walk(v, n.Comm) - } - walkStmtList(v, n.Body) - - case *SelectStmt: - Walk(v, n.Body) - - case *ForStmt: - if n.Init != nil { - Walk(v, n.Init) - } - if n.Cond != nil { - Walk(v, n.Cond) - } - if n.Post != nil { - Walk(v, n.Post) - } - Walk(v, n.Body) - - case *RangeStmt: - Walk(v, n.Key) - if n.Value != nil { - Walk(v, n.Value) - } - Walk(v, n.X) - Walk(v, n.Body) - - // Declarations - case *ImportSpec: - if n.Doc != nil { - Walk(v, n.Doc) - } - if n.Name != nil { - Walk(v, n.Name) - } - Walk(v, n.Path) - if n.Comment != nil { - Walk(v, n.Comment) - } - - case *ValueSpec: - if n.Doc != nil { - Walk(v, n.Doc) - } - walkIdentList(v, n.Names) - if n.Type != nil { - Walk(v, n.Type) - } - walkExprList(v, n.Values) - if n.Comment != nil { - Walk(v, n.Comment) - } - - case *TypeSpec: - if n.Doc != nil { - Walk(v, n.Doc) - } - Walk(v, n.Name) - Walk(v, n.Type) - if n.Comment != nil { - Walk(v, n.Comment) - } - - case *BadDecl: - // nothing to do - - case *GenDecl: - if n.Doc != nil { - Walk(v, n.Doc) - } - for _, s := range n.Specs { - Walk(v, s) - } - - case *FuncDecl: - if n.Doc != nil { - Walk(v, n.Doc) - } - if n.Recv != nil { - Walk(v, n.Recv) - } - Walk(v, n.Name) - Walk(v, n.Type) - if n.Body != nil { - Walk(v, n.Body) - } - - // Files and packages - case *File: - if n.Doc != nil { - Walk(v, n.Doc) - } - Walk(v, n.Name) - walkDeclList(v, n.Decls) - // don't walk n.Comments - they have been - // visited already through the individual - // nodes - - case *Package: - for _, f := range n.Files { - Walk(v, f) - } - - default: - fmt.Printf("ast.Walk: unexpected node type %T", n) - panic("ast.Walk") - } - - v.Visit(nil) -} - -type inspector func(Node) bool - -func (f inspector) Visit(node Node) Visitor { - if f(node) { - return f - } - return nil -} - -// Inspect traverses an AST in depth-first order: It starts by calling -// f(node); node must not be nil. If f returns true, Inspect invokes f -// for all the non-nil children of node, recursively. -// -func Inspect(node Node, f func(Node) bool) { - Walk(inspector(f), node) -} diff --git a/gcc-4.8.1/libgo/go/go/build/build.go b/gcc-4.8.1/libgo/go/go/build/build.go deleted file mode 100644 index e2a47a556..000000000 --- a/gcc-4.8.1/libgo/go/go/build/build.go +++ /dev/null @@ -1,1043 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package build - -import ( - "bytes" - "errors" - "fmt" - "go/ast" - "go/doc" - "go/parser" - "go/token" - "io" - "io/ioutil" - "log" - "os" - pathpkg "path" - "path/filepath" - "runtime" - "sort" - "strconv" - "strings" - "unicode" -) - -// A Context specifies the supporting context for a build. -type Context struct { - GOARCH string // target architecture - GOOS string // target operating system - GOROOT string // Go root - GOPATH string // Go path - CgoEnabled bool // whether cgo can be used - BuildTags []string // additional tags to recognize in +build lines - InstallTag string // package install directory suffix - UseAllFiles bool // use files regardless of +build lines, file names - Compiler string // compiler to assume when computing target paths - - // By default, Import uses the operating system's file system calls - // to read directories and files. To read from other sources, - // callers can set the following functions. They all have default - // behaviors that use the local file system, so clients need only set - // the functions whose behaviors they wish to change. - - // JoinPath joins the sequence of path fragments into a single path. - // If JoinPath is nil, Import uses filepath.Join. - JoinPath func(elem ...string) string - - // SplitPathList splits the path list into a slice of individual paths. - // If SplitPathList is nil, Import uses filepath.SplitList. - SplitPathList func(list string) []string - - // IsAbsPath reports whether path is an absolute path. - // If IsAbsPath is nil, Import uses filepath.IsAbs. - IsAbsPath func(path string) bool - - // IsDir reports whether the path names a directory. - // If IsDir is nil, Import calls os.Stat and uses the result's IsDir method. - IsDir func(path string) bool - - // HasSubdir reports whether dir is a subdirectory of - // (perhaps multiple levels below) root. - // If so, HasSubdir sets rel to a slash-separated path that - // can be joined to root to produce a path equivalent to dir. - // If HasSubdir is nil, Import uses an implementation built on - // filepath.EvalSymlinks. - HasSubdir func(root, dir string) (rel string, ok bool) - - // ReadDir returns a slice of os.FileInfo, sorted by Name, - // describing the content of the named directory. - // If ReadDir is nil, Import uses ioutil.ReadDir. - ReadDir func(dir string) (fi []os.FileInfo, err error) - - // OpenFile opens a file (not a directory) for reading. - // If OpenFile is nil, Import uses os.Open. - OpenFile func(path string) (r io.ReadCloser, err error) -} - -// joinPath calls ctxt.JoinPath (if not nil) or else filepath.Join. -func (ctxt *Context) joinPath(elem ...string) string { - if f := ctxt.JoinPath; f != nil { - return f(elem...) - } - return filepath.Join(elem...) -} - -// splitPathList calls ctxt.SplitPathList (if not nil) or else filepath.SplitList. -func (ctxt *Context) splitPathList(s string) []string { - if f := ctxt.SplitPathList; f != nil { - return f(s) - } - return filepath.SplitList(s) -} - -// isAbsPath calls ctxt.IsAbsSPath (if not nil) or else filepath.IsAbs. -func (ctxt *Context) isAbsPath(path string) bool { - if f := ctxt.IsAbsPath; f != nil { - return f(path) - } - return filepath.IsAbs(path) -} - -// isDir calls ctxt.IsDir (if not nil) or else uses os.Stat. -func (ctxt *Context) isDir(path string) bool { - if f := ctxt.IsDir; f != nil { - return f(path) - } - fi, err := os.Stat(path) - return err == nil && fi.IsDir() -} - -// hasSubdir calls ctxt.HasSubdir (if not nil) or else uses -// the local file system to answer the question. -func (ctxt *Context) hasSubdir(root, dir string) (rel string, ok bool) { - if f := ctxt.HasSubdir; f != nil { - return f(root, dir) - } - - if p, err := filepath.EvalSymlinks(root); err == nil { - root = p - } - if p, err := filepath.EvalSymlinks(dir); err == nil { - dir = p - } - const sep = string(filepath.Separator) - root = filepath.Clean(root) - if !strings.HasSuffix(root, sep) { - root += sep - } - dir = filepath.Clean(dir) - if !strings.HasPrefix(dir, root) { - return "", false - } - return filepath.ToSlash(dir[len(root):]), true -} - -// readDir calls ctxt.ReadDir (if not nil) or else ioutil.ReadDir. -func (ctxt *Context) readDir(path string) ([]os.FileInfo, error) { - if f := ctxt.ReadDir; f != nil { - return f(path) - } - return ioutil.ReadDir(path) -} - -// openFile calls ctxt.OpenFile (if not nil) or else os.Open. -func (ctxt *Context) openFile(path string) (io.ReadCloser, error) { - if fn := ctxt.OpenFile; fn != nil { - return fn(path) - } - - f, err := os.Open(path) - if err != nil { - return nil, err // nil interface - } - return f, nil -} - -// isFile determines whether path is a file by trying to open it. -// It reuses openFile instead of adding another function to the -// list in Context. -func (ctxt *Context) isFile(path string) bool { - f, err := ctxt.openFile(path) - if err != nil { - return false - } - f.Close() - return true -} - -// gopath returns the list of Go path directories. -func (ctxt *Context) gopath() []string { - var all []string - for _, p := range ctxt.splitPathList(ctxt.GOPATH) { - if p == "" || p == ctxt.GOROOT { - // Empty paths are uninteresting. - // If the path is the GOROOT, ignore it. - // People sometimes set GOPATH=$GOROOT, which is useless - // but would cause us to find packages with import paths - // like "pkg/math". - // Do not get confused by this common mistake. - continue - } - all = append(all, p) - } - return all -} - -// SrcDirs returns a list of package source root directories. -// It draws from the current Go root and Go path but omits directories -// that do not exist. -func (ctxt *Context) SrcDirs() []string { - var all []string - if ctxt.GOROOT != "" { - dir := ctxt.joinPath(ctxt.GOROOT, "src", "pkg") - if ctxt.isDir(dir) { - all = append(all, dir) - } - } - for _, p := range ctxt.gopath() { - dir := ctxt.joinPath(p, "src") - if ctxt.isDir(dir) { - all = append(all, dir) - } - } - return all -} - -// Default is the default Context for builds. -// It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variables -// if set, or else the compiled code's GOARCH, GOOS, and GOROOT. -var Default Context = defaultContext() - -var cgoEnabled = map[string]bool{ - "darwin/386": true, - "darwin/amd64": true, - "freebsd/386": true, - "freebsd/amd64": true, - "linux/386": true, - "linux/amd64": true, - "linux/arm": true, - "netbsd/386": true, - "netbsd/amd64": true, - "openbsd/386": true, - "openbsd/amd64": true, - "windows/386": true, - "windows/amd64": true, -} - -func defaultContext() Context { - var c Context - - c.GOARCH = envOr("GOARCH", runtime.GOARCH) - c.GOOS = envOr("GOOS", runtime.GOOS) - c.GOROOT = runtime.GOROOT() - c.GOPATH = envOr("GOPATH", "") - c.Compiler = runtime.Compiler - - switch os.Getenv("CGO_ENABLED") { - case "1": - c.CgoEnabled = true - case "0": - c.CgoEnabled = false - default: - c.CgoEnabled = cgoEnabled[c.GOOS+"/"+c.GOARCH] - } - - return c -} - -func envOr(name, def string) string { - s := os.Getenv(name) - if s == "" { - return def - } - return s -} - -// An ImportMode controls the behavior of the Import method. -type ImportMode uint - -const ( - // If FindOnly is set, Import stops after locating the directory - // that should contain the sources for a package. It does not - // read any files in the directory. - FindOnly ImportMode = 1 << iota - - // If AllowBinary is set, Import can be satisfied by a compiled - // package object without corresponding sources. - AllowBinary -) - -// A Package describes the Go package found in a directory. -type Package struct { - Dir string // directory containing package sources - Name string // package name - Doc string // documentation synopsis - ImportPath string // import path of package ("" if unknown) - Root string // root of Go tree where this package lives - SrcRoot string // package source root directory ("" if unknown) - PkgRoot string // package install root directory ("" if unknown) - BinDir string // command install directory ("" if unknown) - Goroot bool // package found in Go root - PkgObj string // installed .a file - - // Source files - GoFiles []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles) - CgoFiles []string // .go source files that import "C" - CFiles []string // .c source files - HFiles []string // .h source files - SFiles []string // .s source files - SysoFiles []string // .syso system object files to add to archive - SwigFiles []string // .swig files - SwigCXXFiles []string // .swigcxx files - - // Cgo directives - CgoPkgConfig []string // Cgo pkg-config directives - CgoCFLAGS []string // Cgo CFLAGS directives - CgoLDFLAGS []string // Cgo LDFLAGS directives - - // Dependency information - Imports []string // imports from GoFiles, CgoFiles - ImportPos map[string][]token.Position // line information for Imports - - // Test information - TestGoFiles []string // _test.go files in package - TestImports []string // imports from TestGoFiles - TestImportPos map[string][]token.Position // line information for TestImports - XTestGoFiles []string // _test.go files outside package - XTestImports []string // imports from XTestGoFiles - XTestImportPos map[string][]token.Position // line information for XTestImports -} - -// IsCommand reports whether the package is considered a -// command to be installed (not just a library). -// Packages named "main" are treated as commands. -func (p *Package) IsCommand() bool { - return p.Name == "main" -} - -// ImportDir is like Import but processes the Go package found in -// the named directory. -func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error) { - return ctxt.Import(".", dir, mode) -} - -// NoGoError is the error used by Import to describe a directory -// containing no Go source files. -type NoGoError struct { - Dir string -} - -func (e *NoGoError) Error() string { - return "no Go source files in " + e.Dir -} - -// Import returns details about the Go package named by the import path, -// interpreting local import paths relative to the srcDir directory. -// If the path is a local import path naming a package that can be imported -// using a standard import path, the returned package will set p.ImportPath -// to that path. -// -// In the directory containing the package, .go, .c, .h, and .s files are -// considered part of the package except for: -// -// - .go files in package documentation -// - files starting with _ or . (likely editor temporary files) -// - files with build constraints not satisfied by the context -// -// If an error occurs, Import returns a non-nil error and a non-nil -// *Package containing partial information. -// -func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error) { - p := &Package{ - ImportPath: path, - } - if path == "" { - return p, fmt.Errorf("import %q: invalid import path", path) - } - - var pkga string - var pkgerr error - switch ctxt.Compiler { - case "gccgo": - dir, elem := pathpkg.Split(p.ImportPath) - pkga = "pkg/gccgo/" + dir + "lib" + elem + ".a" - case "gc": - tag := "" - if ctxt.InstallTag != "" { - tag = "_" + ctxt.InstallTag - } - pkga = "pkg/" + ctxt.GOOS + "_" + ctxt.GOARCH + tag + "/" + p.ImportPath + ".a" - default: - // Save error for end of function. - pkgerr = fmt.Errorf("import %q: unknown compiler %q", path, ctxt.Compiler) - } - - binaryOnly := false - if IsLocalImport(path) { - pkga = "" // local imports have no installed path - if srcDir == "" { - return p, fmt.Errorf("import %q: import relative to unknown directory", path) - } - if !ctxt.isAbsPath(path) { - p.Dir = ctxt.joinPath(srcDir, path) - } - // Determine canonical import path, if any. - if ctxt.GOROOT != "" { - root := ctxt.joinPath(ctxt.GOROOT, "src", "pkg") - if sub, ok := ctxt.hasSubdir(root, p.Dir); ok { - p.Goroot = true - p.ImportPath = sub - p.Root = ctxt.GOROOT - goto Found - } - } - all := ctxt.gopath() - for i, root := range all { - rootsrc := ctxt.joinPath(root, "src") - if sub, ok := ctxt.hasSubdir(rootsrc, p.Dir); ok { - // We found a potential import path for dir, - // but check that using it wouldn't find something - // else first. - if ctxt.GOROOT != "" { - if dir := ctxt.joinPath(ctxt.GOROOT, "src", "pkg", sub); ctxt.isDir(dir) { - goto Found - } - } - for _, earlyRoot := range all[:i] { - if dir := ctxt.joinPath(earlyRoot, "src", sub); ctxt.isDir(dir) { - goto Found - } - } - - // sub would not name some other directory instead of this one. - // Record it. - p.ImportPath = sub - p.Root = root - goto Found - } - } - // It's okay that we didn't find a root containing dir. - // Keep going with the information we have. - } else { - if strings.HasPrefix(path, "/") { - return p, fmt.Errorf("import %q: cannot import absolute path", path) - } - - // tried records the location of unsucsessful package lookups - var tried struct { - goroot string - gopath []string - } - - // Determine directory from import path. - if ctxt.GOROOT != "" { - dir := ctxt.joinPath(ctxt.GOROOT, "src", "pkg", path) - isDir := ctxt.isDir(dir) - binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga)) - if isDir || binaryOnly { - p.Dir = dir - p.Goroot = true - p.Root = ctxt.GOROOT - goto Found - } - tried.goroot = dir - } - for _, root := range ctxt.gopath() { - dir := ctxt.joinPath(root, "src", path) - isDir := ctxt.isDir(dir) - binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(root, pkga)) - if isDir || binaryOnly { - p.Dir = dir - p.Root = root - goto Found - } - tried.gopath = append(tried.gopath, dir) - } - - // package was not found - var paths []string - if tried.goroot != "" { - paths = append(paths, fmt.Sprintf("\t%s (from $GOROOT)", tried.goroot)) - } else { - paths = append(paths, "\t($GOROOT not set)") - } - var i int - var format = "\t%s (from $GOPATH)" - for ; i < len(tried.gopath); i++ { - if i > 0 { - format = "\t%s" - } - paths = append(paths, fmt.Sprintf(format, tried.gopath[i])) - } - if i == 0 { - paths = append(paths, "\t($GOPATH not set)") - } - return p, fmt.Errorf("cannot find package %q in any of:\n%s", path, strings.Join(paths, "\n")) - } - -Found: - if p.Root != "" { - if p.Goroot { - p.SrcRoot = ctxt.joinPath(p.Root, "src", "pkg") - } else { - p.SrcRoot = ctxt.joinPath(p.Root, "src") - } - p.PkgRoot = ctxt.joinPath(p.Root, "pkg") - p.BinDir = ctxt.joinPath(p.Root, "bin") - if pkga != "" { - p.PkgObj = ctxt.joinPath(p.Root, pkga) - } - } - - if mode&FindOnly != 0 { - return p, pkgerr - } - if binaryOnly && (mode&AllowBinary) != 0 { - return p, pkgerr - } - - dirs, err := ctxt.readDir(p.Dir) - if err != nil { - return p, err - } - - var Sfiles []string // files with ".S" (capital S) - var firstFile string - imported := make(map[string][]token.Position) - testImported := make(map[string][]token.Position) - xTestImported := make(map[string][]token.Position) - fset := token.NewFileSet() - for _, d := range dirs { - if d.IsDir() { - continue - } - name := d.Name() - if strings.HasPrefix(name, "_") || - strings.HasPrefix(name, ".") { - continue - } - if !ctxt.UseAllFiles && !ctxt.goodOSArchFile(name) { - continue - } - - i := strings.LastIndex(name, ".") - if i < 0 { - i = len(name) - } - ext := name[i:] - switch ext { - case ".go", ".c", ".s", ".h", ".S", ".swig", ".swigcxx": - // tentatively okay - read to make sure - case ".syso": - // binary objects to add to package archive - // Likely of the form foo_windows.syso, but - // the name was vetted above with goodOSArchFile. - p.SysoFiles = append(p.SysoFiles, name) - continue - default: - // skip - continue - } - - filename := ctxt.joinPath(p.Dir, name) - f, err := ctxt.openFile(filename) - if err != nil { - return p, err - } - - var data []byte - if strings.HasSuffix(filename, ".go") { - data, err = readImports(f, false) - } else { - data, err = readComments(f) - } - f.Close() - if err != nil { - return p, fmt.Errorf("read %s: %v", filename, err) - } - - // Look for +build comments to accept or reject the file. - if !ctxt.UseAllFiles && !ctxt.shouldBuild(data) { - continue - } - - // Going to save the file. For non-Go files, can stop here. - switch ext { - case ".c": - p.CFiles = append(p.CFiles, name) - continue - case ".h": - p.HFiles = append(p.HFiles, name) - continue - case ".s": - p.SFiles = append(p.SFiles, name) - continue - case ".S": - Sfiles = append(Sfiles, name) - continue - case ".swig": - p.SwigFiles = append(p.SwigFiles, name) - continue - case ".swigcxx": - p.SwigCXXFiles = append(p.SwigCXXFiles, name) - continue - } - - pf, err := parser.ParseFile(fset, filename, data, parser.ImportsOnly|parser.ParseComments) - if err != nil { - return p, err - } - - pkg := pf.Name.Name - if pkg == "documentation" { - continue - } - - isTest := strings.HasSuffix(name, "_test.go") - isXTest := false - if isTest && strings.HasSuffix(pkg, "_test") { - isXTest = true - pkg = pkg[:len(pkg)-len("_test")] - } - - if p.Name == "" { - p.Name = pkg - firstFile = name - } else if pkg != p.Name { - return p, fmt.Errorf("found packages %s (%s) and %s (%s) in %s", p.Name, firstFile, pkg, name, p.Dir) - } - if pf.Doc != nil && p.Doc == "" { - p.Doc = doc.Synopsis(pf.Doc.Text()) - } - - // Record imports and information about cgo. - isCgo := false - for _, decl := range pf.Decls { - d, ok := decl.(*ast.GenDecl) - if !ok { - continue - } - for _, dspec := range d.Specs { - spec, ok := dspec.(*ast.ImportSpec) - if !ok { - continue - } - quoted := spec.Path.Value - path, err := strconv.Unquote(quoted) - if err != nil { - log.Panicf("%s: parser returned invalid quoted string: <%s>", filename, quoted) - } - if isXTest { - xTestImported[path] = append(xTestImported[path], fset.Position(spec.Pos())) - } else if isTest { - testImported[path] = append(testImported[path], fset.Position(spec.Pos())) - } else { - imported[path] = append(imported[path], fset.Position(spec.Pos())) - } - if path == "C" { - if isTest { - return p, fmt.Errorf("use of cgo in test %s not supported", filename) - } - cg := spec.Doc - if cg == nil && len(d.Specs) == 1 { - cg = d.Doc - } - if cg != nil { - if err := ctxt.saveCgo(filename, p, cg); err != nil { - return p, err - } - } - isCgo = true - } - } - } - if isCgo { - if ctxt.CgoEnabled { - p.CgoFiles = append(p.CgoFiles, name) - } - } else if isXTest { - p.XTestGoFiles = append(p.XTestGoFiles, name) - } else if isTest { - p.TestGoFiles = append(p.TestGoFiles, name) - } else { - p.GoFiles = append(p.GoFiles, name) - } - } - if p.Name == "" { - return p, &NoGoError{p.Dir} - } - - p.Imports, p.ImportPos = cleanImports(imported) - p.TestImports, p.TestImportPos = cleanImports(testImported) - p.XTestImports, p.XTestImportPos = cleanImports(xTestImported) - - // add the .S files only if we are using cgo - // (which means gcc will compile them). - // The standard assemblers expect .s files. - if len(p.CgoFiles) > 0 { - p.SFiles = append(p.SFiles, Sfiles...) - sort.Strings(p.SFiles) - } - - return p, pkgerr -} - -func cleanImports(m map[string][]token.Position) ([]string, map[string][]token.Position) { - all := make([]string, 0, len(m)) - for path := range m { - all = append(all, path) - } - sort.Strings(all) - return all, m -} - -// Import is shorthand for Default.Import. -func Import(path, srcDir string, mode ImportMode) (*Package, error) { - return Default.Import(path, srcDir, mode) -} - -// ImportDir is shorthand for Default.ImportDir. -func ImportDir(dir string, mode ImportMode) (*Package, error) { - return Default.ImportDir(dir, mode) -} - -var slashslash = []byte("//") - -// shouldBuild reports whether it is okay to use this file, -// The rule is that in the file's leading run of // comments -// and blank lines, which must be followed by a blank line -// (to avoid including a Go package clause doc comment), -// lines beginning with '// +build' are taken as build directives. -// -// The file is accepted only if each such line lists something -// matching the file. For example: -// -// // +build windows linux -// -// marks the file as applicable only on Windows and Linux. -// -func (ctxt *Context) shouldBuild(content []byte) bool { - // Pass 1. Identify leading run of // comments and blank lines, - // which must be followed by a blank line. - end := 0 - p := content - for len(p) > 0 { - line := p - if i := bytes.IndexByte(line, '\n'); i >= 0 { - line, p = line[:i], p[i+1:] - } else { - p = p[len(p):] - } - line = bytes.TrimSpace(line) - if len(line) == 0 { // Blank line - end = len(content) - len(p) - continue - } - if !bytes.HasPrefix(line, slashslash) { // Not comment line - break - } - } - content = content[:end] - - // Pass 2. Process each line in the run. - p = content - for len(p) > 0 { - line := p - if i := bytes.IndexByte(line, '\n'); i >= 0 { - line, p = line[:i], p[i+1:] - } else { - p = p[len(p):] - } - line = bytes.TrimSpace(line) - if bytes.HasPrefix(line, slashslash) { - line = bytes.TrimSpace(line[len(slashslash):]) - if len(line) > 0 && line[0] == '+' { - // Looks like a comment +line. - f := strings.Fields(string(line)) - if f[0] == "+build" { - ok := false - for _, tok := range f[1:] { - if ctxt.match(tok) { - ok = true - break - } - } - if !ok { - return false // this one doesn't match - } - } - } - } - } - return true // everything matches -} - -// saveCgo saves the information from the #cgo lines in the import "C" comment. -// These lines set CFLAGS and LDFLAGS and pkg-config directives that affect -// the way cgo's C code is built. -// -// TODO(rsc): This duplicates code in cgo. -// Once the dust settles, remove this code from cgo. -func (ctxt *Context) saveCgo(filename string, di *Package, cg *ast.CommentGroup) error { - text := cg.Text() - for _, line := range strings.Split(text, "\n") { - orig := line - - // Line is - // #cgo [GOOS/GOARCH...] LDFLAGS: stuff - // - line = strings.TrimSpace(line) - if len(line) < 5 || line[:4] != "#cgo" || (line[4] != ' ' && line[4] != '\t') { - continue - } - - // Split at colon. - line = strings.TrimSpace(line[4:]) - i := strings.Index(line, ":") - if i < 0 { - return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig) - } - line, argstr := line[:i], line[i+1:] - - // Parse GOOS/GOARCH stuff. - f := strings.Fields(line) - if len(f) < 1 { - return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig) - } - - cond, verb := f[:len(f)-1], f[len(f)-1] - if len(cond) > 0 { - ok := false - for _, c := range cond { - if ctxt.match(c) { - ok = true - break - } - } - if !ok { - continue - } - } - - args, err := splitQuoted(argstr) - if err != nil { - return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig) - } - for _, arg := range args { - if !safeName(arg) { - return fmt.Errorf("%s: malformed #cgo argument: %s", filename, arg) - } - } - - switch verb { - case "CFLAGS": - di.CgoCFLAGS = append(di.CgoCFLAGS, args...) - case "LDFLAGS": - di.CgoLDFLAGS = append(di.CgoLDFLAGS, args...) - case "pkg-config": - di.CgoPkgConfig = append(di.CgoPkgConfig, args...) - default: - return fmt.Errorf("%s: invalid #cgo verb: %s", filename, orig) - } - } - return nil -} - -var safeBytes = []byte("+-.,/0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz:") - -func safeName(s string) bool { - if s == "" { - return false - } - for i := 0; i < len(s); i++ { - if c := s[i]; c < 0x80 && bytes.IndexByte(safeBytes, c) < 0 { - return false - } - } - return true -} - -// splitQuoted splits the string s around each instance of one or more consecutive -// white space characters while taking into account quotes and escaping, and -// returns an array of substrings of s or an empty list if s contains only white space. -// Single quotes and double quotes are recognized to prevent splitting within the -// quoted region, and are removed from the resulting substrings. If a quote in s -// isn't closed err will be set and r will have the unclosed argument as the -// last element. The backslash is used for escaping. -// -// For example, the following string: -// -// a b:"c d" 'e''f' "g\"" -// -// Would be parsed as: -// -// []string{"a", "b:c d", "ef", `g"`} -// -func splitQuoted(s string) (r []string, err error) { - var args []string - arg := make([]rune, len(s)) - escaped := false - quoted := false - quote := '\x00' - i := 0 - for _, rune := range s { - switch { - case escaped: - escaped = false - case rune == '\\': - escaped = true - continue - case quote != '\x00': - if rune == quote { - quote = '\x00' - continue - } - case rune == '"' || rune == '\'': - quoted = true - quote = rune - continue - case unicode.IsSpace(rune): - if quoted || i > 0 { - quoted = false - args = append(args, string(arg[:i])) - i = 0 - } - continue - } - arg[i] = rune - i++ - } - if quoted || i > 0 { - args = append(args, string(arg[:i])) - } - if quote != 0 { - err = errors.New("unclosed quote") - } else if escaped { - err = errors.New("unfinished escaping") - } - return args, err -} - -// match returns true if the name is one of: -// -// $GOOS -// $GOARCH -// cgo (if cgo is enabled) -// !cgo (if cgo is disabled) -// ctxt.Compiler -// !ctxt.Compiler -// tag (if tag is listed in ctxt.BuildTags) -// !tag (if tag is not listed in ctxt.BuildTags) -// a comma-separated list of any of these -// -func (ctxt *Context) match(name string) bool { - if name == "" { - return false - } - if i := strings.Index(name, ","); i >= 0 { - // comma-separated list - return ctxt.match(name[:i]) && ctxt.match(name[i+1:]) - } - if strings.HasPrefix(name, "!!") { // bad syntax, reject always - return false - } - if strings.HasPrefix(name, "!") { // negation - return len(name) > 1 && !ctxt.match(name[1:]) - } - - // Tags must be letters, digits, underscores. - // Unlike in Go identifiers, all digits are fine (e.g., "386"). - for _, c := range name { - if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' { - return false - } - } - - // special tags - if ctxt.CgoEnabled && name == "cgo" { - return true - } - if name == ctxt.GOOS || name == ctxt.GOARCH || name == ctxt.Compiler { - return true - } - - // other tags - for _, tag := range ctxt.BuildTags { - if tag == name { - return true - } - } - - return false -} - -// goodOSArchFile returns false if the name contains a $GOOS or $GOARCH -// suffix which does not match the current system. -// The recognized name formats are: -// -// name_$(GOOS).* -// name_$(GOARCH).* -// name_$(GOOS)_$(GOARCH).* -// name_$(GOOS)_test.* -// name_$(GOARCH)_test.* -// name_$(GOOS)_$(GOARCH)_test.* -// -func (ctxt *Context) goodOSArchFile(name string) bool { - if dot := strings.Index(name, "."); dot != -1 { - name = name[:dot] - } - l := strings.Split(name, "_") - if n := len(l); n > 0 && l[n-1] == "test" { - l = l[:n-1] - } - n := len(l) - if n >= 2 && knownOS[l[n-2]] && knownArch[l[n-1]] { - return l[n-2] == ctxt.GOOS && l[n-1] == ctxt.GOARCH - } - if n >= 1 && knownOS[l[n-1]] { - return l[n-1] == ctxt.GOOS - } - if n >= 1 && knownArch[l[n-1]] { - return l[n-1] == ctxt.GOARCH - } - return true -} - -var knownOS = make(map[string]bool) -var knownArch = make(map[string]bool) - -func init() { - for _, v := range strings.Fields(goosList) { - knownOS[v] = true - } - for _, v := range strings.Fields(goarchList) { - knownArch[v] = true - } -} - -// ToolDir is the directory containing build tools. -var ToolDir = filepath.Join(runtime.GOROOT(), "pkg/tool/"+runtime.GOOS+"_"+runtime.GOARCH) - -// IsLocalImport reports whether the import path is -// a local import path, like ".", "..", "./foo", or "../foo". -func IsLocalImport(path string) bool { - return path == "." || path == ".." || - strings.HasPrefix(path, "./") || strings.HasPrefix(path, "../") -} - -// ArchChar returns the architecture character for the given goarch. -// For example, ArchChar("amd64") returns "6". -func ArchChar(goarch string) (string, error) { - switch goarch { - case "386": - return "8", nil - case "amd64": - return "6", nil - case "arm": - return "5", nil - } - return "", errors.New("unsupported GOARCH " + goarch) -} diff --git a/gcc-4.8.1/libgo/go/go/build/build_test.go b/gcc-4.8.1/libgo/go/go/build/build_test.go deleted file mode 100644 index d8cf98840..000000000 --- a/gcc-4.8.1/libgo/go/go/build/build_test.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package build - -import ( - "os" - "path/filepath" - "runtime" - "testing" -) - -func TestMatch(t *testing.T) { - ctxt := Default - what := "default" - match := func(tag string) { - if !ctxt.match(tag) { - t.Errorf("%s context should match %s, does not", what, tag) - } - } - nomatch := func(tag string) { - if ctxt.match(tag) { - t.Errorf("%s context should NOT match %s, does", what, tag) - } - } - - match(runtime.GOOS + "," + runtime.GOARCH) - match(runtime.GOOS + "," + runtime.GOARCH + ",!foo") - nomatch(runtime.GOOS + "," + runtime.GOARCH + ",foo") - - what = "modified" - ctxt.BuildTags = []string{"foo"} - match(runtime.GOOS + "," + runtime.GOARCH) - match(runtime.GOOS + "," + runtime.GOARCH + ",foo") - nomatch(runtime.GOOS + "," + runtime.GOARCH + ",!foo") - match(runtime.GOOS + "," + runtime.GOARCH + ",!bar") - nomatch(runtime.GOOS + "," + runtime.GOARCH + ",bar") - nomatch("!") -} - -func TestDotSlashImport(t *testing.T) { - p, err := ImportDir("testdata/other", 0) - if err != nil { - t.Fatal(err) - } - if len(p.Imports) != 1 || p.Imports[0] != "./file" { - t.Fatalf("testdata/other: Imports=%v, want [./file]", p.Imports) - } - - p1, err := Import("./file", "testdata/other", 0) - if err != nil { - t.Fatal(err) - } - if p1.Name != "file" { - t.Fatalf("./file: Name=%q, want %q", p1.Name, "file") - } - dir := filepath.Clean("testdata/other/file") // Clean to use \ on Windows - if p1.Dir != dir { - t.Fatalf("./file: Dir=%q, want %q", p1.Name, dir) - } -} - -func TestEmptyImport(t *testing.T) { - p, err := Import("", Default.GOROOT, FindOnly) - if err == nil { - t.Fatal(`Import("") returned nil error.`) - } - if p == nil { - t.Fatal(`Import("") returned nil package.`) - } - if p.ImportPath != "" { - t.Fatalf("ImportPath=%q, want %q.", p.ImportPath, "") - } -} - -func TestLocalDirectory(t *testing.T) { - cwd, err := os.Getwd() - if err != nil { - t.Fatal(err) - } - - p, err := ImportDir(cwd, 0) - if err != nil { - t.Fatal(err) - } - if p.ImportPath != "go/build" { - t.Fatalf("ImportPath=%q, want %q", p.ImportPath, "go/build") - } -} - -func TestShouldBuild(t *testing.T) { - const file1 = "// +build tag1\n\n" + - "package main\n" - - const file2 = "// +build cgo\n\n" + - "// This package implements parsing of tags like\n" + - "// +build tag1\n" + - "package build" - - const file3 = "// Copyright The Go Authors.\n\n" + - "package build\n\n" + - "// shouldBuild checks tags given by lines of the form\n" + - "// +build tag\n" + - "func shouldBuild(content []byte)\n" - - ctx := &Context{BuildTags: []string{"tag1"}} - if !ctx.shouldBuild([]byte(file1)) { - t.Errorf("should not build file1, expected the contrary") - } - if ctx.shouldBuild([]byte(file2)) { - t.Errorf("should build file2, expected the contrary") - } - - ctx = &Context{BuildTags: nil} - if !ctx.shouldBuild([]byte(file3)) { - t.Errorf("should not build file3, expected the contrary") - } -} diff --git a/gcc-4.8.1/libgo/go/go/build/deps_test.go b/gcc-4.8.1/libgo/go/go/build/deps_test.go deleted file mode 100644 index e303b7ae2..000000000 --- a/gcc-4.8.1/libgo/go/go/build/deps_test.go +++ /dev/null @@ -1,431 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file exercises the import parser but also checks that -// some low-level packages do not have new dependencies added. - -package build_test - -import ( - "go/build" - "sort" - "testing" -) - -// pkgDeps defines the expected dependencies between packages in -// the Go source tree. It is a statement of policy. -// Changes should not be made to this map without prior discussion. -// -// The map contains two kinds of entries: -// 1) Lower-case keys are standard import paths and list the -// allowed imports in that package. -// 2) Upper-case keys define aliases for package sets, which can then -// be used as dependencies by other rules. -// -// DO NOT CHANGE THIS DATA TO FIX BUILDS. -// -var pkgDeps = map[string][]string{ - // L0 is the lowest level, core, nearly unavoidable packages. - "errors": {}, - "io": {"errors", "sync"}, - "runtime": {"unsafe"}, - "sync": {"sync/atomic", "unsafe"}, - "sync/atomic": {"unsafe"}, - "unsafe": {}, - - "L0": { - "errors", - "io", - "runtime", - "sync", - "sync/atomic", - "unsafe", - }, - - // L1 adds simple functions and strings processing, - // but not Unicode tables. - "math": {"unsafe"}, - "math/cmplx": {"math"}, - "math/rand": {"L0", "math"}, - "sort": {"math"}, - "strconv": {"L0", "unicode/utf8", "math"}, - "unicode/utf16": {}, - "unicode/utf8": {}, - - "L1": { - "L0", - "math", - "math/cmplx", - "math/rand", - "sort", - "strconv", - "unicode/utf16", - "unicode/utf8", - }, - - // L2 adds Unicode and strings processing. - "bufio": {"L0", "unicode/utf8", "bytes"}, - "bytes": {"L0", "unicode", "unicode/utf8"}, - "path": {"L0", "unicode/utf8", "strings"}, - "strings": {"L0", "unicode", "unicode/utf8"}, - "unicode": {}, - - "L2": { - "L1", - "bufio", - "bytes", - "path", - "strings", - "unicode", - }, - - // L3 adds reflection and some basic utility packages - // and interface definitions, but nothing that makes - // system calls. - "crypto": {"L2", "hash"}, // interfaces - "crypto/cipher": {"L2"}, // interfaces - "encoding/base32": {"L2"}, - "encoding/base64": {"L2"}, - "encoding/binary": {"L2", "reflect"}, - "hash": {"L2"}, // interfaces - "hash/adler32": {"L2", "hash"}, - "hash/crc32": {"L2", "hash"}, - "hash/crc64": {"L2", "hash"}, - "hash/fnv": {"L2", "hash"}, - "image": {"L2", "image/color"}, // interfaces - "image/color": {"L2"}, // interfaces - "reflect": {"L2"}, - - "L3": { - "L2", - "crypto", - "crypto/cipher", - "encoding/base32", - "encoding/base64", - "encoding/binary", - "hash", - "hash/adler32", - "hash/crc32", - "hash/crc64", - "hash/fnv", - "image", - "image/color", - "reflect", - }, - - // End of linear dependency definitions. - - // Operating system access. - "syscall": {"L0", "unicode/utf16"}, - "time": {"L0", "syscall"}, - "os": {"L1", "os", "syscall", "time"}, - "path/filepath": {"L2", "os", "syscall"}, - "io/ioutil": {"L2", "os", "path/filepath", "time"}, - "os/exec": {"L2", "os", "syscall"}, - "os/signal": {"L2", "os", "syscall"}, - - // OS enables basic operating system functionality, - // but not direct use of package syscall, nor os/signal. - "OS": { - "io/ioutil", - "os", - "os/exec", - "path/filepath", - "time", - }, - - // Formatted I/O: few dependencies (L1) but we must add reflect. - "fmt": {"L1", "os", "reflect"}, - "log": {"L1", "os", "fmt", "time"}, - - // Packages used by testing must be low-level (L2+fmt). - "regexp": {"L2", "regexp/syntax"}, - "regexp/syntax": {"L2"}, - "runtime/debug": {"L2", "fmt", "io/ioutil", "os"}, - "runtime/pprof": {"L2", "fmt", "text/tabwriter"}, - "text/tabwriter": {"L2"}, - - "testing": {"L2", "flag", "fmt", "os", "runtime/pprof", "time"}, - "testing/iotest": {"L2", "log"}, - "testing/quick": {"L2", "flag", "fmt", "reflect"}, - - // L4 is defined as L3+fmt+log+time, because in general once - // you're using L3 packages, use of fmt, log, or time is not a big deal. - "L4": { - "L3", - "fmt", - "log", - "time", - }, - - // Go parser. - "go/ast": {"L4", "OS", "go/scanner", "go/token"}, - "go/doc": {"L4", "go/ast", "go/token", "regexp", "text/template"}, - "go/parser": {"L4", "OS", "go/ast", "go/scanner", "go/token"}, - "go/printer": {"L4", "OS", "go/ast", "go/scanner", "go/token", "text/tabwriter"}, - "go/scanner": {"L4", "OS", "go/token"}, - "go/token": {"L4"}, - - "GOPARSER": { - "go/ast", - "go/doc", - "go/parser", - "go/printer", - "go/scanner", - "go/token", - }, - - // One of a kind. - "archive/tar": {"L4", "OS", "syscall"}, - "archive/zip": {"L4", "OS", "compress/flate"}, - "compress/bzip2": {"L4"}, - "compress/flate": {"L4"}, - "compress/gzip": {"L4", "compress/flate"}, - "compress/lzw": {"L4"}, - "compress/zlib": {"L4", "compress/flate"}, - "database/sql": {"L4", "database/sql/driver"}, - "database/sql/driver": {"L4", "time"}, - "debug/dwarf": {"L4"}, - "debug/elf": {"L4", "OS", "debug/dwarf"}, - "debug/gosym": {"L4"}, - "debug/macho": {"L4", "OS", "debug/dwarf"}, - "debug/pe": {"L4", "OS", "debug/dwarf"}, - "encoding/ascii85": {"L4"}, - "encoding/asn1": {"L4", "math/big"}, - "encoding/csv": {"L4"}, - "encoding/gob": {"L4", "OS"}, - "encoding/hex": {"L4"}, - "encoding/json": {"L4"}, - "encoding/pem": {"L4"}, - "encoding/xml": {"L4"}, - "flag": {"L4", "OS"}, - "go/build": {"L4", "OS", "GOPARSER"}, - "html": {"L4"}, - "image/draw": {"L4"}, - "image/gif": {"L4", "compress/lzw"}, - "image/jpeg": {"L4"}, - "image/png": {"L4", "compress/zlib"}, - "index/suffixarray": {"L4", "regexp"}, - "math/big": {"L4"}, - "mime": {"L4", "OS", "syscall"}, - "net/url": {"L4"}, - "text/scanner": {"L4", "OS"}, - "text/template/parse": {"L4"}, - - "html/template": { - "L4", "OS", "encoding/json", "html", "text/template", - "text/template/parse", - }, - "text/template": { - "L4", "OS", "net/url", "text/template/parse", - }, - - // Cgo. - "runtime/cgo": {"L0", "C"}, - "CGO": {"C", "runtime/cgo"}, - - // Fake entry to satisfy the pseudo-import "C" - // that shows up in programs that use cgo. - "C": {}, - - "os/user": {"L4", "CGO", "syscall"}, - - // Basic networking. - // Because net must be used by any package that wants to - // do networking portably, it must have a small dependency set: just L1+basic os. - "net": {"L1", "CGO", "os", "syscall", "time"}, - - // NET enables use of basic network-related packages. - "NET": { - "net", - "mime", - "net/textproto", - "net/url", - }, - - // Uses of networking. - "log/syslog": {"L4", "OS", "net"}, - "net/mail": {"L4", "NET", "OS"}, - "net/textproto": {"L4", "OS", "net"}, - - // Support libraries for crypto that aren't L2. - "CRYPTO-SUPPORT": { - "crypto/subtle", - }, - - // Core crypto. - "crypto/aes": {"L3"}, - "crypto/des": {"L3"}, - "crypto/hmac": {"L3", "CRYPTO-SUPPORT"}, - "crypto/md5": {"L3"}, - "crypto/rc4": {"L3"}, - "crypto/sha1": {"L3"}, - "crypto/sha256": {"L3"}, - "crypto/sha512": {"L3"}, - - "CRYPTO": { - "CRYPTO-SUPPORT", - "crypto/aes", - "crypto/des", - "crypto/hmac", - "crypto/md5", - "crypto/rc4", - "crypto/sha1", - "crypto/sha256", - "crypto/sha512", - }, - - // Random byte, number generation. - // This would be part of core crypto except that it imports - // math/big, which imports fmt. - "crypto/rand": {"L4", "CRYPTO", "OS", "math/big", "syscall"}, - - // Mathematical crypto: dependencies on fmt (L4) and math/big. - // We could avoid some of the fmt, but math/big imports fmt anyway. - "crypto/dsa": {"L4", "CRYPTO", "math/big"}, - "crypto/ecdsa": {"L4", "CRYPTO", "crypto/elliptic", "math/big"}, - "crypto/elliptic": {"L4", "CRYPTO", "math/big"}, - "crypto/rsa": {"L4", "CRYPTO", "crypto/rand", "math/big"}, - - "CRYPTO-MATH": { - "CRYPTO", - "crypto/dsa", - "crypto/ecdsa", - "crypto/elliptic", - "crypto/rand", - "crypto/rsa", - "encoding/asn1", - "math/big", - }, - - // SSL/TLS. - "crypto/tls": { - "L4", "CRYPTO-MATH", "CGO", "OS", - "crypto/x509", "encoding/pem", "net", "syscall", - }, - "crypto/x509": { - "L4", "CRYPTO-MATH", "OS", "CGO", - "crypto/x509/pkix", "encoding/pem", "encoding/hex", "syscall", - }, - "crypto/x509/pkix": {"L4", "CRYPTO-MATH"}, - - // Simple net+crypto-aware packages. - "mime/multipart": {"L4", "OS", "mime", "crypto/rand", "net/textproto"}, - "net/smtp": {"L4", "CRYPTO", "NET", "crypto/tls"}, - - // HTTP, kingpin of dependencies. - "net/http": { - "L4", "NET", "OS", - "compress/gzip", "crypto/tls", "mime/multipart", "runtime/debug", - }, - - // HTTP-using packages. - "expvar": {"L4", "OS", "encoding/json", "net/http"}, - "net/http/cgi": {"L4", "NET", "OS", "crypto/tls", "net/http", "regexp"}, - "net/http/fcgi": {"L4", "NET", "OS", "net/http", "net/http/cgi"}, - "net/http/httptest": {"L4", "NET", "OS", "crypto/tls", "flag", "net/http"}, - "net/http/httputil": {"L4", "NET", "OS", "net/http"}, - "net/http/pprof": {"L4", "OS", "html/template", "net/http", "runtime/pprof"}, - "net/rpc": {"L4", "NET", "encoding/gob", "net/http", "text/template"}, - "net/rpc/jsonrpc": {"L4", "NET", "encoding/json", "net/rpc"}, -} - -// isMacro reports whether p is a package dependency macro -// (uppercase name). -func isMacro(p string) bool { - return 'A' <= p[0] && p[0] <= 'Z' -} - -func allowed(pkg string) map[string]bool { - m := map[string]bool{} - var allow func(string) - allow = func(p string) { - if m[p] { - return - } - m[p] = true // set even for macros, to avoid loop on cycle - - // Upper-case names are macro-expanded. - if isMacro(p) { - for _, pp := range pkgDeps[p] { - allow(pp) - } - } - } - for _, pp := range pkgDeps[pkg] { - allow(pp) - } - return m -} - -var bools = []bool{false, true} -var geese = []string{"darwin", "freebsd", "linux", "netbsd", "openbsd", "plan9", "windows"} -var goarches = []string{"386", "amd64", "arm"} - -type osPkg struct { - goos, pkg string -} - -// allowedErrors are the operating systems and packages known to contain errors -// (currently just "no Go source files") -var allowedErrors = map[osPkg]bool{ - osPkg{"windows", "log/syslog"}: true, - osPkg{"plan9", "log/syslog"}: true, -} - -func TestDependencies(t *testing.T) { - var all []string - - for k := range pkgDeps { - all = append(all, k) - } - sort.Strings(all) - - ctxt := build.Default - test := func(mustImport bool) { - for _, pkg := range all { - if isMacro(pkg) { - continue - } - p, err := ctxt.Import(pkg, "", 0) - if err != nil { - if allowedErrors[osPkg{ctxt.GOOS, pkg}] { - continue - } - // Some of the combinations we try might not - // be reasonable (like arm,plan9,cgo), so ignore - // errors for the auto-generated combinations. - if !mustImport { - continue - } - t.Errorf("%s/%s/cgo=%v %v", ctxt.GOOS, ctxt.GOARCH, ctxt.CgoEnabled, err) - continue - } - ok := allowed(pkg) - var bad []string - for _, imp := range p.Imports { - if !ok[imp] { - bad = append(bad, imp) - } - } - if bad != nil { - t.Errorf("%s/%s/cgo=%v unexpected dependency: %s imports %v", ctxt.GOOS, ctxt.GOARCH, ctxt.CgoEnabled, pkg, bad) - } - } - } - test(true) - - if testing.Short() { - t.Logf("skipping other systems") - return - } - - for _, ctxt.GOOS = range geese { - for _, ctxt.GOARCH = range goarches { - for _, ctxt.CgoEnabled = range bools { - test(false) - } - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/build/doc.go b/gcc-4.8.1/libgo/go/go/build/doc.go deleted file mode 100644 index c562d05d0..000000000 --- a/gcc-4.8.1/libgo/go/go/build/doc.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package build gathers information about Go packages. -// -// Go Path -// -// The Go path is a list of directory trees containing Go source code. -// It is consulted to resolve imports that cannot be found in the standard -// Go tree. The default path is the value of the GOPATH environment -// variable, interpreted as a path list appropriate to the operating system -// (on Unix, the variable is a colon-separated string; -// on Windows, a semicolon-separated string; -// on Plan 9, a list). -// -// Each directory listed in the Go path must have a prescribed structure: -// -// The src/ directory holds source code. The path below 'src' determines -// the import path or executable name. -// -// The pkg/ directory holds installed package objects. -// As in the Go tree, each target operating system and -// architecture pair has its own subdirectory of pkg -// (pkg/GOOS_GOARCH). -// -// If DIR is a directory listed in the Go path, a package with -// source in DIR/src/foo/bar can be imported as "foo/bar" and -// has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a" -// (or, for gccgo, "DIR/pkg/gccgo/foo/libbar.a"). -// -// The bin/ directory holds compiled commands. -// Each command is named for its source directory, but only -// using the final element, not the entire path. That is, the -// command with source in DIR/src/foo/quux is installed into -// DIR/bin/quux, not DIR/bin/foo/quux. The foo/ is stripped -// so that you can add DIR/bin to your PATH to get at the -// installed commands. -// -// Here's an example directory layout: -// -// GOPATH=/home/user/gocode -// -// /home/user/gocode/ -// src/ -// foo/ -// bar/ (go code in package bar) -// x.go -// quux/ (go code in package main) -// y.go -// bin/ -// quux (installed command) -// pkg/ -// linux_amd64/ -// foo/ -// bar.a (installed package object) -// -// Build Constraints -// -// A build constraint is a line comment beginning with the directive +build -// that lists the conditions under which a file should be included in the package. -// Constraints may appear in any kind of source file (not just Go), but -// they must appear near the top of the file, preceded -// only by blank lines and other line comments. -// -// To distinguish build constraints from package documentation, a series of -// build constraints must be followed by a blank line. -// -// A build constraint is evaluated as the OR of space-separated options; -// each option evaluates as the AND of its comma-separated terms; -// and each term is an alphanumeric word or, preceded by !, its negation. -// That is, the build constraint: -// -// // +build linux,386 darwin,!cgo -// -// corresponds to the boolean formula: -// -// (linux AND 386) OR (darwin AND (NOT cgo)) -// -// A file may have multiple build constraints. The overall constraint is the AND -// of the individual constraints. That is, the build constraints: -// -// // +build linux darwin -// // +build 386 -// -// corresponds to the boolean formula: -// -// (linux OR darwin) AND 386 -// -// During a particular build, the following words are satisfied: -// -// - the target operating system, as spelled by runtime.GOOS -// - the target architecture, as spelled by runtime.GOARCH -// - the compiler being used, currently either "gc" or "gccgo" -// - "cgo", if ctxt.CgoEnabled is true -// - any additional words listed in ctxt.BuildTags -// -// If a file's name, after stripping the extension and a possible _test suffix, -// matches *_GOOS, *_GOARCH, or *_GOOS_GOARCH for any known operating -// system and architecture values, then the file is considered to have an implicit -// build constraint requiring those terms. -// -// To keep a file from being considered for the build: -// -// // +build ignore -// -// (any other unsatisfied word will work as well, but ``ignore'' is conventional.) -// -// To build a file only when using cgo, and only on Linux and OS X: -// -// // +build linux,cgo darwin,cgo -// -// Such a file is usually paired with another file implementing the -// default functionality for other systems, which in this case would -// carry the constraint: -// -// // +build !linux,!darwin !cgo -// -// Naming a file dns_windows.go will cause it to be included only when -// building the package for Windows; similarly, math_386.s will be included -// only when building the package for 32-bit x86. -// -package build diff --git a/gcc-4.8.1/libgo/go/go/build/read.go b/gcc-4.8.1/libgo/go/go/build/read.go deleted file mode 100644 index c8079dfd1..000000000 --- a/gcc-4.8.1/libgo/go/go/build/read.go +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package build - -import ( - "bufio" - "errors" - "io" -) - -type importReader struct { - b *bufio.Reader - buf []byte - peek byte - err error - eof bool - nerr int -} - -func isIdent(c byte) bool { - return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '_' || c >= 0x80 -} - -var ( - errSyntax = errors.New("syntax error") - errNUL = errors.New("unexpected NUL in input") -) - -// syntaxError records a syntax error, but only if an I/O error has not already been recorded. -func (r *importReader) syntaxError() { - if r.err == nil { - r.err = errSyntax - } -} - -// readByte reads the next byte from the input, saves it in buf, and returns it. -// If an error occurs, readByte records the error in r.err and returns 0. -func (r *importReader) readByte() byte { - c, err := r.b.ReadByte() - if err == nil { - r.buf = append(r.buf, c) - if c == 0 { - err = errNUL - } - } - if err != nil { - if err == io.EOF { - r.eof = true - } else if r.err == nil { - r.err = err - } - c = 0 - } - return c -} - -// peekByte returns the next byte from the input reader but does not advance beyond it. -// If skipSpace is set, peekByte skips leading spaces and comments. -func (r *importReader) peekByte(skipSpace bool) byte { - if r.err != nil { - if r.nerr++; r.nerr > 10000 { - panic("go/build: import reader looping") - } - return 0 - } - - // Use r.peek as first input byte. - // Don't just return r.peek here: it might have been left by peekByte(false) - // and this might be peekByte(true). - c := r.peek - if c == 0 { - c = r.readByte() - } - for r.err == nil && !r.eof { - if skipSpace { - // For the purposes of this reader, semicolons are never necessary to - // understand the input and are treated as spaces. - switch c { - case ' ', '\f', '\t', '\r', '\n', ';': - c = r.readByte() - continue - - case '/': - c = r.readByte() - if c == '/' { - for c != '\n' && r.err == nil && !r.eof { - c = r.readByte() - } - } else if c == '*' { - var c1 byte - for (c != '*' || c1 != '/') && r.err == nil { - if r.eof { - r.syntaxError() - } - c, c1 = c1, r.readByte() - } - } else { - r.syntaxError() - } - c = r.readByte() - continue - } - } - break - } - r.peek = c - return r.peek -} - -// nextByte is like peekByte but advances beyond the returned byte. -func (r *importReader) nextByte(skipSpace bool) byte { - c := r.peekByte(skipSpace) - r.peek = 0 - return c -} - -// readKeyword reads the given keyword from the input. -// If the keyword is not present, readKeyword records a syntax error. -func (r *importReader) readKeyword(kw string) { - r.peekByte(true) - for i := 0; i < len(kw); i++ { - if r.nextByte(false) != kw[i] { - r.syntaxError() - return - } - } - if isIdent(r.peekByte(false)) { - r.syntaxError() - } -} - -// readIdent reads an identifier from the input. -// If an identifier is not present, readIdent records a syntax error. -func (r *importReader) readIdent() { - c := r.peekByte(true) - if !isIdent(c) { - r.syntaxError() - return - } - for isIdent(r.peekByte(false)) { - r.peek = 0 - } -} - -// readString reads a quoted string literal from the input. -// If an identifier is not present, readString records a syntax error. -func (r *importReader) readString() { - switch r.nextByte(true) { - case '`': - for r.err == nil { - if r.nextByte(false) == '`' { - break - } - if r.eof { - r.syntaxError() - } - } - case '"': - for r.err == nil { - c := r.nextByte(false) - if c == '"' { - break - } - if r.eof || c == '\n' { - r.syntaxError() - } - if c == '\\' { - r.nextByte(false) - } - } - default: - r.syntaxError() - } -} - -// readImport reads an import clause - optional identifier followed by quoted string - -// from the input. -func (r *importReader) readImport() { - c := r.peekByte(true) - if c == '.' { - r.peek = 0 - } else if isIdent(c) { - r.readIdent() - } - r.readString() -} - -// readComments is like ioutil.ReadAll, except that it only reads the leading -// block of comments in the file. -func readComments(f io.Reader) ([]byte, error) { - r := &importReader{b: bufio.NewReader(f)} - r.peekByte(true) - if r.err == nil && !r.eof { - // Didn't reach EOF, so must have found a non-space byte. Remove it. - r.buf = r.buf[:len(r.buf)-1] - } - return r.buf, r.err -} - -// readImports is like ioutil.ReadAll, except that it expects a Go file as input -// and stops reading the input once the imports have completed. -func readImports(f io.Reader, reportSyntaxError bool) ([]byte, error) { - r := &importReader{b: bufio.NewReader(f)} - - r.readKeyword("package") - r.readIdent() - for r.peekByte(true) == 'i' { - r.readKeyword("import") - if r.peekByte(true) == '(' { - r.nextByte(false) - for r.peekByte(true) != ')' && r.err == nil { - r.readImport() - } - r.nextByte(false) - } else { - r.readImport() - } - } - - // If we stopped successfully before EOF, we read a byte that told us we were done. - // Return all but that last byte, which would cause a syntax error if we let it through. - if r.err == nil && !r.eof { - return r.buf[:len(r.buf)-1], nil - } - - // If we stopped for a syntax error, consume the whole file so that - // we are sure we don't change the errors that go/parser returns. - if r.err == errSyntax && !reportSyntaxError { - r.err = nil - for r.err == nil && !r.eof { - r.readByte() - } - } - - return r.buf, r.err -} diff --git a/gcc-4.8.1/libgo/go/go/build/read_test.go b/gcc-4.8.1/libgo/go/go/build/read_test.go deleted file mode 100644 index 2dcc1208f..000000000 --- a/gcc-4.8.1/libgo/go/go/build/read_test.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package build - -import ( - "io" - "strings" - "testing" -) - -const quote = "`" - -type readTest struct { - // Test input contains ℙ where readImports should stop. - in string - err string -} - -var readImportsTests = []readTest{ - { - `package p`, - "", - }, - { - `package p; import "x"`, - "", - }, - { - `package p; import . "x"`, - "", - }, - { - `package p; import "x";ℙvar x = 1`, - "", - }, - { - `package p - - // comment - - import "x" - import _ "x" - import a "x" - - /* comment */ - - import ( - "x" /* comment */ - _ "x" - a "x" // comment - ` + quote + `x` + quote + ` - _ /*comment*/ ` + quote + `x` + quote + ` - a ` + quote + `x` + quote + ` - ) - import ( - ) - import () - import()import()import() - import();import();import() - - ℙvar x = 1 - `, - "", - }, -} - -var readCommentsTests = []readTest{ - { - `ℙpackage p`, - "", - }, - { - `ℙpackage p; import "x"`, - "", - }, - { - `ℙpackage p; import . "x"`, - "", - }, - { - `// foo - - /* bar */ - - /* quux */ // baz - - /*/ zot */ - - // asdf - ℙHello, world`, - "", - }, -} - -func testRead(t *testing.T, tests []readTest, read func(io.Reader) ([]byte, error)) { - for i, tt := range tests { - var in, testOut string - j := strings.Index(tt.in, "ℙ") - if j < 0 { - in = tt.in - testOut = tt.in - } else { - in = tt.in[:j] + tt.in[j+len("ℙ"):] - testOut = tt.in[:j] - } - r := strings.NewReader(in) - buf, err := read(r) - if err != nil { - if tt.err == "" { - t.Errorf("#%d: err=%q, expected success (%q)", i, err, string(buf)) - continue - } - if !strings.Contains(err.Error(), tt.err) { - t.Errorf("#%d: err=%q, expected %q", i, err, tt.err) - continue - } - continue - } - if err == nil && tt.err != "" { - t.Errorf("#%d: success, expected %q", i, tt.err) - continue - } - - out := string(buf) - if out != testOut { - t.Errorf("#%d: wrong output:\nhave %q\nwant %q\n", i, out, testOut) - } - } -} - -func TestReadImports(t *testing.T) { - testRead(t, readImportsTests, func(r io.Reader) ([]byte, error) { return readImports(r, true) }) -} - -func TestReadComments(t *testing.T) { - testRead(t, readCommentsTests, readComments) -} - -var readFailuresTests = []readTest{ - { - `package`, - "syntax error", - }, - { - "package p\n\x00\nimport `math`\n", - "unexpected NUL in input", - }, - { - `package p; import`, - "syntax error", - }, - { - `package p; import "`, - "syntax error", - }, - { - "package p; import ` \n\n", - "syntax error", - }, - { - `package p; import "x`, - "syntax error", - }, - { - `package p; import _`, - "syntax error", - }, - { - `package p; import _ "`, - "syntax error", - }, - { - `package p; import _ "x`, - "syntax error", - }, - { - `package p; import .`, - "syntax error", - }, - { - `package p; import . "`, - "syntax error", - }, - { - `package p; import . "x`, - "syntax error", - }, - { - `package p; import (`, - "syntax error", - }, - { - `package p; import ("`, - "syntax error", - }, - { - `package p; import ("x`, - "syntax error", - }, - { - `package p; import ("x"`, - "syntax error", - }, -} - -func TestReadFailures(t *testing.T) { - // Errors should be reported (true arg to readImports). - testRead(t, readFailuresTests, func(r io.Reader) ([]byte, error) { return readImports(r, true) }) -} - -func TestReadFailuresIgnored(t *testing.T) { - // Syntax errors should not be reported (false arg to readImports). - // Instead, entire file should be the output and no error. - // Convert tests not to return syntax errors. - tests := make([]readTest, len(readFailuresTests)) - copy(tests, readFailuresTests) - for i := range tests { - tt := &tests[i] - if !strings.Contains(tt.err, "NUL") { - tt.err = "" - } - } - testRead(t, tests, func(r io.Reader) ([]byte, error) { return readImports(r, false) }) -} diff --git a/gcc-4.8.1/libgo/go/go/build/syslist_test.go b/gcc-4.8.1/libgo/go/go/build/syslist_test.go deleted file mode 100644 index 9157faf8c..000000000 --- a/gcc-4.8.1/libgo/go/go/build/syslist_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package build - -import ( - "runtime" - "testing" -) - -var ( - thisOS = runtime.GOOS - thisArch = runtime.GOARCH - otherOS = anotherOS() - otherArch = anotherArch() -) - -func anotherOS() string { - if thisOS != "darwin" { - return "darwin" - } - return "linux" -} - -func anotherArch() string { - if thisArch != "amd64" { - return "amd64" - } - return "386" -} - -type GoodFileTest struct { - name string - result bool -} - -var tests = []GoodFileTest{ - {"file.go", true}, - {"file.c", true}, - {"file_foo.go", true}, - {"file_" + thisArch + ".go", true}, - {"file_" + otherArch + ".go", false}, - {"file_" + thisOS + ".go", true}, - {"file_" + otherOS + ".go", false}, - {"file_" + thisOS + "_" + thisArch + ".go", true}, - {"file_" + otherOS + "_" + thisArch + ".go", false}, - {"file_" + thisOS + "_" + otherArch + ".go", false}, - {"file_" + otherOS + "_" + otherArch + ".go", false}, - {"file_foo_" + thisArch + ".go", true}, - {"file_foo_" + otherArch + ".go", false}, - {"file_" + thisOS + ".c", true}, - {"file_" + otherOS + ".c", false}, -} - -func TestGoodOSArch(t *testing.T) { - for _, test := range tests { - if Default.goodOSArchFile(test.name) != test.result { - t.Fatalf("goodOSArchFile(%q) != %v", test.name, test.result) - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/build/testdata/other/file/file.go b/gcc-4.8.1/libgo/go/go/build/testdata/other/file/file.go deleted file mode 100644 index bbfd3e9e5..000000000 --- a/gcc-4.8.1/libgo/go/go/build/testdata/other/file/file.go +++ /dev/null @@ -1,5 +0,0 @@ -// Test data - not compiled. - -package file - -func F() {} diff --git a/gcc-4.8.1/libgo/go/go/build/testdata/other/main.go b/gcc-4.8.1/libgo/go/go/build/testdata/other/main.go deleted file mode 100644 index e0904357c..000000000 --- a/gcc-4.8.1/libgo/go/go/build/testdata/other/main.go +++ /dev/null @@ -1,11 +0,0 @@ -// Test data - not compiled. - -package main - -import ( - "./file" -) - -func main() { - file.F() -} diff --git a/gcc-4.8.1/libgo/go/go/doc/comment.go b/gcc-4.8.1/libgo/go/go/doc/comment.go deleted file mode 100644 index c4b7e6ae6..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/comment.go +++ /dev/null @@ -1,442 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Godoc comment extraction and comment -> HTML formatting. - -package doc - -import ( - "io" - "regexp" - "strings" - "text/template" // for HTMLEscape - "unicode" - "unicode/utf8" -) - -var ( - ldquo = []byte("“") - rdquo = []byte("”") -) - -// Escape comment text for HTML. If nice is set, -// also turn `` into “ and '' into ”. -func commentEscape(w io.Writer, text string, nice bool) { - last := 0 - if nice { - for i := 0; i < len(text)-1; i++ { - ch := text[i] - if ch == text[i+1] && (ch == '`' || ch == '\'') { - template.HTMLEscape(w, []byte(text[last:i])) - last = i + 2 - switch ch { - case '`': - w.Write(ldquo) - case '\'': - w.Write(rdquo) - } - i++ // loop will add one more - } - } - } - template.HTMLEscape(w, []byte(text[last:])) -} - -const ( - // Regexp for Go identifiers - identRx = `[a-zA-Z_][a-zA-Z_0-9]*` // TODO(gri) ASCII only for now - fix this - - // Regexp for URLs - protocol = `(https?|ftp|file|gopher|mailto|news|nntp|telnet|wais|prospero):` - hostPart = `[a-zA-Z0-9_@\-]+` - filePart = `[a-zA-Z0-9_?%#~&/\-+=]+` - urlRx = protocol + `//` + // http:// - hostPart + `([.:]` + hostPart + `)*/?` + // //www.google.com:8080/ - filePart + `([:.,]` + filePart + `)*` -) - -var matchRx = regexp.MustCompile(`(` + urlRx + `)|(` + identRx + `)`) - -var ( - html_a = []byte(`<a href="`) - html_aq = []byte(`">`) - html_enda = []byte("</a>") - html_i = []byte("<i>") - html_endi = []byte("</i>") - html_p = []byte("<p>\n") - html_endp = []byte("</p>\n") - html_pre = []byte("<pre>") - html_endpre = []byte("</pre>\n") - html_h = []byte(`<h3 id="`) - html_hq = []byte(`">`) - html_endh = []byte("</h3>\n") -) - -// Emphasize and escape a line of text for HTML. URLs are converted into links; -// if the URL also appears in the words map, the link is taken from the map (if -// the corresponding map value is the empty string, the URL is not converted -// into a link). Go identifiers that appear in the words map are italicized; if -// the corresponding map value is not the empty string, it is considered a URL -// and the word is converted into a link. If nice is set, the remaining text's -// appearance is improved where it makes sense (e.g., `` is turned into “ -// and '' into ”). -func emphasize(w io.Writer, line string, words map[string]string, nice bool) { - for { - m := matchRx.FindStringSubmatchIndex(line) - if m == nil { - break - } - // m >= 6 (two parenthesized sub-regexps in matchRx, 1st one is urlRx) - - // write text before match - commentEscape(w, line[0:m[0]], nice) - - // analyze match - match := line[m[0]:m[1]] - url := "" - italics := false - if words != nil { - url, italics = words[string(match)] - } - if m[2] >= 0 { - // match against first parenthesized sub-regexp; must be match against urlRx - if !italics { - // no alternative URL in words list, use match instead - url = string(match) - } - italics = false // don't italicize URLs - } - - // write match - if len(url) > 0 { - w.Write(html_a) - template.HTMLEscape(w, []byte(url)) - w.Write(html_aq) - } - if italics { - w.Write(html_i) - } - commentEscape(w, match, nice) - if italics { - w.Write(html_endi) - } - if len(url) > 0 { - w.Write(html_enda) - } - - // advance - line = line[m[1]:] - } - commentEscape(w, line, nice) -} - -func indentLen(s string) int { - i := 0 - for i < len(s) && (s[i] == ' ' || s[i] == '\t') { - i++ - } - return i -} - -func isBlank(s string) bool { - return len(s) == 0 || (len(s) == 1 && s[0] == '\n') -} - -func commonPrefix(a, b string) string { - i := 0 - for i < len(a) && i < len(b) && a[i] == b[i] { - i++ - } - return a[0:i] -} - -func unindent(block []string) { - if len(block) == 0 { - return - } - - // compute maximum common white prefix - prefix := block[0][0:indentLen(block[0])] - for _, line := range block { - if !isBlank(line) { - prefix = commonPrefix(prefix, line[0:indentLen(line)]) - } - } - n := len(prefix) - - // remove - for i, line := range block { - if !isBlank(line) { - block[i] = line[n:] - } - } -} - -// heading returns the trimmed line if it passes as a section heading; -// otherwise it returns the empty string. -func heading(line string) string { - line = strings.TrimSpace(line) - if len(line) == 0 { - return "" - } - - // a heading must start with an uppercase letter - r, _ := utf8.DecodeRuneInString(line) - if !unicode.IsLetter(r) || !unicode.IsUpper(r) { - return "" - } - - // it must end in a letter or digit: - r, _ = utf8.DecodeLastRuneInString(line) - if !unicode.IsLetter(r) && !unicode.IsDigit(r) { - return "" - } - - // exclude lines with illegal characters - if strings.IndexAny(line, ",.;:!?+*/=()[]{}_^°&§~%#@<\">\\") >= 0 { - return "" - } - - // allow "'" for possessive "'s" only - for b := line; ; { - i := strings.IndexRune(b, '\'') - if i < 0 { - break - } - if i+1 >= len(b) || b[i+1] != 's' || (i+2 < len(b) && b[i+2] != ' ') { - return "" // not followed by "s " - } - b = b[i+2:] - } - - return line -} - -type op int - -const ( - opPara op = iota - opHead - opPre -) - -type block struct { - op op - lines []string -} - -var nonAlphaNumRx = regexp.MustCompile(`[^a-zA-Z0-9]`) - -func anchorID(line string) string { - // Add a "hdr-" prefix to avoid conflicting with IDs used for package symbols. - return "hdr-" + nonAlphaNumRx.ReplaceAllString(line, "_") -} - -// ToHTML converts comment text to formatted HTML. -// The comment was prepared by DocReader, -// so it is known not to have leading, trailing blank lines -// nor to have trailing spaces at the end of lines. -// The comment markers have already been removed. -// -// Turn each run of multiple \n into </p><p>. -// Turn each run of indented lines into a <pre> block without indent. -// Enclose headings with header tags. -// -// URLs in the comment text are converted into links; if the URL also appears -// in the words map, the link is taken from the map (if the corresponding map -// value is the empty string, the URL is not converted into a link). -// -// Go identifiers that appear in the words map are italicized; if the corresponding -// map value is not the empty string, it is considered a URL and the word is converted -// into a link. -func ToHTML(w io.Writer, text string, words map[string]string) { - for _, b := range blocks(text) { - switch b.op { - case opPara: - w.Write(html_p) - for _, line := range b.lines { - emphasize(w, line, words, true) - } - w.Write(html_endp) - case opHead: - w.Write(html_h) - id := "" - for _, line := range b.lines { - if id == "" { - id = anchorID(line) - w.Write([]byte(id)) - w.Write(html_hq) - } - commentEscape(w, line, true) - } - if id == "" { - w.Write(html_hq) - } - w.Write(html_endh) - case opPre: - w.Write(html_pre) - for _, line := range b.lines { - emphasize(w, line, nil, false) - } - w.Write(html_endpre) - } - } -} - -func blocks(text string) []block { - var ( - out []block - para []string - - lastWasBlank = false - lastWasHeading = false - ) - - close := func() { - if para != nil { - out = append(out, block{opPara, para}) - para = nil - } - } - - lines := strings.SplitAfter(text, "\n") - unindent(lines) - for i := 0; i < len(lines); { - line := lines[i] - if isBlank(line) { - // close paragraph - close() - i++ - lastWasBlank = true - continue - } - if indentLen(line) > 0 { - // close paragraph - close() - - // count indented or blank lines - j := i + 1 - for j < len(lines) && (isBlank(lines[j]) || indentLen(lines[j]) > 0) { - j++ - } - // but not trailing blank lines - for j > i && isBlank(lines[j-1]) { - j-- - } - pre := lines[i:j] - i = j - - unindent(pre) - - // put those lines in a pre block - out = append(out, block{opPre, pre}) - lastWasHeading = false - continue - } - - if lastWasBlank && !lastWasHeading && i+2 < len(lines) && - isBlank(lines[i+1]) && !isBlank(lines[i+2]) && indentLen(lines[i+2]) == 0 { - // current line is non-blank, surrounded by blank lines - // and the next non-blank line is not indented: this - // might be a heading. - if head := heading(line); head != "" { - close() - out = append(out, block{opHead, []string{head}}) - i += 2 - lastWasHeading = true - continue - } - } - - // open paragraph - lastWasBlank = false - lastWasHeading = false - para = append(para, lines[i]) - i++ - } - close() - - return out -} - -// ToText prepares comment text for presentation in textual output. -// It wraps paragraphs of text to width or fewer Unicode code points -// and then prefixes each line with the indent. In preformatted sections -// (such as program text), it prefixes each non-blank line with preIndent. -func ToText(w io.Writer, text string, indent, preIndent string, width int) { - l := lineWrapper{ - out: w, - width: width, - indent: indent, - } - for _, b := range blocks(text) { - switch b.op { - case opPara: - // l.write will add leading newline if required - for _, line := range b.lines { - l.write(line) - } - l.flush() - case opHead: - w.Write(nl) - for _, line := range b.lines { - l.write(line + "\n") - } - l.flush() - case opPre: - w.Write(nl) - for _, line := range b.lines { - if !isBlank(line) { - w.Write([]byte(preIndent)) - w.Write([]byte(line)) - } - } - } - } -} - -type lineWrapper struct { - out io.Writer - printed bool - width int - indent string - n int - pendSpace int -} - -var nl = []byte("\n") -var space = []byte(" ") - -func (l *lineWrapper) write(text string) { - if l.n == 0 && l.printed { - l.out.Write(nl) // blank line before new paragraph - } - l.printed = true - - for _, f := range strings.Fields(text) { - w := utf8.RuneCountInString(f) - // wrap if line is too long - if l.n > 0 && l.n+l.pendSpace+w > l.width { - l.out.Write(nl) - l.n = 0 - l.pendSpace = 0 - } - if l.n == 0 { - l.out.Write([]byte(l.indent)) - } - l.out.Write(space[:l.pendSpace]) - l.out.Write([]byte(f)) - l.n += l.pendSpace + w - l.pendSpace = 1 - } -} - -func (l *lineWrapper) flush() { - if l.n == 0 { - return - } - l.out.Write(nl) - l.pendSpace = 0 - l.n = 0 -} diff --git a/gcc-4.8.1/libgo/go/go/doc/comment_test.go b/gcc-4.8.1/libgo/go/go/doc/comment_test.go deleted file mode 100644 index aa21b8d1b..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/comment_test.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package doc - -import ( - "bytes" - "reflect" - "testing" -) - -var headingTests = []struct { - line string - ok bool -}{ - {"Section", true}, - {"A typical usage", true}, - {"ΔΛΞ is Greek", true}, - {"Foo 42", true}, - {"", false}, - {"section", false}, - {"A typical usage:", false}, - {"This code:", false}, - {"δ is Greek", false}, - {"Foo §", false}, - {"Fermat's Last Sentence", true}, - {"Fermat's", true}, - {"'sX", false}, - {"Ted 'Too' Bar", false}, - {"Use n+m", false}, - {"Scanning:", false}, - {"N:M", false}, -} - -func TestIsHeading(t *testing.T) { - for _, tt := range headingTests { - if h := heading(tt.line); (len(h) > 0) != tt.ok { - t.Errorf("isHeading(%q) = %v, want %v", tt.line, h, tt.ok) - } - } -} - -var blocksTests = []struct { - in string - out []block -}{ - { - in: `Para 1. -Para 1 line 2. - -Para 2. - -Section - -Para 3. - - pre - pre1 - -Para 4. - pre - pre2 -`, - out: []block{ - {opPara, []string{"Para 1.\n", "Para 1 line 2.\n"}}, - {opPara, []string{"Para 2.\n"}}, - {opHead, []string{"Section"}}, - {opPara, []string{"Para 3.\n"}}, - {opPre, []string{"pre\n", "pre1\n"}}, - {opPara, []string{"Para 4.\n"}}, - {opPre, []string{"pre\n", "pre2\n"}}, - }, - }, -} - -func TestBlocks(t *testing.T) { - for i, tt := range blocksTests { - b := blocks(tt.in) - if !reflect.DeepEqual(b, tt.out) { - t.Errorf("#%d: mismatch\nhave: %v\nwant: %v", i, b, tt.out) - } - } -} - -var emphasizeTests = []struct { - in string - out string -}{ - {"http://www.google.com/", `<a href="http://www.google.com/">http://www.google.com/</a>`}, - {"https://www.google.com/", `<a href="https://www.google.com/">https://www.google.com/</a>`}, - {"http://www.google.com/path.", `<a href="http://www.google.com/path">http://www.google.com/path</a>.`}, - {"(http://www.google.com/)", `(<a href="http://www.google.com/">http://www.google.com/</a>)`}, - {"Foo bar http://example.com/ quux!", `Foo bar <a href="http://example.com/">http://example.com/</a> quux!`}, - {"Hello http://example.com/%2f/ /world.", `Hello <a href="http://example.com/%2f/">http://example.com/%2f/</a> /world.`}, - {"Lorem http: ipsum //host/path", "Lorem http: ipsum //host/path"}, - {"javascript://is/not/linked", "javascript://is/not/linked"}, -} - -func TestEmphasize(t *testing.T) { - for i, tt := range emphasizeTests { - var buf bytes.Buffer - emphasize(&buf, tt.in, nil, true) - out := buf.String() - if out != tt.out { - t.Errorf("#%d: mismatch\nhave: %v\nwant: %v", i, out, tt.out) - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/doc/doc.go b/gcc-4.8.1/libgo/go/go/doc/doc.go deleted file mode 100644 index 9c606315d..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/doc.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package doc extracts source code documentation from a Go AST. -package doc - -import ( - "go/ast" - "go/token" -) - -// Package is the documentation for an entire package. -type Package struct { - Doc string - Name string - ImportPath string - Imports []string - Filenames []string - Bugs []string - - // declarations - Consts []*Value - Types []*Type - Vars []*Value - Funcs []*Func -} - -// Value is the documentation for a (possibly grouped) var or const declaration. -type Value struct { - Doc string - Names []string // var or const names in declaration order - Decl *ast.GenDecl - - order int -} - -// Type is the documentation for a type declaration. -type Type struct { - Doc string - Name string - Decl *ast.GenDecl - - // associated declarations - Consts []*Value // sorted list of constants of (mostly) this type - Vars []*Value // sorted list of variables of (mostly) this type - Funcs []*Func // sorted list of functions returning this type - Methods []*Func // sorted list of methods (including embedded ones) of this type -} - -// Func is the documentation for a func declaration. -type Func struct { - Doc string - Name string - Decl *ast.FuncDecl - - // methods - // (for functions, these fields have the respective zero value) - Recv string // actual receiver "T" or "*T" - Orig string // original receiver "T" or "*T" - Level int // embedding level; 0 means not embedded -} - -// Mode values control the operation of New. -type Mode int - -const ( - // extract documentation for all package-level declarations, - // not just exported ones - AllDecls Mode = 1 << iota - - // show all embedded methods, not just the ones of - // invisible (unexported) anonymous fields - AllMethods -) - -// New computes the package documentation for the given package AST. -// New takes ownership of the AST pkg and may edit or overwrite it. -// -func New(pkg *ast.Package, importPath string, mode Mode) *Package { - var r reader - r.readPackage(pkg, mode) - r.computeMethodSets() - r.cleanupTypes() - return &Package{ - Doc: r.doc, - Name: pkg.Name, - ImportPath: importPath, - Imports: sortedKeys(r.imports), - Filenames: r.filenames, - Bugs: r.bugs, - Consts: sortedValues(r.values, token.CONST), - Types: sortedTypes(r.types, mode&AllMethods != 0), - Vars: sortedValues(r.values, token.VAR), - Funcs: sortedFuncs(r.funcs, true), - } -} diff --git a/gcc-4.8.1/libgo/go/go/doc/doc_test.go b/gcc-4.8.1/libgo/go/go/doc/doc_test.go deleted file mode 100644 index 8043038b4..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/doc_test.go +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package doc - -import ( - "bytes" - "flag" - "fmt" - "go/parser" - "go/printer" - "go/token" - "io/ioutil" - "os" - "path/filepath" - "regexp" - "strings" - "testing" - "text/template" -) - -var update = flag.Bool("update", false, "update golden (.out) files") -var files = flag.String("files", "", "consider only Go test files matching this regular expression") - -const dataDir = "testdata" - -var templateTxt = readTemplate("template.txt") - -func readTemplate(filename string) *template.Template { - t := template.New(filename) - t.Funcs(template.FuncMap{ - "node": nodeFmt, - "synopsis": synopsisFmt, - }) - return template.Must(t.ParseFiles(filepath.Join(dataDir, filename))) -} - -func nodeFmt(node interface{}, fset *token.FileSet) string { - var buf bytes.Buffer - printer.Fprint(&buf, fset, node) - return strings.Replace(strings.TrimSpace(buf.String()), "\n", "\n\t", -1) -} - -func synopsisFmt(s string) string { - const n = 64 - if len(s) > n { - // cut off excess text and go back to a word boundary - s = s[0:n] - if i := strings.LastIndexAny(s, "\t\n "); i >= 0 { - s = s[0:i] - } - s = strings.TrimSpace(s) + " ..." - } - return "// " + strings.Replace(s, "\n", " ", -1) -} - -func isGoFile(fi os.FileInfo) bool { - name := fi.Name() - return !fi.IsDir() && - len(name) > 0 && name[0] != '.' && // ignore .files - filepath.Ext(name) == ".go" -} - -type bundle struct { - *Package - FSet *token.FileSet -} - -func test(t *testing.T, mode Mode) { - // determine file filter - filter := isGoFile - if *files != "" { - rx, err := regexp.Compile(*files) - if err != nil { - t.Fatal(err) - } - filter = func(fi os.FileInfo) bool { - return isGoFile(fi) && rx.MatchString(fi.Name()) - } - } - - // get packages - fset := token.NewFileSet() - pkgs, err := parser.ParseDir(fset, dataDir, filter, parser.ParseComments) - if err != nil { - t.Fatal(err) - } - - // test packages - for _, pkg := range pkgs { - importpath := dataDir + "/" + pkg.Name - doc := New(pkg, importpath, mode) - - // golden files always use / in filenames - canonicalize them - for i, filename := range doc.Filenames { - doc.Filenames[i] = filepath.ToSlash(filename) - } - - // print documentation - var buf bytes.Buffer - if err := templateTxt.Execute(&buf, bundle{doc, fset}); err != nil { - t.Error(err) - continue - } - got := buf.Bytes() - - // update golden file if necessary - golden := filepath.Join(dataDir, fmt.Sprintf("%s.%d.golden", pkg.Name, mode)) - if *update { - err := ioutil.WriteFile(golden, got, 0644) - if err != nil { - t.Error(err) - } - continue - } - - // get golden file - want, err := ioutil.ReadFile(golden) - if err != nil { - t.Error(err) - continue - } - - // compare - if !bytes.Equal(got, want) { - t.Errorf("package %s\n\tgot:\n%s\n\twant:\n%s", pkg.Name, got, want) - } - } -} - -func Test(t *testing.T) { - test(t, 0) - test(t, AllDecls) - test(t, AllMethods) -} diff --git a/gcc-4.8.1/libgo/go/go/doc/example.go b/gcc-4.8.1/libgo/go/go/doc/example.go deleted file mode 100644 index f634e1677..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/example.go +++ /dev/null @@ -1,332 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Extract example functions from file ASTs. - -package doc - -import ( - "go/ast" - "go/token" - "path" - "regexp" - "sort" - "strconv" - "strings" - "unicode" - "unicode/utf8" -) - -type Example struct { - Name string // name of the item being exemplified - Doc string // example function doc string - Code ast.Node - Play *ast.File // a whole program version of the example - Comments []*ast.CommentGroup - Output string // expected output - EmptyOutput bool // expect empty output -} - -func Examples(files ...*ast.File) []*Example { - var list []*Example - for _, file := range files { - hasTests := false // file contains tests or benchmarks - numDecl := 0 // number of non-import declarations in the file - var flist []*Example - for _, decl := range file.Decls { - if g, ok := decl.(*ast.GenDecl); ok && g.Tok != token.IMPORT { - numDecl++ - continue - } - f, ok := decl.(*ast.FuncDecl) - if !ok { - continue - } - numDecl++ - name := f.Name.Name - if isTest(name, "Test") || isTest(name, "Benchmark") { - hasTests = true - continue - } - if !isTest(name, "Example") { - continue - } - var doc string - if f.Doc != nil { - doc = f.Doc.Text() - } - output, hasOutput := exampleOutput(f.Body, file.Comments) - flist = append(flist, &Example{ - Name: name[len("Example"):], - Doc: doc, - Code: f.Body, - Play: playExample(file, f.Body), - Comments: file.Comments, - Output: output, - EmptyOutput: output == "" && hasOutput, - }) - } - if !hasTests && numDecl > 1 && len(flist) == 1 { - // If this file only has one example function, some - // other top-level declarations, and no tests or - // benchmarks, use the whole file as the example. - flist[0].Code = file - flist[0].Play = playExampleFile(file) - } - list = append(list, flist...) - } - sort.Sort(exampleByName(list)) - return list -} - -var outputPrefix = regexp.MustCompile(`(?i)^[[:space:]]*output:`) - -// Extracts the expected output and whether there was a valid output comment -func exampleOutput(b *ast.BlockStmt, comments []*ast.CommentGroup) (output string, ok bool) { - if _, last := lastComment(b, comments); last != nil { - // test that it begins with the correct prefix - text := last.Text() - if loc := outputPrefix.FindStringIndex(text); loc != nil { - text = text[loc[1]:] - // Strip zero or more spaces followed by \n or a single space. - text = strings.TrimLeft(text, " ") - if len(text) > 0 && text[0] == '\n' { - text = text[1:] - } - return text, true - } - } - return "", false // no suitable comment found -} - -// isTest tells whether name looks like a test, example, or benchmark. -// It is a Test (say) if there is a character after Test that is not a -// lower-case letter. (We don't want Testiness.) -func isTest(name, prefix string) bool { - if !strings.HasPrefix(name, prefix) { - return false - } - if len(name) == len(prefix) { // "Test" is ok - return true - } - rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) - return !unicode.IsLower(rune) -} - -type exampleByName []*Example - -func (s exampleByName) Len() int { return len(s) } -func (s exampleByName) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s exampleByName) Less(i, j int) bool { return s[i].Name < s[j].Name } - -// playExample synthesizes a new *ast.File based on the provided -// file with the provided function body as the body of main. -func playExample(file *ast.File, body *ast.BlockStmt) *ast.File { - if !strings.HasSuffix(file.Name.Name, "_test") { - // We don't support examples that are part of the - // greater package (yet). - return nil - } - - // Find top-level declarations in the file. - topDecls := make(map[*ast.Object]bool) - for _, decl := range file.Decls { - switch d := decl.(type) { - case *ast.FuncDecl: - topDecls[d.Name.Obj] = true - case *ast.GenDecl: - for _, spec := range d.Specs { - switch s := spec.(type) { - case *ast.TypeSpec: - topDecls[s.Name.Obj] = true - case *ast.ValueSpec: - for _, id := range s.Names { - topDecls[id.Obj] = true - } - } - } - } - } - - // Find unresolved identifiers and uses of top-level declarations. - unresolved := make(map[string]bool) - usesTopDecl := false - var inspectFunc func(ast.Node) bool - inspectFunc = func(n ast.Node) bool { - // For selector expressions, only inspect the left hand side. - // (For an expression like fmt.Println, only add "fmt" to the - // set of unresolved names, not "Println".) - if e, ok := n.(*ast.SelectorExpr); ok { - ast.Inspect(e.X, inspectFunc) - return false - } - if id, ok := n.(*ast.Ident); ok { - if id.Obj == nil { - unresolved[id.Name] = true - } else if topDecls[id.Obj] { - usesTopDecl = true - } - } - return true - } - ast.Inspect(body, inspectFunc) - if usesTopDecl { - // We don't support examples that are not self-contained (yet). - return nil - } - - // Remove predeclared identifiers from unresolved list. - for n := range unresolved { - if predeclaredTypes[n] || predeclaredConstants[n] || predeclaredFuncs[n] { - delete(unresolved, n) - } - } - - // Use unresolved identifiers to determine the imports used by this - // example. The heuristic assumes package names match base import - // paths for imports w/o renames (should be good enough most of the time). - namedImports := make(map[string]string) // [name]path - var blankImports []ast.Spec // _ imports - for _, s := range file.Imports { - p, err := strconv.Unquote(s.Path.Value) - if err != nil { - continue - } - n := path.Base(p) - if s.Name != nil { - n = s.Name.Name - switch n { - case "_": - blankImports = append(blankImports, s) - continue - case ".": - // We can't resolve dot imports (yet). - return nil - } - } - if unresolved[n] { - namedImports[n] = p - delete(unresolved, n) - } - } - - // If there are other unresolved identifiers, give up because this - // synthesized file is not going to build. - if len(unresolved) > 0 { - return nil - } - - // Include documentation belonging to blank imports. - var comments []*ast.CommentGroup - for _, s := range blankImports { - if c := s.(*ast.ImportSpec).Doc; c != nil { - comments = append(comments, c) - } - } - - // Include comments that are inside the function body. - for _, c := range file.Comments { - if body.Pos() <= c.Pos() && c.End() <= body.End() { - comments = append(comments, c) - } - } - - // Strip "Output:" commment and adjust body end position. - body, comments = stripOutputComment(body, comments) - - // Synthesize import declaration. - importDecl := &ast.GenDecl{ - Tok: token.IMPORT, - Lparen: 1, // Need non-zero Lparen and Rparen so that printer - Rparen: 1, // treats this as a factored import. - } - for n, p := range namedImports { - s := &ast.ImportSpec{Path: &ast.BasicLit{Value: strconv.Quote(p)}} - if path.Base(p) != n { - s.Name = ast.NewIdent(n) - } - importDecl.Specs = append(importDecl.Specs, s) - } - importDecl.Specs = append(importDecl.Specs, blankImports...) - - // Synthesize main function. - funcDecl := &ast.FuncDecl{ - Name: ast.NewIdent("main"), - Type: &ast.FuncType{}, - Body: body, - } - - // Synthesize file. - return &ast.File{ - Name: ast.NewIdent("main"), - Decls: []ast.Decl{importDecl, funcDecl}, - Comments: comments, - } -} - -// playExampleFile takes a whole file example and synthesizes a new *ast.File -// such that the example is function main in package main. -func playExampleFile(file *ast.File) *ast.File { - // Strip copyright comment if present. - comments := file.Comments - if len(comments) > 0 && strings.HasPrefix(comments[0].Text(), "Copyright") { - comments = comments[1:] - } - - // Copy declaration slice, rewriting the ExampleX function to main. - var decls []ast.Decl - for _, d := range file.Decls { - if f, ok := d.(*ast.FuncDecl); ok && isTest(f.Name.Name, "Example") { - // Copy the FuncDecl, as it may be used elsewhere. - newF := *f - newF.Name = ast.NewIdent("main") - newF.Body, comments = stripOutputComment(f.Body, comments) - d = &newF - } - decls = append(decls, d) - } - - // Copy the File, as it may be used elsewhere. - f := *file - f.Name = ast.NewIdent("main") - f.Decls = decls - f.Comments = comments - return &f -} - -// stripOutputComment finds and removes an "Output:" commment from body -// and comments, and adjusts the body block's end position. -func stripOutputComment(body *ast.BlockStmt, comments []*ast.CommentGroup) (*ast.BlockStmt, []*ast.CommentGroup) { - // Do nothing if no "Output:" comment found. - i, last := lastComment(body, comments) - if last == nil || !outputPrefix.MatchString(last.Text()) { - return body, comments - } - - // Copy body and comments, as the originals may be used elsewhere. - newBody := &ast.BlockStmt{ - Lbrace: body.Lbrace, - List: body.List, - Rbrace: last.Pos(), - } - newComments := make([]*ast.CommentGroup, len(comments)-1) - copy(newComments, comments[:i]) - copy(newComments[i:], comments[i+1:]) - return newBody, newComments -} - -// lastComment returns the last comment inside the provided block. -func lastComment(b *ast.BlockStmt, c []*ast.CommentGroup) (i int, last *ast.CommentGroup) { - pos, end := b.Pos(), b.End() - for j, cg := range c { - if cg.Pos() < pos { - continue - } - if cg.End() > end { - break - } - i, last = j, cg - } - return -} diff --git a/gcc-4.8.1/libgo/go/go/doc/example_test.go b/gcc-4.8.1/libgo/go/go/doc/example_test.go deleted file mode 100644 index b70efd93d..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/example_test.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package doc_test - -import ( - "bytes" - "go/doc" - "go/format" - "go/parser" - "go/token" - "strings" - "testing" -) - -const exampleTestFile = ` -package foo_test - -import ( - "fmt" - "log" - "os/exec" -) - -func ExampleHello() { - fmt.Println("Hello, world!") - // Output: Hello, world! -} - -func ExampleImport() { - out, err := exec.Command("date").Output() - if err != nil { - log.Fatal(err) - } - fmt.Printf("The date is %s\n", out) -} -` - -var exampleTestCases = []struct { - Name, Play, Output string -}{ - { - Name: "Hello", - Play: exampleHelloPlay, - Output: "Hello, world!\n", - }, - { - Name: "Import", - Play: exampleImportPlay, - }, -} - -const exampleHelloPlay = `package main - -import ( - "fmt" -) - -func main() { - fmt.Println("Hello, world!") -} -` -const exampleImportPlay = `package main - -import ( - "fmt" - "log" - "os/exec" -) - -func main() { - out, err := exec.Command("date").Output() - if err != nil { - log.Fatal(err) - } - fmt.Printf("The date is %s\n", out) -} -` - -func TestExamples(t *testing.T) { - fs := token.NewFileSet() - file, err := parser.ParseFile(fs, "test.go", strings.NewReader(exampleTestFile), parser.ParseComments) - if err != nil { - t.Fatal(err) - } - for i, e := range doc.Examples(file) { - c := exampleTestCases[i] - if e.Name != c.Name { - t.Errorf("got Name == %q, want %q", e.Name, c.Name) - } - if w := c.Play; w != "" { - var g string // hah - if e.Play == nil { - g = "<nil>" - } else { - b := new(bytes.Buffer) - if err := format.Node(b, fs, e.Play); err != nil { - t.Fatal(err) - } - g = b.String() - } - if g != w { - t.Errorf("%s: got Play == %q, want %q", c.Name, g, w) - } - } - if g, w := e.Output, c.Output; g != w { - t.Errorf("%s: got Output == %q, want %q", c.Name, g, w) - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/doc/exports.go b/gcc-4.8.1/libgo/go/go/doc/exports.go deleted file mode 100644 index ff01285d4..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/exports.go +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements export filtering of an AST. - -package doc - -import "go/ast" - -// filterIdentList removes unexported names from list in place -// and returns the resulting list. -// -func filterIdentList(list []*ast.Ident) []*ast.Ident { - j := 0 - for _, x := range list { - if ast.IsExported(x.Name) { - list[j] = x - j++ - } - } - return list[0:j] -} - -// removeErrorField removes anonymous fields named "error" from an interface. -// This is called when "error" has been determined to be a local name, -// not the predeclared type. -// -func removeErrorField(ityp *ast.InterfaceType) { - list := ityp.Methods.List // we know that ityp.Methods != nil - j := 0 - for _, field := range list { - keepField := true - if n := len(field.Names); n == 0 { - // anonymous field - if fname, _ := baseTypeName(field.Type); fname == "error" { - keepField = false - } - } - if keepField { - list[j] = field - j++ - } - } - if j < len(list) { - ityp.Incomplete = true - } - ityp.Methods.List = list[0:j] -} - -// filterFieldList removes unexported fields (field names) from the field list -// in place and returns true if fields were removed. Anonymous fields are -// recorded with the parent type. filterType is called with the types of -// all remaining fields. -// -func (r *reader) filterFieldList(parent *namedType, fields *ast.FieldList, ityp *ast.InterfaceType) (removedFields bool) { - if fields == nil { - return - } - list := fields.List - j := 0 - for _, field := range list { - keepField := false - if n := len(field.Names); n == 0 { - // anonymous field - fname := r.recordAnonymousField(parent, field.Type) - if ast.IsExported(fname) { - keepField = true - } else if ityp != nil && fname == "error" { - // possibly the predeclared error interface; keep - // it for now but remember this interface so that - // it can be fixed if error is also defined locally - keepField = true - r.remember(ityp) - } - } else { - field.Names = filterIdentList(field.Names) - if len(field.Names) < n { - removedFields = true - } - if len(field.Names) > 0 { - keepField = true - } - } - if keepField { - r.filterType(nil, field.Type) - list[j] = field - j++ - } - } - if j < len(list) { - removedFields = true - } - fields.List = list[0:j] - return -} - -// filterParamList applies filterType to each parameter type in fields. -// -func (r *reader) filterParamList(fields *ast.FieldList) { - if fields != nil { - for _, f := range fields.List { - r.filterType(nil, f.Type) - } - } -} - -// filterType strips any unexported struct fields or method types from typ -// in place. If fields (or methods) have been removed, the corresponding -// struct or interface type has the Incomplete field set to true. -// -func (r *reader) filterType(parent *namedType, typ ast.Expr) { - switch t := typ.(type) { - case *ast.Ident: - // nothing to do - case *ast.ParenExpr: - r.filterType(nil, t.X) - case *ast.ArrayType: - r.filterType(nil, t.Elt) - case *ast.StructType: - if r.filterFieldList(parent, t.Fields, nil) { - t.Incomplete = true - } - case *ast.FuncType: - r.filterParamList(t.Params) - r.filterParamList(t.Results) - case *ast.InterfaceType: - if r.filterFieldList(parent, t.Methods, t) { - t.Incomplete = true - } - case *ast.MapType: - r.filterType(nil, t.Key) - r.filterType(nil, t.Value) - case *ast.ChanType: - r.filterType(nil, t.Value) - } -} - -func (r *reader) filterSpec(spec ast.Spec) bool { - switch s := spec.(type) { - case *ast.ImportSpec: - // always keep imports so we can collect them - return true - case *ast.ValueSpec: - s.Names = filterIdentList(s.Names) - if len(s.Names) > 0 { - r.filterType(nil, s.Type) - return true - } - case *ast.TypeSpec: - if name := s.Name.Name; ast.IsExported(name) { - r.filterType(r.lookupType(s.Name.Name), s.Type) - return true - } else if name == "error" { - // special case: remember that error is declared locally - r.errorDecl = true - } - } - return false -} - -func (r *reader) filterSpecList(list []ast.Spec) []ast.Spec { - j := 0 - for _, s := range list { - if r.filterSpec(s) { - list[j] = s - j++ - } - } - return list[0:j] -} - -func (r *reader) filterDecl(decl ast.Decl) bool { - switch d := decl.(type) { - case *ast.GenDecl: - d.Specs = r.filterSpecList(d.Specs) - return len(d.Specs) > 0 - case *ast.FuncDecl: - // ok to filter these methods early because any - // conflicting method will be filtered here, too - - // thus, removing these methods early will not lead - // to the false removal of possible conflicts - return ast.IsExported(d.Name.Name) - } - return false -} - -// fileExports removes unexported declarations from src in place. -// -func (r *reader) fileExports(src *ast.File) { - j := 0 - for _, d := range src.Decls { - if r.filterDecl(d) { - src.Decls[j] = d - j++ - } - } - src.Decls = src.Decls[0:j] -} diff --git a/gcc-4.8.1/libgo/go/go/doc/filter.go b/gcc-4.8.1/libgo/go/go/doc/filter.go deleted file mode 100644 index 02b66ccef..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/filter.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package doc - -import "go/ast" - -type Filter func(string) bool - -func matchFields(fields *ast.FieldList, f Filter) bool { - if fields != nil { - for _, field := range fields.List { - for _, name := range field.Names { - if f(name.Name) { - return true - } - } - } - } - return false -} - -func matchDecl(d *ast.GenDecl, f Filter) bool { - for _, d := range d.Specs { - switch v := d.(type) { - case *ast.ValueSpec: - for _, name := range v.Names { - if f(name.Name) { - return true - } - } - case *ast.TypeSpec: - if f(v.Name.Name) { - return true - } - switch t := v.Type.(type) { - case *ast.StructType: - if matchFields(t.Fields, f) { - return true - } - case *ast.InterfaceType: - if matchFields(t.Methods, f) { - return true - } - } - } - } - return false -} - -func filterValues(a []*Value, f Filter) []*Value { - w := 0 - for _, vd := range a { - if matchDecl(vd.Decl, f) { - a[w] = vd - w++ - } - } - return a[0:w] -} - -func filterFuncs(a []*Func, f Filter) []*Func { - w := 0 - for _, fd := range a { - if f(fd.Name) { - a[w] = fd - w++ - } - } - return a[0:w] -} - -func filterTypes(a []*Type, f Filter) []*Type { - w := 0 - for _, td := range a { - n := 0 // number of matches - if matchDecl(td.Decl, f) { - n = 1 - } else { - // type name doesn't match, but we may have matching consts, vars, factories or methods - td.Consts = filterValues(td.Consts, f) - td.Vars = filterValues(td.Vars, f) - td.Funcs = filterFuncs(td.Funcs, f) - td.Methods = filterFuncs(td.Methods, f) - n += len(td.Consts) + len(td.Vars) + len(td.Funcs) + len(td.Methods) - } - if n > 0 { - a[w] = td - w++ - } - } - return a[0:w] -} - -// Filter eliminates documentation for names that don't pass through the filter f. -// TODO: Recognize "Type.Method" as a name. -// -func (p *Package) Filter(f Filter) { - p.Consts = filterValues(p.Consts, f) - p.Vars = filterValues(p.Vars, f) - p.Types = filterTypes(p.Types, f) - p.Funcs = filterFuncs(p.Funcs, f) - p.Doc = "" // don't show top-level package doc -} diff --git a/gcc-4.8.1/libgo/go/go/doc/headscan.go b/gcc-4.8.1/libgo/go/go/doc/headscan.go deleted file mode 100644 index f55934763..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/headscan.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* - The headscan command extracts comment headings from package files; - it is used to detect false positives which may require an adjustment - to the comment formatting heuristics in comment.go. - - Usage: headscan [-root root_directory] - - By default, the $GOROOT/src directory is scanned. -*/ -package main - -import ( - "bytes" - "flag" - "fmt" - "go/doc" - "go/parser" - "go/token" - "os" - "path/filepath" - "runtime" - "strings" -) - -var ( - root = flag.String("root", filepath.Join(runtime.GOROOT(), "src"), "root of filesystem tree to scan") - verbose = flag.Bool("v", false, "verbose mode") -) - -const ( - html_h = "<h3>" - html_endh = "</h3>\n" -) - -func isGoFile(fi os.FileInfo) bool { - return strings.HasSuffix(fi.Name(), ".go") && - !strings.HasSuffix(fi.Name(), "_test.go") -} - -func appendHeadings(list []string, comment string) []string { - var buf bytes.Buffer - doc.ToHTML(&buf, comment, nil) - for s := buf.String(); ; { - i := strings.Index(s, html_h) - if i < 0 { - break - } - i += len(html_h) - j := strings.Index(s, html_endh) - if j < 0 { - list = append(list, s[i:]) // incorrect HTML - break - } - list = append(list, s[i:j]) - s = s[j+len(html_endh):] - } - return list -} - -func main() { - flag.Parse() - fset := token.NewFileSet() - nheadings := 0 - err := filepath.Walk(*root, func(path string, fi os.FileInfo, err error) error { - if !fi.IsDir() { - return nil - } - pkgs, err := parser.ParseDir(fset, path, isGoFile, parser.ParseComments) - if err != nil { - if *verbose { - fmt.Fprintln(os.Stderr, err) - } - return nil - } - for _, pkg := range pkgs { - d := doc.New(pkg, path, doc.Mode(0)) - list := appendHeadings(nil, d.Doc) - for _, d := range d.Consts { - list = appendHeadings(list, d.Doc) - } - for _, d := range d.Types { - list = appendHeadings(list, d.Doc) - } - for _, d := range d.Vars { - list = appendHeadings(list, d.Doc) - } - for _, d := range d.Funcs { - list = appendHeadings(list, d.Doc) - } - if len(list) > 0 { - // directories may contain multiple packages; - // print path and package name - fmt.Printf("%s (package %s)\n", path, pkg.Name) - for _, h := range list { - fmt.Printf("\t%s\n", h) - } - nheadings += len(list) - } - } - return nil - }) - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - fmt.Println(nheadings, "headings found") -} diff --git a/gcc-4.8.1/libgo/go/go/doc/reader.go b/gcc-4.8.1/libgo/go/go/doc/reader.go deleted file mode 100644 index fafd8f98e..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/reader.go +++ /dev/null @@ -1,802 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package doc - -import ( - "go/ast" - "go/token" - "regexp" - "sort" - "strconv" -) - -// ---------------------------------------------------------------------------- -// function/method sets -// -// Internally, we treat functions like methods and collect them in method sets. - -// A methodSet describes a set of methods. Entries where Decl == nil are conflict -// entries (more then one method with the same name at the same embedding level). -// -type methodSet map[string]*Func - -// recvString returns a string representation of recv of the -// form "T", "*T", or "BADRECV" (if not a proper receiver type). -// -func recvString(recv ast.Expr) string { - switch t := recv.(type) { - case *ast.Ident: - return t.Name - case *ast.StarExpr: - return "*" + recvString(t.X) - } - return "BADRECV" -} - -// set creates the corresponding Func for f and adds it to mset. -// If there are multiple f's with the same name, set keeps the first -// one with documentation; conflicts are ignored. -// -func (mset methodSet) set(f *ast.FuncDecl) { - name := f.Name.Name - if g := mset[name]; g != nil && g.Doc != "" { - // A function with the same name has already been registered; - // since it has documentation, assume f is simply another - // implementation and ignore it. This does not happen if the - // caller is using go/build.ScanDir to determine the list of - // files implementing a package. - return - } - // function doesn't exist or has no documentation; use f - recv := "" - if f.Recv != nil { - var typ ast.Expr - // be careful in case of incorrect ASTs - if list := f.Recv.List; len(list) == 1 { - typ = list[0].Type - } - recv = recvString(typ) - } - mset[name] = &Func{ - Doc: f.Doc.Text(), - Name: name, - Decl: f, - Recv: recv, - Orig: recv, - } - f.Doc = nil // doc consumed - remove from AST -} - -// add adds method m to the method set; m is ignored if the method set -// already contains a method with the same name at the same or a higher -// level then m. -// -func (mset methodSet) add(m *Func) { - old := mset[m.Name] - if old == nil || m.Level < old.Level { - mset[m.Name] = m - return - } - if old != nil && m.Level == old.Level { - // conflict - mark it using a method with nil Decl - mset[m.Name] = &Func{ - Name: m.Name, - Level: m.Level, - } - } -} - -// ---------------------------------------------------------------------------- -// Named types - -// baseTypeName returns the name of the base type of x (or "") -// and whether the type is imported or not. -// -func baseTypeName(x ast.Expr) (name string, imported bool) { - switch t := x.(type) { - case *ast.Ident: - return t.Name, false - case *ast.SelectorExpr: - if _, ok := t.X.(*ast.Ident); ok { - // only possible for qualified type names; - // assume type is imported - return t.Sel.Name, true - } - case *ast.StarExpr: - return baseTypeName(t.X) - } - return -} - -// An embeddedSet describes a set of embedded types. -type embeddedSet map[*namedType]bool - -// A namedType represents a named unqualified (package local, or possibly -// predeclared) type. The namedType for a type name is always found via -// reader.lookupType. -// -type namedType struct { - doc string // doc comment for type - name string // type name - decl *ast.GenDecl // nil if declaration hasn't been seen yet - - isEmbedded bool // true if this type is embedded - isStruct bool // true if this type is a struct - embedded embeddedSet // true if the embedded type is a pointer - - // associated declarations - values []*Value // consts and vars - funcs methodSet - methods methodSet -} - -// ---------------------------------------------------------------------------- -// AST reader - -// reader accumulates documentation for a single package. -// It modifies the AST: Comments (declaration documentation) -// that have been collected by the reader are set to nil -// in the respective AST nodes so that they are not printed -// twice (once when printing the documentation and once when -// printing the corresponding AST node). -// -type reader struct { - mode Mode - - // package properties - doc string // package documentation, if any - filenames []string - bugs []string - - // declarations - imports map[string]int - values []*Value // consts and vars - types map[string]*namedType - funcs methodSet - - // support for package-local error type declarations - errorDecl bool // if set, type "error" was declared locally - fixlist []*ast.InterfaceType // list of interfaces containing anonymous field "error" -} - -func (r *reader) isVisible(name string) bool { - return r.mode&AllDecls != 0 || ast.IsExported(name) -} - -// lookupType returns the base type with the given name. -// If the base type has not been encountered yet, a new -// type with the given name but no associated declaration -// is added to the type map. -// -func (r *reader) lookupType(name string) *namedType { - if name == "" || name == "_" { - return nil // no type docs for anonymous types - } - if typ, found := r.types[name]; found { - return typ - } - // type not found - add one without declaration - typ := &namedType{ - name: name, - embedded: make(embeddedSet), - funcs: make(methodSet), - methods: make(methodSet), - } - r.types[name] = typ - return typ -} - -// recordAnonymousField registers fieldType as the type of an -// anonymous field in the parent type. If the field is imported -// (qualified name) or the parent is nil, the field is ignored. -// The function returns the field name. -// -func (r *reader) recordAnonymousField(parent *namedType, fieldType ast.Expr) (fname string) { - fname, imp := baseTypeName(fieldType) - if parent == nil || imp { - return - } - if ftype := r.lookupType(fname); ftype != nil { - ftype.isEmbedded = true - _, ptr := fieldType.(*ast.StarExpr) - parent.embedded[ftype] = ptr - } - return -} - -func (r *reader) readDoc(comment *ast.CommentGroup) { - // By convention there should be only one package comment - // but collect all of them if there are more then one. - text := comment.Text() - if r.doc == "" { - r.doc = text - return - } - r.doc += "\n" + text -} - -func (r *reader) remember(typ *ast.InterfaceType) { - r.fixlist = append(r.fixlist, typ) -} - -func specNames(specs []ast.Spec) []string { - names := make([]string, 0, len(specs)) // reasonable estimate - for _, s := range specs { - // s guaranteed to be an *ast.ValueSpec by readValue - for _, ident := range s.(*ast.ValueSpec).Names { - names = append(names, ident.Name) - } - } - return names -} - -// readValue processes a const or var declaration. -// -func (r *reader) readValue(decl *ast.GenDecl) { - // determine if decl should be associated with a type - // 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 := "" - n := 0 - for _, spec := range decl.Specs { - s, ok := spec.(*ast.ValueSpec) - if !ok { - continue // should not happen, but be conservative - } - name := "" - switch { - case s.Type != nil: - // a type is present; determine its name - if n, imp := baseTypeName(s.Type); !imp { - name = n - } - case decl.Tok == token.CONST: - // no type is present but we have a constant declaration; - // use the previous type name (w/o more type information - // we cannot handle the case of unnamed variables with - // initializer expressions except for some trivial cases) - name = prev - } - if name != "" { - // entry has a named type - if domName != "" && domName != name { - // more than one type name - do not associate - // with any type - domName = "" - break - } - domName = name - domFreq++ - } - prev = name - n++ - } - - // nothing to do w/o a legal declaration - if n == 0 { - return - } - - // determine values list with which to associate the Value for this decl - values := &r.values - const threshold = 0.75 - if domName != "" && r.isVisible(domName) && domFreq >= int(float64(len(decl.Specs))*threshold) { - // typed entries are sufficiently frequent - if typ := r.lookupType(domName); typ != nil { - values = &typ.values // associate with that type - } - } - - *values = append(*values, &Value{ - Doc: decl.Doc.Text(), - Names: specNames(decl.Specs), - Decl: decl, - order: len(*values), - }) - decl.Doc = nil // doc consumed - remove from AST -} - -// fields returns a struct's fields or an interface's methods. -// -func fields(typ ast.Expr) (list []*ast.Field, isStruct bool) { - var fields *ast.FieldList - switch t := typ.(type) { - case *ast.StructType: - fields = t.Fields - isStruct = true - case *ast.InterfaceType: - fields = t.Methods - } - if fields != nil { - list = fields.List - } - return -} - -// readType processes a type declaration. -// -func (r *reader) readType(decl *ast.GenDecl, spec *ast.TypeSpec) { - typ := r.lookupType(spec.Name.Name) - if typ == nil { - return // no name or blank name - ignore the type - } - - // A type should be added at most once, so typ.decl - // should be nil - if it is not, simply overwrite it. - typ.decl = decl - - // compute documentation - doc := spec.Doc - spec.Doc = nil // doc consumed - remove from AST - 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 - typ.doc = doc.Text() - - // record anonymous fields (they may contribute methods) - // (some fields may have been recorded already when filtering - // exports, but that's ok) - var list []*ast.Field - list, typ.isStruct = fields(spec.Type) - for _, field := range list { - if len(field.Names) == 0 { - r.recordAnonymousField(typ, field.Type) - } - } -} - -// readFunc processes a func or method declaration. -// -func (r *reader) readFunc(fun *ast.FuncDecl) { - // strip function body - fun.Body = nil - - // associate methods with the receiver type, if any - if fun.Recv != nil { - // method - recvTypeName, imp := baseTypeName(fun.Recv.List[0].Type) - if imp { - // should not happen (incorrect AST); - // don't show this method - return - } - if typ := r.lookupType(recvTypeName); typ != nil { - typ.methods.set(fun) - } - // otherwise ignore the method - // TODO(gri): There may be exported methods of non-exported types - // 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 - } - - // associate factory functions with the first visible result type, if any - if fun.Type.Results.NumFields() >= 1 { - res := fun.Type.Results.List[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) - if n, imp := baseTypeName(res.Type); !imp && r.isVisible(n) { - if typ := r.lookupType(n); typ != nil { - // associate function with typ - typ.funcs.set(fun) - return - } - } - } - } - - // just an ordinary function - r.funcs.set(fun) -} - -var ( - bug_markers = regexp.MustCompile("^/[/*][ \t]*BUG\\(.*\\):[ \t]*") // BUG(uid): - bug_content = regexp.MustCompile("[^ \n\r\t]+") // at least one non-whitespace char -) - -// readFile adds the AST for a source file to the reader. -// -func (r *reader) readFile(src *ast.File) { - // add package documentation - if src.Doc != nil { - r.readDoc(src.Doc) - src.Doc = nil // doc consumed - remove from AST - } - - // add all declarations - for _, decl := range src.Decls { - switch d := decl.(type) { - case *ast.GenDecl: - switch d.Tok { - case token.IMPORT: - // imports are handled individually - for _, spec := range d.Specs { - if s, ok := spec.(*ast.ImportSpec); ok { - if import_, err := strconv.Unquote(s.Path.Value); err == nil { - r.imports[import_] = 1 - } - } - } - case token.CONST, token.VAR: - // constants and variables are always handled as a group - r.readValue(d) - case token.TYPE: - // types are handled individually - if len(d.Specs) == 1 && !d.Lparen.IsValid() { - // common case: single declaration w/o parentheses - // (if a single declaration is parenthesized, - // create a new fake declaration below, so that - // go/doc type declarations always appear w/o - // parentheses) - if s, ok := d.Specs[0].(*ast.TypeSpec); ok { - r.readType(d, s) - } - break - } - for _, spec := range d.Specs { - if s, ok := spec.(*ast.TypeSpec); ok { - // use an individual (possibly fake) declaration - // for each type; this also ensures that each type - // gets to (re-)use the declaration documentation - // if there's none associated with the spec itself - fake := &ast.GenDecl{ - Doc: d.Doc, - // don't use the existing TokPos because it - // will lead to the wrong selection range for - // the fake declaration if there are more - // than one type in the group (this affects - // src/cmd/godoc/godoc.go's posLink_urlFunc) - TokPos: s.Pos(), - Tok: token.TYPE, - Specs: []ast.Spec{s}, - } - r.readType(fake, s) - } - } - } - case *ast.FuncDecl: - r.readFunc(d) - } - } - - // collect BUG(...) comments - for _, c := range src.Comments { - text := c.List[0].Text - if m := bug_markers.FindStringIndex(text); m != nil { - // found a BUG comment; maybe empty - if btxt := text[m[1]:]; bug_content.MatchString(btxt) { - // non-empty BUG comment; collect comment without BUG prefix - list := append([]*ast.Comment(nil), c.List...) // make a copy - list[0].Text = text[m[1]:] - r.bugs = append(r.bugs, (&ast.CommentGroup{List: list}).Text()) - } - } - } - src.Comments = nil // consumed unassociated comments - remove from AST -} - -func (r *reader) readPackage(pkg *ast.Package, mode Mode) { - // initialize reader - r.filenames = make([]string, len(pkg.Files)) - r.imports = make(map[string]int) - r.mode = mode - r.types = make(map[string]*namedType) - r.funcs = make(methodSet) - - // sort package files before reading them so that the - // result does not depend on map iteration order - i := 0 - for filename := range pkg.Files { - r.filenames[i] = filename - i++ - } - sort.Strings(r.filenames) - - // process files in sorted order - for _, filename := range r.filenames { - f := pkg.Files[filename] - if mode&AllDecls == 0 { - r.fileExports(f) - } - r.readFile(f) - } -} - -// ---------------------------------------------------------------------------- -// Types - -func customizeRecv(f *Func, recvTypeName string, embeddedIsPtr bool, level int) *Func { - if f == nil || f.Decl == nil || f.Decl.Recv == nil || len(f.Decl.Recv.List) != 1 { - return f // shouldn't happen, but be safe - } - - // copy existing receiver field and set new type - newField := *f.Decl.Recv.List[0] - _, origRecvIsPtr := newField.Type.(*ast.StarExpr) - var typ ast.Expr = ast.NewIdent(recvTypeName) - if !embeddedIsPtr && origRecvIsPtr { - typ = &ast.StarExpr{X: typ} - } - newField.Type = typ - - // copy existing receiver field list and set new receiver field - newFieldList := *f.Decl.Recv - newFieldList.List = []*ast.Field{&newField} - - // copy existing function declaration and set new receiver field list - newFuncDecl := *f.Decl - newFuncDecl.Recv = &newFieldList - - // copy existing function documentation and set new declaration - newF := *f - newF.Decl = &newFuncDecl - newF.Recv = recvString(typ) - // the Orig field never changes - newF.Level = level - - return &newF -} - -// collectEmbeddedMethods collects the embedded methods of typ in mset. -// -func (r *reader) collectEmbeddedMethods(mset methodSet, typ *namedType, recvTypeName string, embeddedIsPtr bool, level int, visited embeddedSet) { - visited[typ] = true - for embedded, isPtr := range typ.embedded { - // Once an embedded type is embedded as a pointer type - // all embedded types in those types are treated like - // pointer types for the purpose of the receiver type - // computation; i.e., embeddedIsPtr is sticky for this - // embedding hierarchy. - thisEmbeddedIsPtr := embeddedIsPtr || isPtr - for _, m := range embedded.methods { - // only top-level methods are embedded - if m.Level == 0 { - mset.add(customizeRecv(m, recvTypeName, thisEmbeddedIsPtr, level)) - } - } - if !visited[embedded] { - r.collectEmbeddedMethods(mset, embedded, recvTypeName, thisEmbeddedIsPtr, level+1, visited) - } - } - delete(visited, typ) -} - -// computeMethodSets determines the actual method sets for each type encountered. -// -func (r *reader) computeMethodSets() { - for _, t := range r.types { - // collect embedded methods for t - if t.isStruct { - // struct - r.collectEmbeddedMethods(t.methods, t, t.name, false, 1, make(embeddedSet)) - } else { - // interface - // TODO(gri) fix this - } - } - - // if error was declared locally, don't treat it as exported field anymore - if r.errorDecl { - for _, ityp := range r.fixlist { - removeErrorField(ityp) - } - } -} - -// cleanupTypes removes the association of functions and methods with -// types that have no declaration. Instead, these functions and methods -// are shown at the package level. It also removes types with missing -// declarations or which are not visible. -// -func (r *reader) cleanupTypes() { - for _, t := range r.types { - visible := r.isVisible(t.name) - if t.decl == nil && (predeclaredTypes[t.name] || t.isEmbedded && visible) { - // t.name is a predeclared type (and was not redeclared in this package), - // or it was embedded somewhere but its declaration is missing (because - // the AST is incomplete): move any associated values, funcs, and methods - // back to the top-level so that they are not lost. - // 1) move values - r.values = append(r.values, t.values...) - // 2) move factory functions - for name, f := range t.funcs { - // in a correct AST, package-level function names - // are all different - no need to check for conflicts - r.funcs[name] = f - } - // 3) move methods - for name, m := range t.methods { - // don't overwrite functions with the same name - drop them - if _, found := r.funcs[name]; !found { - r.funcs[name] = m - } - } - } - // remove types w/o declaration or which are not visible - if t.decl == nil || !visible { - delete(r.types, t.name) - } - } -} - -// ---------------------------------------------------------------------------- -// Sorting - -type data struct { - n int - swap func(i, j int) - less func(i, j int) bool -} - -func (d *data) Len() int { return d.n } -func (d *data) Swap(i, j int) { d.swap(i, j) } -func (d *data) Less(i, j int) bool { return d.less(i, j) } - -// sortBy is a helper function for sorting -func sortBy(less func(i, j int) bool, swap func(i, j int), n int) { - sort.Sort(&data{n, swap, less}) -} - -func sortedKeys(m map[string]int) []string { - list := make([]string, len(m)) - i := 0 - for key := range m { - list[i] = key - i++ - } - sort.Strings(list) - return list -} - -// sortingName returns the name to use when sorting d into place. -// -func sortingName(d *ast.GenDecl) string { - if len(d.Specs) == 1 { - if s, ok := d.Specs[0].(*ast.ValueSpec); ok { - return s.Names[0].Name - } - } - return "" -} - -func sortedValues(m []*Value, tok token.Token) []*Value { - list := make([]*Value, len(m)) // big enough in any case - i := 0 - for _, val := range m { - if val.Decl.Tok == tok { - list[i] = val - i++ - } - } - list = list[0:i] - - sortBy( - func(i, j int) bool { - if ni, nj := sortingName(list[i].Decl), sortingName(list[j].Decl); ni != nj { - return ni < nj - } - return list[i].order < list[j].order - }, - func(i, j int) { list[i], list[j] = list[j], list[i] }, - len(list), - ) - - return list -} - -func sortedTypes(m map[string]*namedType, allMethods bool) []*Type { - list := make([]*Type, len(m)) - i := 0 - for _, t := range m { - list[i] = &Type{ - Doc: t.doc, - Name: t.name, - Decl: t.decl, - Consts: sortedValues(t.values, token.CONST), - Vars: sortedValues(t.values, token.VAR), - Funcs: sortedFuncs(t.funcs, true), - Methods: sortedFuncs(t.methods, allMethods), - } - i++ - } - - sortBy( - func(i, j int) bool { return list[i].Name < list[j].Name }, - func(i, j int) { list[i], list[j] = list[j], list[i] }, - len(list), - ) - - return list -} - -func removeStar(s string) string { - if len(s) > 0 && s[0] == '*' { - return s[1:] - } - return s -} - -func sortedFuncs(m methodSet, allMethods bool) []*Func { - list := make([]*Func, len(m)) - i := 0 - for _, m := range m { - // determine which methods to include - switch { - case m.Decl == nil: - // exclude conflict entry - case allMethods, m.Level == 0, !ast.IsExported(removeStar(m.Orig)): - // forced inclusion, method not embedded, or method - // embedded but original receiver type not exported - list[i] = m - i++ - } - } - list = list[0:i] - sortBy( - func(i, j int) bool { return list[i].Name < list[j].Name }, - func(i, j int) { list[i], list[j] = list[j], list[i] }, - len(list), - ) - return list -} - -// ---------------------------------------------------------------------------- -// Predeclared identifiers - -var predeclaredTypes = map[string]bool{ - "bool": true, - "byte": true, - "complex64": true, - "complex128": true, - "error": true, - "float32": true, - "float64": true, - "int": true, - "int8": true, - "int16": true, - "int32": true, - "int64": true, - "rune": true, - "string": true, - "uint": true, - "uint8": true, - "uint16": true, - "uint32": true, - "uint64": true, - "uintptr": true, -} - -var predeclaredFuncs = map[string]bool{ - "append": true, - "cap": true, - "close": true, - "complex": true, - "copy": true, - "delete": true, - "imag": true, - "len": true, - "make": true, - "new": true, - "panic": true, - "print": true, - "println": true, - "real": true, - "recover": true, -} - -var predeclaredConstants = map[string]bool{ - "false": true, - "iota": true, - "nil": true, - "true": true, -} diff --git a/gcc-4.8.1/libgo/go/go/doc/synopsis.go b/gcc-4.8.1/libgo/go/go/doc/synopsis.go deleted file mode 100644 index 2d1817439..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/synopsis.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package doc - -import ( - "strings" - "unicode" -) - -// firstSentenceLen returns the length of the first sentence in s. -// The sentence ends after the first period followed by space and -// not preceded by exactly one uppercase letter. -// -func firstSentenceLen(s string) int { - var ppp, pp, p rune - for i, q := range s { - if q == '\n' || q == '\r' || q == '\t' { - q = ' ' - } - if q == ' ' && p == '.' && (!unicode.IsUpper(pp) || unicode.IsUpper(ppp)) { - return i - } - ppp, pp, p = pp, p, q - } - return len(s) -} - -// clean replaces each sequence of space, \n, \r, or \t characters -// with a single space and removes any trailing and leading spaces. -func clean(s string) string { - var b []byte - p := byte(' ') - for i := 0; i < len(s); i++ { - q := s[i] - if q == '\n' || q == '\r' || q == '\t' { - q = ' ' - } - if q != ' ' || p != ' ' { - b = append(b, q) - p = q - } - } - // remove trailing blank, if any - if n := len(b); n > 0 && p == ' ' { - b = b[0 : n-1] - } - return string(b) -} - -// Synopsis returns a cleaned version of the first sentence in s. -// That sentence ends after the first period followed by space and -// not preceded by exactly one uppercase letter. The result string -// has no \n, \r, or \t characters and uses only single spaces between -// words. If s starts with any of the IllegalPrefixes, the result -// is the empty string. -// -func Synopsis(s string) string { - s = clean(s[0:firstSentenceLen(s)]) - for _, prefix := range IllegalPrefixes { - if strings.HasPrefix(strings.ToLower(s), prefix) { - return "" - } - } - return s -} - -var IllegalPrefixes = []string{ - "copyright", - "all rights", - "author", -} diff --git a/gcc-4.8.1/libgo/go/go/doc/synopsis_test.go b/gcc-4.8.1/libgo/go/go/doc/synopsis_test.go deleted file mode 100644 index fd7081a07..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/synopsis_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package doc - -import "testing" - -var tests = []struct { - txt string - fsl int - syn string -}{ - {"", 0, ""}, - {"foo", 3, "foo"}, - {"foo.", 4, "foo."}, - {"foo.bar", 7, "foo.bar"}, - {" foo. ", 6, "foo."}, - {" foo\t bar.\n", 12, "foo bar."}, - {" foo\t bar.\n", 12, "foo bar."}, - {"a b\n\nc\r\rd\t\t", 12, "a b c d"}, - {"a b\n\nc\r\rd\t\t . BLA", 15, "a b c d ."}, - {"Package poems by T.S.Eliot. To rhyme...", 27, "Package poems by T.S.Eliot."}, - {"Package poems by T. S. Eliot. To rhyme...", 29, "Package poems by T. S. Eliot."}, - {"foo implements the foo ABI. The foo ABI is...", 27, "foo implements the foo ABI."}, - {"Package\nfoo. ..", 12, "Package foo."}, - {"P . Q.", 3, "P ."}, - {"P. Q. ", 8, "P. Q."}, - {"Package Καλημέρα κόσμε.", 36, "Package Καλημέρα κόσμε."}, - {"Package こんにちは 世界\n", 31, "Package こんにちは 世界"}, - {"Package foo does bar.", 21, "Package foo does bar."}, - {"Copyright 2012 Google, Inc. Package foo does bar.", 27, ""}, - {"All Rights reserved. Package foo does bar.", 20, ""}, - {"All rights reserved. Package foo does bar.", 20, ""}, - {"Authors: foo@bar.com. Package foo does bar.", 21, ""}, -} - -func TestSynopsis(t *testing.T) { - for _, e := range tests { - fsl := firstSentenceLen(e.txt) - if fsl != e.fsl { - t.Errorf("got fsl = %d; want %d for %q\n", fsl, e.fsl, e.txt) - } - syn := Synopsis(e.txt) - if syn != e.syn { - t.Errorf("got syn = %q; want %q for %q\n", syn, e.syn, e.txt) - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/a.0.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/a.0.golden deleted file mode 100644 index 24db02d34..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/a.0.golden +++ /dev/null @@ -1,13 +0,0 @@ -// comment 0 comment 1 -PACKAGE a - -IMPORTPATH - testdata/a - -FILENAMES - testdata/a0.go - testdata/a1.go - -BUGS - // bug0 - // bug1 diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/a.1.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/a.1.golden deleted file mode 100644 index 24db02d34..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/a.1.golden +++ /dev/null @@ -1,13 +0,0 @@ -// comment 0 comment 1 -PACKAGE a - -IMPORTPATH - testdata/a - -FILENAMES - testdata/a0.go - testdata/a1.go - -BUGS - // bug0 - // bug1 diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/a.2.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/a.2.golden deleted file mode 100644 index 24db02d34..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/a.2.golden +++ /dev/null @@ -1,13 +0,0 @@ -// comment 0 comment 1 -PACKAGE a - -IMPORTPATH - testdata/a - -FILENAMES - testdata/a0.go - testdata/a1.go - -BUGS - // bug0 - // bug1 diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/a0.go b/gcc-4.8.1/libgo/go/go/doc/testdata/a0.go deleted file mode 100644 index dc552989e..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/a0.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// comment 0 -package a - -//BUG(uid): bug0 diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/a1.go b/gcc-4.8.1/libgo/go/go/doc/testdata/a1.go deleted file mode 100644 index 098776c1b..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/a1.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// comment 1 -package a - -//BUG(uid): bug1 diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/b.0.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/b.0.golden deleted file mode 100644 index 9d93392ea..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/b.0.golden +++ /dev/null @@ -1,71 +0,0 @@ -// -PACKAGE b - -IMPORTPATH - testdata/b - -IMPORTS - a - -FILENAMES - testdata/b.go - -CONSTANTS - // - const ( - C1 notExported = iota - C2 - - C4 - C5 - ) - - // - const C notExported = 0 - - // - const Pi = 3.14 // Pi - - -VARIABLES - // - var ( - U1, U2, U4, U5 notExported - - U7 notExported = 7 - ) - - // - var MaxInt int // MaxInt - - // - var V notExported - - // - var V1, V2, V4, V5 notExported - - -FUNCTIONS - // - func F(x int) int - - // - func F1() notExported - - // Always under the package functions list. - func NotAFactory() int - - // Associated with uint type if AllDecls is set. - func UintFactory() uint - - -TYPES - // - type T struct{} // T - - // - var V T // v - - // - func (x *T) M() - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/b.1.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/b.1.golden deleted file mode 100644 index 66c47b5c2..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/b.1.golden +++ /dev/null @@ -1,83 +0,0 @@ -// -PACKAGE b - -IMPORTPATH - testdata/b - -IMPORTS - a - -FILENAMES - testdata/b.go - -CONSTANTS - // - const Pi = 3.14 // Pi - - -VARIABLES - // - var MaxInt int // MaxInt - - -FUNCTIONS - // - func F(x int) int - - // Always under the package functions list. - func NotAFactory() int - - -TYPES - // - type T struct{} // T - - // - var V T // v - - // - func (x *T) M() - - // - type notExported int - - // - const ( - C1 notExported = iota - C2 - c3 - C4 - C5 - ) - - // - const C notExported = 0 - - // - var ( - U1, U2, u3, U4, U5 notExported - u6 notExported - U7 notExported = 7 - ) - - // - var V notExported - - // - var V1, V2, v3, V4, V5 notExported - - // - func F1() notExported - - // - func f2() notExported - - // Should only appear if AllDecls is set. - type uint struct{} // overrides a predeclared type uint - - // Associated with uint type if AllDecls is set. - func UintFactory() uint - - // Associated with uint type if AllDecls is set. - func uintFactory() uint - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/b.2.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/b.2.golden deleted file mode 100644 index 9d93392ea..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/b.2.golden +++ /dev/null @@ -1,71 +0,0 @@ -// -PACKAGE b - -IMPORTPATH - testdata/b - -IMPORTS - a - -FILENAMES - testdata/b.go - -CONSTANTS - // - const ( - C1 notExported = iota - C2 - - C4 - C5 - ) - - // - const C notExported = 0 - - // - const Pi = 3.14 // Pi - - -VARIABLES - // - var ( - U1, U2, U4, U5 notExported - - U7 notExported = 7 - ) - - // - var MaxInt int // MaxInt - - // - var V notExported - - // - var V1, V2, V4, V5 notExported - - -FUNCTIONS - // - func F(x int) int - - // - func F1() notExported - - // Always under the package functions list. - func NotAFactory() int - - // Associated with uint type if AllDecls is set. - func UintFactory() uint - - -TYPES - // - type T struct{} // T - - // - var V T // v - - // - func (x *T) M() - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/b.go b/gcc-4.8.1/libgo/go/go/doc/testdata/b.go deleted file mode 100644 index e50663b3d..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/b.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package b - -import "a" - -// ---------------------------------------------------------------------------- -// Basic declarations - -const Pi = 3.14 // Pi -var MaxInt int // MaxInt -type T struct{} // T -var V T // v -func F(x int) int {} // F -func (x *T) M() {} // M - -// Corner cases: association with (presumed) predeclared types - -// Always under the package functions list. -func NotAFactory() int {} - -// Associated with uint type if AllDecls is set. -func UintFactory() uint {} - -// Associated with uint type if AllDecls is set. -func uintFactory() uint {} - -// Should only appear if AllDecls is set. -type uint struct{} // overrides a predeclared type uint - -// ---------------------------------------------------------------------------- -// Exported declarations associated with non-exported types must always be shown. - -type notExported int - -const C notExported = 0 - -const ( - C1 notExported = iota - C2 - c3 - C4 - C5 -) - -var V notExported -var V1, V2, v3, V4, V5 notExported - -var ( - U1, U2, u3, U4, U5 notExported - u6 notExported - U7 notExported = 7 -) - -func F1() notExported {} -func f2() notExported {} diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/benchmark.go b/gcc-4.8.1/libgo/go/go/doc/testdata/benchmark.go deleted file mode 100644 index 905e49644..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/benchmark.go +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package testing - -import ( - "flag" - "fmt" - "os" - "runtime" - "time" -) - -var matchBenchmarks = flag.String("test.bench", "", "regular expression to select benchmarks to run") -var benchTime = flag.Duration("test.benchtime", 1*time.Second, "approximate run time for each benchmark") - -// An internal type but exported because it is cross-package; part of the implementation -// of go test. -type InternalBenchmark struct { - Name string - F func(b *B) -} - -// B is a type passed to Benchmark functions to manage benchmark -// timing and to specify the number of iterations to run. -type B struct { - common - N int - benchmark InternalBenchmark - bytes int64 - timerOn bool - result BenchmarkResult -} - -// StartTimer starts timing a test. This function is called automatically -// before a benchmark starts, but it can also used to resume timing after -// a call to StopTimer. -func (b *B) StartTimer() { - if !b.timerOn { - b.start = time.Now() - b.timerOn = true - } -} - -// StopTimer stops timing a test. This can be used to pause the timer -// while performing complex initialization that you don't -// want to measure. -func (b *B) StopTimer() { - if b.timerOn { - b.duration += time.Now().Sub(b.start) - b.timerOn = false - } -} - -// ResetTimer sets the elapsed benchmark time to zero. -// It does not affect whether the timer is running. -func (b *B) ResetTimer() { - if b.timerOn { - b.start = time.Now() - } - b.duration = 0 -} - -// SetBytes records the number of bytes processed in a single operation. -// If this is called, the benchmark will report ns/op and MB/s. -func (b *B) SetBytes(n int64) { b.bytes = n } - -func (b *B) nsPerOp() int64 { - if b.N <= 0 { - return 0 - } - return b.duration.Nanoseconds() / int64(b.N) -} - -// runN runs a single benchmark for the specified number of iterations. -func (b *B) runN(n int) { - // Try to get a comparable environment for each run - // by clearing garbage from previous runs. - runtime.GC() - b.N = n - b.ResetTimer() - b.StartTimer() - b.benchmark.F(b) - b.StopTimer() -} - -func min(x, y int) int { - if x > y { - return y - } - return x -} - -func max(x, y int) int { - if x < y { - return y - } - return x -} - -// roundDown10 rounds a number down to the nearest power of 10. -func roundDown10(n int) int { - var tens = 0 - // tens = floor(log_10(n)) - for n > 10 { - n = n / 10 - tens++ - } - // result = 10^tens - result := 1 - for i := 0; i < tens; i++ { - result *= 10 - } - return result -} - -// roundUp rounds x up to a number of the form [1eX, 2eX, 5eX]. -func roundUp(n int) int { - base := roundDown10(n) - if n < (2 * base) { - return 2 * base - } - if n < (5 * base) { - return 5 * base - } - return 10 * base -} - -// run times the benchmark function in a separate goroutine. -func (b *B) run() BenchmarkResult { - go b.launch() - <-b.signal - return b.result -} - -// launch launches the benchmark function. It gradually increases the number -// of benchmark iterations until the benchmark runs for a second in order -// to get a reasonable measurement. It prints timing information in this form -// testing.BenchmarkHello 100000 19 ns/op -// launch is run by the fun function as a separate goroutine. -func (b *B) launch() { - // Run the benchmark for a single iteration in case it's expensive. - n := 1 - - // Signal that we're done whether we return normally - // or by FailNow's runtime.Goexit. - defer func() { - b.signal <- b - }() - - b.runN(n) - // Run the benchmark for at least the specified amount of time. - d := *benchTime - for !b.failed && b.duration < d && n < 1e9 { - last := n - // Predict iterations/sec. - if b.nsPerOp() == 0 { - n = 1e9 - } else { - n = int(d.Nanoseconds() / b.nsPerOp()) - } - // Run more iterations than we think we'll need for a second (1.5x). - // Don't grow too fast in case we had timing errors previously. - // Be sure to run at least one more than last time. - n = max(min(n+n/2, 100*last), last+1) - // Round up to something easy to read. - n = roundUp(n) - b.runN(n) - } - b.result = BenchmarkResult{b.N, b.duration, b.bytes} -} - -// The results of a benchmark run. -type BenchmarkResult struct { - N int // The number of iterations. - T time.Duration // The total time taken. - Bytes int64 // Bytes processed in one iteration. -} - -func (r BenchmarkResult) NsPerOp() int64 { - if r.N <= 0 { - return 0 - } - return r.T.Nanoseconds() / int64(r.N) -} - -func (r BenchmarkResult) mbPerSec() float64 { - if r.Bytes <= 0 || r.T <= 0 || r.N <= 0 { - return 0 - } - return (float64(r.Bytes) * float64(r.N) / 1e6) / r.T.Seconds() -} - -func (r BenchmarkResult) String() string { - mbs := r.mbPerSec() - mb := "" - if mbs != 0 { - mb = fmt.Sprintf("\t%7.2f MB/s", mbs) - } - nsop := r.NsPerOp() - ns := fmt.Sprintf("%10d ns/op", nsop) - if r.N > 0 && nsop < 100 { - // The format specifiers here make sure that - // the ones digits line up for all three possible formats. - if nsop < 10 { - ns = fmt.Sprintf("%13.2f ns/op", float64(r.T.Nanoseconds())/float64(r.N)) - } else { - ns = fmt.Sprintf("%12.1f ns/op", float64(r.T.Nanoseconds())/float64(r.N)) - } - } - return fmt.Sprintf("%8d\t%s%s", r.N, ns, mb) -} - -// An internal function but exported because it is cross-package; part of the implementation -// of go test. -func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) { - // If no flag was specified, don't run benchmarks. - if len(*matchBenchmarks) == 0 { - return - } - for _, Benchmark := range benchmarks { - matched, err := matchString(*matchBenchmarks, Benchmark.Name) - if err != nil { - fmt.Fprintf(os.Stderr, "testing: invalid regexp for -test.bench: %s\n", err) - os.Exit(1) - } - if !matched { - continue - } - for _, procs := range cpuList { - runtime.GOMAXPROCS(procs) - b := &B{ - common: common{ - signal: make(chan interface{}), - }, - benchmark: Benchmark, - } - benchName := Benchmark.Name - if procs != 1 { - benchName = fmt.Sprintf("%s-%d", Benchmark.Name, procs) - } - fmt.Printf("%s\t", benchName) - r := b.run() - if b.failed { - // The output could be very long here, but probably isn't. - // We print it all, regardless, because we don't want to trim the reason - // the benchmark failed. - fmt.Printf("--- FAIL: %s\n%s", benchName, b.output) - continue - } - fmt.Printf("%v\n", r) - // Unlike with tests, we ignore the -chatty flag and always print output for - // benchmarks since the output generation time will skew the results. - if len(b.output) > 0 { - b.trimOutput() - fmt.Printf("--- BENCH: %s\n%s", benchName, b.output) - } - if p := runtime.GOMAXPROCS(-1); p != procs { - fmt.Fprintf(os.Stderr, "testing: %s left GOMAXPROCS set to %d\n", benchName, p) - } - } - } -} - -// trimOutput shortens the output from a benchmark, which can be very long. -func (b *B) trimOutput() { - // The output is likely to appear multiple times because the benchmark - // is run multiple times, but at least it will be seen. This is not a big deal - // because benchmarks rarely print, but just in case, we trim it if it's too long. - const maxNewlines = 10 - for nlCount, j := 0, 0; j < len(b.output); j++ { - if b.output[j] == '\n' { - nlCount++ - if nlCount >= maxNewlines { - b.output = append(b.output[:j], "\n\t... [output truncated]\n"...) - break - } - } - } -} - -// Benchmark benchmarks a single function. Useful for creating -// custom benchmarks that do not use go test. -func Benchmark(f func(b *B)) BenchmarkResult { - b := &B{ - common: common{ - signal: make(chan interface{}), - }, - benchmark: InternalBenchmark{"", f}, - } - return b.run() -} diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/c.0.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/c.0.golden deleted file mode 100644 index e21959b19..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/c.0.golden +++ /dev/null @@ -1,48 +0,0 @@ -// -PACKAGE c - -IMPORTPATH - testdata/c - -IMPORTS - a - -FILENAMES - testdata/c.go - -TYPES - // A (should see this) - type A struct{} - - // B (should see this) - type B struct{} - - // C (should see this) - type C struct{} - - // D (should see this) - type D struct{} - - // E1 (should see this) - type E1 struct{} - - // E (should see this for E2 and E3) - type E2 struct{} - - // E (should see this for E2 and E3) - type E3 struct{} - - // E4 (should see this) - type E4 struct{} - - // - type T1 struct{} - - // - func (t1 *T1) M() - - // T2 must not show methods of local T1 - type T2 struct { - a.T1 // not the same as locally declared T1 - } - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/c.1.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/c.1.golden deleted file mode 100644 index e21959b19..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/c.1.golden +++ /dev/null @@ -1,48 +0,0 @@ -// -PACKAGE c - -IMPORTPATH - testdata/c - -IMPORTS - a - -FILENAMES - testdata/c.go - -TYPES - // A (should see this) - type A struct{} - - // B (should see this) - type B struct{} - - // C (should see this) - type C struct{} - - // D (should see this) - type D struct{} - - // E1 (should see this) - type E1 struct{} - - // E (should see this for E2 and E3) - type E2 struct{} - - // E (should see this for E2 and E3) - type E3 struct{} - - // E4 (should see this) - type E4 struct{} - - // - type T1 struct{} - - // - func (t1 *T1) M() - - // T2 must not show methods of local T1 - type T2 struct { - a.T1 // not the same as locally declared T1 - } - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/c.2.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/c.2.golden deleted file mode 100644 index e21959b19..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/c.2.golden +++ /dev/null @@ -1,48 +0,0 @@ -// -PACKAGE c - -IMPORTPATH - testdata/c - -IMPORTS - a - -FILENAMES - testdata/c.go - -TYPES - // A (should see this) - type A struct{} - - // B (should see this) - type B struct{} - - // C (should see this) - type C struct{} - - // D (should see this) - type D struct{} - - // E1 (should see this) - type E1 struct{} - - // E (should see this for E2 and E3) - type E2 struct{} - - // E (should see this for E2 and E3) - type E3 struct{} - - // E4 (should see this) - type E4 struct{} - - // - type T1 struct{} - - // - func (t1 *T1) M() - - // T2 must not show methods of local T1 - type T2 struct { - a.T1 // not the same as locally declared T1 - } - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/c.go b/gcc-4.8.1/libgo/go/go/doc/testdata/c.go deleted file mode 100644 index e0f39196d..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/c.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package c - -import "a" - -// ---------------------------------------------------------------------------- -// Test that empty declarations don't cause problems - -const () - -type () - -var () - -// ---------------------------------------------------------------------------- -// Test that types with documentation on both, the Decl and the Spec node -// are handled correctly. - -// A (should see this) -type A struct{} - -// B (should see this) -type ( - B struct{} -) - -type ( - // C (should see this) - C struct{} -) - -// D (should not see this) -type ( - // D (should see this) - D struct{} -) - -// E (should see this for E2 and E3) -type ( - // E1 (should see this) - E1 struct{} - E2 struct{} - E3 struct{} - // E4 (should see this) - E4 struct{} -) - -// ---------------------------------------------------------------------------- -// Test that local and imported types are different when -// handling anonymous fields. - -type T1 struct{} - -func (t1 *T1) M() {} - -// T2 must not show methods of local T1 -type T2 struct { - a.T1 // not the same as locally declared T1 -} diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/d.0.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/d.0.golden deleted file mode 100644 index c00519953..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/d.0.golden +++ /dev/null @@ -1,104 +0,0 @@ -// -PACKAGE d - -IMPORTPATH - testdata/d - -FILENAMES - testdata/d1.go - testdata/d2.go - -CONSTANTS - // CBx constants should appear before CAx constants. - const ( - CB2 = iota // before CB1 - CB1 // before CB0 - CB0 // at end - ) - - // CAx constants should appear after CBx constants. - const ( - CA2 = iota // before CA1 - CA1 // before CA0 - CA0 // at end - ) - - // C0 should be first. - const C0 = 0 - - // C1 should be second. - const C1 = 1 - - // C2 should be third. - const C2 = 2 - - // - const ( - // Single const declarations inside ()'s are considered ungrouped - // and show up in sorted order. - Cungrouped = 0 - ) - - -VARIABLES - // VBx variables should appear before VAx variables. - var ( - VB2 int // before VB1 - VB1 int // before VB0 - VB0 int // at end - ) - - // VAx variables should appear after VBx variables. - var ( - VA2 int // before VA1 - VA1 int // before VA0 - VA0 int // at end - ) - - // V0 should be first. - var V0 uintptr - - // V1 should be second. - var V1 uint - - // V2 should be third. - var V2 int - - // - var ( - // Single var declarations inside ()'s are considered ungrouped - // and show up in sorted order. - Vungrouped = 0 - ) - - -FUNCTIONS - // F0 should be first. - func F0() - - // F1 should be second. - func F1() - - // F2 should be third. - func F2() - - -TYPES - // T0 should be first. - type T0 struct{} - - // T1 should be second. - type T1 struct{} - - // T2 should be third. - type T2 struct{} - - // TG0 should be first. - type TG0 struct{} - - // TG1 should be second. - type TG1 struct{} - - // TG2 should be third. - type TG2 struct{} - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/d.1.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/d.1.golden deleted file mode 100644 index c00519953..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/d.1.golden +++ /dev/null @@ -1,104 +0,0 @@ -// -PACKAGE d - -IMPORTPATH - testdata/d - -FILENAMES - testdata/d1.go - testdata/d2.go - -CONSTANTS - // CBx constants should appear before CAx constants. - const ( - CB2 = iota // before CB1 - CB1 // before CB0 - CB0 // at end - ) - - // CAx constants should appear after CBx constants. - const ( - CA2 = iota // before CA1 - CA1 // before CA0 - CA0 // at end - ) - - // C0 should be first. - const C0 = 0 - - // C1 should be second. - const C1 = 1 - - // C2 should be third. - const C2 = 2 - - // - const ( - // Single const declarations inside ()'s are considered ungrouped - // and show up in sorted order. - Cungrouped = 0 - ) - - -VARIABLES - // VBx variables should appear before VAx variables. - var ( - VB2 int // before VB1 - VB1 int // before VB0 - VB0 int // at end - ) - - // VAx variables should appear after VBx variables. - var ( - VA2 int // before VA1 - VA1 int // before VA0 - VA0 int // at end - ) - - // V0 should be first. - var V0 uintptr - - // V1 should be second. - var V1 uint - - // V2 should be third. - var V2 int - - // - var ( - // Single var declarations inside ()'s are considered ungrouped - // and show up in sorted order. - Vungrouped = 0 - ) - - -FUNCTIONS - // F0 should be first. - func F0() - - // F1 should be second. - func F1() - - // F2 should be third. - func F2() - - -TYPES - // T0 should be first. - type T0 struct{} - - // T1 should be second. - type T1 struct{} - - // T2 should be third. - type T2 struct{} - - // TG0 should be first. - type TG0 struct{} - - // TG1 should be second. - type TG1 struct{} - - // TG2 should be third. - type TG2 struct{} - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/d.2.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/d.2.golden deleted file mode 100644 index c00519953..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/d.2.golden +++ /dev/null @@ -1,104 +0,0 @@ -// -PACKAGE d - -IMPORTPATH - testdata/d - -FILENAMES - testdata/d1.go - testdata/d2.go - -CONSTANTS - // CBx constants should appear before CAx constants. - const ( - CB2 = iota // before CB1 - CB1 // before CB0 - CB0 // at end - ) - - // CAx constants should appear after CBx constants. - const ( - CA2 = iota // before CA1 - CA1 // before CA0 - CA0 // at end - ) - - // C0 should be first. - const C0 = 0 - - // C1 should be second. - const C1 = 1 - - // C2 should be third. - const C2 = 2 - - // - const ( - // Single const declarations inside ()'s are considered ungrouped - // and show up in sorted order. - Cungrouped = 0 - ) - - -VARIABLES - // VBx variables should appear before VAx variables. - var ( - VB2 int // before VB1 - VB1 int // before VB0 - VB0 int // at end - ) - - // VAx variables should appear after VBx variables. - var ( - VA2 int // before VA1 - VA1 int // before VA0 - VA0 int // at end - ) - - // V0 should be first. - var V0 uintptr - - // V1 should be second. - var V1 uint - - // V2 should be third. - var V2 int - - // - var ( - // Single var declarations inside ()'s are considered ungrouped - // and show up in sorted order. - Vungrouped = 0 - ) - - -FUNCTIONS - // F0 should be first. - func F0() - - // F1 should be second. - func F1() - - // F2 should be third. - func F2() - - -TYPES - // T0 should be first. - type T0 struct{} - - // T1 should be second. - type T1 struct{} - - // T2 should be third. - type T2 struct{} - - // TG0 should be first. - type TG0 struct{} - - // TG1 should be second. - type TG1 struct{} - - // TG2 should be third. - type TG2 struct{} - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/d1.go b/gcc-4.8.1/libgo/go/go/doc/testdata/d1.go deleted file mode 100644 index ebd694195..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/d1.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Test cases for sort order of declarations. - -package d - -// C2 should be third. -const C2 = 2 - -// V2 should be third. -var V2 int - -// CBx constants should appear before CAx constants. -const ( - CB2 = iota // before CB1 - CB1 // before CB0 - CB0 // at end -) - -// VBx variables should appear before VAx variables. -var ( - VB2 int // before VB1 - VB1 int // before VB0 - VB0 int // at end -) - -const ( - // Single const declarations inside ()'s are considered ungrouped - // and show up in sorted order. - Cungrouped = 0 -) - -var ( - // Single var declarations inside ()'s are considered ungrouped - // and show up in sorted order. - Vungrouped = 0 -) - -// T2 should be third. -type T2 struct{} - -// Grouped types are sorted nevertheless. -type ( - // TG2 should be third. - TG2 struct{} - - // TG1 should be second. - TG1 struct{} - - // TG0 should be first. - TG0 struct{} -) - -// F2 should be third. -func F2() {} diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/d2.go b/gcc-4.8.1/libgo/go/go/doc/testdata/d2.go deleted file mode 100644 index 2f56f4fa4..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/d2.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Test cases for sort order of declarations. - -package d - -// C1 should be second. -const C1 = 1 - -// C0 should be first. -const C0 = 0 - -// V1 should be second. -var V1 uint - -// V0 should be first. -var V0 uintptr - -// CAx constants should appear after CBx constants. -const ( - CA2 = iota // before CA1 - CA1 // before CA0 - CA0 // at end -) - -// VAx variables should appear after VBx variables. -var ( - VA2 int // before VA1 - VA1 int // before VA0 - VA0 int // at end -) - -// T1 should be second. -type T1 struct{} - -// T0 should be first. -type T0 struct{} - -// F1 should be second. -func F1() {} - -// F0 should be first. -func F0() {} diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/e.0.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/e.0.golden deleted file mode 100644 index 6987e5867..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/e.0.golden +++ /dev/null @@ -1,109 +0,0 @@ -// The package e is a go/doc test for embedded methods. -PACKAGE e - -IMPORTPATH - testdata/e - -FILENAMES - testdata/e.go - -TYPES - // T1 has no embedded (level 1) M method due to conflict. - type T1 struct { - // contains filtered or unexported fields - } - - // T2 has only M as top-level method. - type T2 struct { - // contains filtered or unexported fields - } - - // T2.M should appear as method of T2. - func (T2) M() - - // T3 has only M as top-level method. - type T3 struct { - // contains filtered or unexported fields - } - - // T3.M should appear as method of T3. - func (T3) M() - - // - type T4 struct{} - - // T4.M should appear as method of T5 only if AllMethods is set. - func (*T4) M() - - // - type T5 struct { - T4 - } - - // - type U1 struct { - *U1 - } - - // U1.M should appear as method of U1. - func (*U1) M() - - // - type U2 struct { - *U3 - } - - // U2.M should appear as method of U2 and as method of U3 only if ... - func (*U2) M() - - // - type U3 struct { - *U2 - } - - // U3.N should appear as method of U3 and as method of U2 only if ... - func (*U3) N() - - // - type U4 struct { - // contains filtered or unexported fields - } - - // U4.M should appear as method of U4. - func (*U4) M() - - // - type V1 struct { - *V2 - *V5 - } - - // - type V2 struct { - *V3 - } - - // - type V3 struct { - *V4 - } - - // - type V4 struct { - *V5 - } - - // V4.M should appear as method of V2 and V3 if AllMethods is set. - func (*V4) M() - - // - type V5 struct { - *V6 - } - - // - type V6 struct{} - - // V6.M should appear as method of V1 and V5 if AllMethods is set. - func (*V6) M() - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/e.1.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/e.1.golden deleted file mode 100644 index cbe22e0bf..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/e.1.golden +++ /dev/null @@ -1,144 +0,0 @@ -// The package e is a go/doc test for embedded methods. -PACKAGE e - -IMPORTPATH - testdata/e - -FILENAMES - testdata/e.go - -TYPES - // T1 has no embedded (level 1) M method due to conflict. - type T1 struct { - t1 - t2 - } - - // T2 has only M as top-level method. - type T2 struct { - t1 - } - - // T2.M should appear as method of T2. - func (T2) M() - - // T3 has only M as top-level method. - type T3 struct { - t1e - t2e - } - - // T3.M should appear as method of T3. - func (T3) M() - - // - type T4 struct{} - - // T4.M should appear as method of T5 only if AllMethods is set. - func (*T4) M() - - // - type T5 struct { - T4 - } - - // - type U1 struct { - *U1 - } - - // U1.M should appear as method of U1. - func (*U1) M() - - // - type U2 struct { - *U3 - } - - // U2.M should appear as method of U2 and as method of U3 only if ... - func (*U2) M() - - // - type U3 struct { - *U2 - } - - // U3.N should appear as method of U3 and as method of U2 only if ... - func (*U3) N() - - // - type U4 struct { - *u5 - } - - // U4.M should appear as method of U4. - func (*U4) M() - - // - type V1 struct { - *V2 - *V5 - } - - // - type V2 struct { - *V3 - } - - // - type V3 struct { - *V4 - } - - // - type V4 struct { - *V5 - } - - // V4.M should appear as method of V2 and V3 if AllMethods is set. - func (*V4) M() - - // - type V5 struct { - *V6 - } - - // - type V6 struct{} - - // V6.M should appear as method of V1 and V5 if AllMethods is set. - func (*V6) M() - - // - type t1 struct{} - - // t1.M should not appear as method in a Tx type. - func (t1) M() - - // - type t1e struct { - t1 - } - - // t1.M should not appear as method in a Tx type. - func (t1e) M() - - // - type t2 struct{} - - // t2.M should not appear as method in a Tx type. - func (t2) M() - - // - type t2e struct { - t2 - } - - // t2.M should not appear as method in a Tx type. - func (t2e) M() - - // - type u5 struct { - *U4 - } - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/e.2.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/e.2.golden deleted file mode 100644 index e7b05e80f..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/e.2.golden +++ /dev/null @@ -1,130 +0,0 @@ -// The package e is a go/doc test for embedded methods. -PACKAGE e - -IMPORTPATH - testdata/e - -FILENAMES - testdata/e.go - -TYPES - // T1 has no embedded (level 1) M method due to conflict. - type T1 struct { - // contains filtered or unexported fields - } - - // T2 has only M as top-level method. - type T2 struct { - // contains filtered or unexported fields - } - - // T2.M should appear as method of T2. - func (T2) M() - - // T3 has only M as top-level method. - type T3 struct { - // contains filtered or unexported fields - } - - // T3.M should appear as method of T3. - func (T3) M() - - // - type T4 struct{} - - // T4.M should appear as method of T5 only if AllMethods is set. - func (*T4) M() - - // - type T5 struct { - T4 - } - - // T4.M should appear as method of T5 only if AllMethods is set. - func (*T5) M() - - // - type U1 struct { - *U1 - } - - // U1.M should appear as method of U1. - func (*U1) M() - - // - type U2 struct { - *U3 - } - - // U2.M should appear as method of U2 and as method of U3 only if ... - func (*U2) M() - - // U3.N should appear as method of U3 and as method of U2 only if ... - func (U2) N() - - // - type U3 struct { - *U2 - } - - // U2.M should appear as method of U2 and as method of U3 only if ... - func (U3) M() - - // U3.N should appear as method of U3 and as method of U2 only if ... - func (*U3) N() - - // - type U4 struct { - // contains filtered or unexported fields - } - - // U4.M should appear as method of U4. - func (*U4) M() - - // - type V1 struct { - *V2 - *V5 - } - - // V6.M should appear as method of V1 and V5 if AllMethods is set. - func (V1) M() - - // - type V2 struct { - *V3 - } - - // V4.M should appear as method of V2 and V3 if AllMethods is set. - func (V2) M() - - // - type V3 struct { - *V4 - } - - // V4.M should appear as method of V2 and V3 if AllMethods is set. - func (V3) M() - - // - type V4 struct { - *V5 - } - - // V4.M should appear as method of V2 and V3 if AllMethods is set. - func (*V4) M() - - // - type V5 struct { - *V6 - } - - // V6.M should appear as method of V1 and V5 if AllMethods is set. - func (V5) M() - - // - type V6 struct{} - - // V6.M should appear as method of V1 and V5 if AllMethods is set. - func (*V6) M() - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/e.go b/gcc-4.8.1/libgo/go/go/doc/testdata/e.go deleted file mode 100644 index ec432e3e5..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/e.go +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// The package e is a go/doc test for embedded methods. -package e - -// ---------------------------------------------------------------------------- -// Conflicting methods M must not show up. - -type t1 struct{} - -// t1.M should not appear as method in a Tx type. -func (t1) M() {} - -type t2 struct{} - -// t2.M should not appear as method in a Tx type. -func (t2) M() {} - -// T1 has no embedded (level 1) M method due to conflict. -type T1 struct { - t1 - t2 -} - -// ---------------------------------------------------------------------------- -// Higher-level method M wins over lower-level method M. - -// T2 has only M as top-level method. -type T2 struct { - t1 -} - -// T2.M should appear as method of T2. -func (T2) M() {} - -// ---------------------------------------------------------------------------- -// Higher-level method M wins over lower-level conflicting methods M. - -type t1e struct { - t1 -} - -type t2e struct { - t2 -} - -// T3 has only M as top-level method. -type T3 struct { - t1e - t2e -} - -// T3.M should appear as method of T3. -func (T3) M() {} - -// ---------------------------------------------------------------------------- -// Don't show conflicting methods M embedded via an exported and non-exported -// type. - -// T1 has no embedded (level 1) M method due to conflict. -type T4 struct { - t2 - T2 -} - -// ---------------------------------------------------------------------------- -// Don't show embedded methods of exported anonymous fields unless AllMethods -// is set. - -type T4 struct{} - -// T4.M should appear as method of T5 only if AllMethods is set. -func (*T4) M() {} - -type T5 struct { - T4 -} - -// ---------------------------------------------------------------------------- -// Recursive type declarations must not lead to endless recursion. - -type U1 struct { - *U1 -} - -// U1.M should appear as method of U1. -func (*U1) M() {} - -type U2 struct { - *U3 -} - -// U2.M should appear as method of U2 and as method of U3 only if AllMethods is set. -func (*U2) M() {} - -type U3 struct { - *U2 -} - -// U3.N should appear as method of U3 and as method of U2 only if AllMethods is set. -func (*U3) N() {} - -type U4 struct { - *u5 -} - -// U4.M should appear as method of U4. -func (*U4) M() {} - -type u5 struct { - *U4 -} - -// ---------------------------------------------------------------------------- -// A higher-level embedded type (and its methods) wins over the same type (and -// its methods) embedded at a lower level. - -type V1 struct { - *V2 - *V5 -} - -type V2 struct { - *V3 -} - -type V3 struct { - *V4 -} - -type V4 struct { - *V5 -} - -type V5 struct { - *V6 -} - -type V6 struct{} - -// V4.M should appear as method of V2 and V3 if AllMethods is set. -func (*V4) M() {} - -// V6.M should appear as method of V1 and V5 if AllMethods is set. -func (*V6) M() {} diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/error1.0.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/error1.0.golden deleted file mode 100644 index 6c6fe5d49..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/error1.0.golden +++ /dev/null @@ -1,30 +0,0 @@ -// -PACKAGE error1 - -IMPORTPATH - testdata/error1 - -FILENAMES - testdata/error1.go - -TYPES - // - type I0 interface { - // When embedded, the predeclared error interface - // must remain visible in interface types. - error - } - - // - type S0 struct { - // contains filtered or unexported fields - } - - // - type T0 struct { - ExportedField interface { - // error should be visible - error - } - } - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/error1.1.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/error1.1.golden deleted file mode 100644 index a8dc2e71d..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/error1.1.golden +++ /dev/null @@ -1,32 +0,0 @@ -// -PACKAGE error1 - -IMPORTPATH - testdata/error1 - -FILENAMES - testdata/error1.go - -TYPES - // - type I0 interface { - // When embedded, the predeclared error interface - // must remain visible in interface types. - error - } - - // - type S0 struct { - // In struct types, an embedded error must only be visible - // if AllDecls is set. - error - } - - // - type T0 struct { - ExportedField interface { - // error should be visible - error - } - } - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/error1.2.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/error1.2.golden deleted file mode 100644 index 6c6fe5d49..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/error1.2.golden +++ /dev/null @@ -1,30 +0,0 @@ -// -PACKAGE error1 - -IMPORTPATH - testdata/error1 - -FILENAMES - testdata/error1.go - -TYPES - // - type I0 interface { - // When embedded, the predeclared error interface - // must remain visible in interface types. - error - } - - // - type S0 struct { - // contains filtered or unexported fields - } - - // - type T0 struct { - ExportedField interface { - // error should be visible - error - } - } - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/error1.go b/gcc-4.8.1/libgo/go/go/doc/testdata/error1.go deleted file mode 100644 index 3c777a780..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/error1.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package error1 - -type I0 interface { - // When embedded, the predeclared error interface - // must remain visible in interface types. - error -} - -type T0 struct { - ExportedField interface { - // error should be visible - error - } -} - -type S0 struct { - // In struct types, an embedded error must only be visible - // if AllDecls is set. - error -} diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/error2.0.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/error2.0.golden deleted file mode 100644 index dedfe412a..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/error2.0.golden +++ /dev/null @@ -1,27 +0,0 @@ -// -PACKAGE error2 - -IMPORTPATH - testdata/error2 - -FILENAMES - testdata/error2.go - -TYPES - // - type I0 interface { - // contains filtered or unexported methods - } - - // - type S0 struct { - // contains filtered or unexported fields - } - - // - type T0 struct { - ExportedField interface { - // contains filtered or unexported methods - } - } - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/error2.1.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/error2.1.golden deleted file mode 100644 index dbcc1b03e..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/error2.1.golden +++ /dev/null @@ -1,37 +0,0 @@ -// -PACKAGE error2 - -IMPORTPATH - testdata/error2 - -FILENAMES - testdata/error2.go - -TYPES - // - type I0 interface { - // When embedded, the locally-declared error interface - // is only visible if all declarations are shown. - error - } - - // - type S0 struct { - // In struct types, an embedded error must only be visible - // if AllDecls is set. - error - } - - // - type T0 struct { - ExportedField interface { - // error should not be visible - error - } - } - - // This error declaration shadows the predeclared error type. - type error interface { - Error() string - } - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/error2.2.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/error2.2.golden deleted file mode 100644 index dedfe412a..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/error2.2.golden +++ /dev/null @@ -1,27 +0,0 @@ -// -PACKAGE error2 - -IMPORTPATH - testdata/error2 - -FILENAMES - testdata/error2.go - -TYPES - // - type I0 interface { - // contains filtered or unexported methods - } - - // - type S0 struct { - // contains filtered or unexported fields - } - - // - type T0 struct { - ExportedField interface { - // contains filtered or unexported methods - } - } - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/error2.go b/gcc-4.8.1/libgo/go/go/doc/testdata/error2.go deleted file mode 100644 index 6ee96c245..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/error2.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package error2 - -type I0 interface { - // When embedded, the locally-declared error interface - // is only visible if all declarations are shown. - error -} - -type T0 struct { - ExportedField interface { - // error should not be visible - error - } -} - -type S0 struct { - // In struct types, an embedded error must only be visible - // if AllDecls is set. - error -} - -// This error declaration shadows the predeclared error type. -type error interface { - Error() string -} diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/example.go b/gcc-4.8.1/libgo/go/go/doc/testdata/example.go deleted file mode 100644 index fdeda137e..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/example.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package testing - -import ( - "bytes" - "fmt" - "io" - "os" - "strings" - "time" -) - -type InternalExample struct { - Name string - F func() - Output string -} - -func RunExamples(examples []InternalExample) (ok bool) { - ok = true - - var eg InternalExample - - stdout, stderr := os.Stdout, os.Stderr - defer func() { - os.Stdout, os.Stderr = stdout, stderr - if e := recover(); e != nil { - fmt.Printf("--- FAIL: %s\npanic: %v\n", eg.Name, e) - os.Exit(1) - } - }() - - for _, eg = range examples { - if *chatty { - fmt.Printf("=== RUN: %s\n", eg.Name) - } - - // capture stdout and stderr - r, w, err := os.Pipe() - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - os.Stdout, os.Stderr = w, w - outC := make(chan string) - go func() { - buf := new(bytes.Buffer) - _, err := io.Copy(buf, r) - if err != nil { - fmt.Fprintf(stderr, "testing: copying pipe: %v\n", err) - os.Exit(1) - } - outC <- buf.String() - }() - - // run example - t0 := time.Now() - eg.F() - dt := time.Now().Sub(t0) - - // close pipe, restore stdout/stderr, get output - w.Close() - os.Stdout, os.Stderr = stdout, stderr - out := <-outC - - // report any errors - tstr := fmt.Sprintf("(%.2f seconds)", dt.Seconds()) - if g, e := strings.TrimSpace(out), strings.TrimSpace(eg.Output); g != e { - fmt.Printf("--- FAIL: %s %s\ngot:\n%s\nwant:\n%s\n", - eg.Name, tstr, g, e) - ok = false - } else if *chatty { - fmt.Printf("--- PASS: %s %s\n", eg.Name, tstr) - } - } - - return -} diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/f.0.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/f.0.golden deleted file mode 100644 index 817590186..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/f.0.golden +++ /dev/null @@ -1,13 +0,0 @@ -// The package f is a go/doc test for functions and factory ... -PACKAGE f - -IMPORTPATH - testdata/f - -FILENAMES - testdata/f.go - -FUNCTIONS - // Exported must always be visible. Was issue 2824. - func Exported() private - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/f.1.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/f.1.golden deleted file mode 100644 index ba68e884c..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/f.1.golden +++ /dev/null @@ -1,16 +0,0 @@ -// The package f is a go/doc test for functions and factory ... -PACKAGE f - -IMPORTPATH - testdata/f - -FILENAMES - testdata/f.go - -TYPES - // - type private struct{} - - // Exported must always be visible. Was issue 2824. - func Exported() private - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/f.2.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/f.2.golden deleted file mode 100644 index 817590186..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/f.2.golden +++ /dev/null @@ -1,13 +0,0 @@ -// The package f is a go/doc test for functions and factory ... -PACKAGE f - -IMPORTPATH - testdata/f - -FILENAMES - testdata/f.go - -FUNCTIONS - // Exported must always be visible. Was issue 2824. - func Exported() private - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/f.go b/gcc-4.8.1/libgo/go/go/doc/testdata/f.go deleted file mode 100644 index 7e9add907..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/f.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// The package f is a go/doc test for functions and factory methods. -package f - -// ---------------------------------------------------------------------------- -// Factory functions for non-exported types must not get lost. - -type private struct{} - -// Exported must always be visible. Was issue 2824. -func Exported() private {} diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/template.txt b/gcc-4.8.1/libgo/go/go/doc/testdata/template.txt deleted file mode 100644 index 32e331cdd..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/template.txt +++ /dev/null @@ -1,65 +0,0 @@ -{{synopsis .Doc}} -PACKAGE {{.Name}} - -IMPORTPATH - {{.ImportPath}} - -{{with .Imports}}IMPORTS -{{range .}} {{.}} -{{end}} -{{end}}{{/* - -*/}}FILENAMES -{{range .Filenames}} {{.}} -{{end}}{{/* - -*/}}{{with .Consts}} -CONSTANTS -{{range .}} {{synopsis .Doc}} - {{node .Decl $.FSet}} - -{{end}}{{end}}{{/* - -*/}}{{with .Vars}} -VARIABLES -{{range .}} {{synopsis .Doc}} - {{node .Decl $.FSet}} - -{{end}}{{end}}{{/* - -*/}}{{with .Funcs}} -FUNCTIONS -{{range .}} {{synopsis .Doc}} - {{node .Decl $.FSet}} - -{{end}}{{end}}{{/* - -*/}}{{with .Types}} -TYPES -{{range .}} {{synopsis .Doc}} - {{node .Decl $.FSet}} - -{{range .Consts}} {{synopsis .Doc}} - {{node .Decl $.FSet}} - -{{end}}{{/* - -*/}}{{range .Vars}} {{synopsis .Doc}} - {{node .Decl $.FSet}} - -{{end}}{{/* - -*/}}{{range .Funcs}} {{synopsis .Doc}} - {{node .Decl $.FSet}} - -{{end}}{{/* - -*/}}{{range .Methods}} {{synopsis .Doc}} - {{node .Decl $.FSet}} - -{{end}}{{end}}{{end}}{{/* - -*/}}{{with .Bugs}} -BUGS -{{range .}} {{synopsis .}} -{{end}}{{end}}
\ No newline at end of file diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/testing.0.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/testing.0.golden deleted file mode 100644 index 15a903986..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/testing.0.golden +++ /dev/null @@ -1,156 +0,0 @@ -// Package testing provides support for automated testing of Go ... -PACKAGE testing - -IMPORTPATH - testdata/testing - -IMPORTS - bytes - flag - fmt - io - os - runtime - runtime/pprof - strconv - strings - time - -FILENAMES - testdata/benchmark.go - testdata/example.go - testdata/testing.go - -FUNCTIONS - // An internal function but exported because it is cross-package; ... - func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) - - // An internal function but exported because it is cross-package; ... - func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) - - // - func RunExamples(examples []InternalExample) (ok bool) - - // - func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) - - // Short reports whether the -test.short flag is set. - func Short() bool - - -TYPES - // B is a type passed to Benchmark functions to manage benchmark ... - type B struct { - N int - // contains filtered or unexported fields - } - - // Error is equivalent to Log() followed by Fail(). - func (c *B) Error(args ...interface{}) - - // Errorf is equivalent to Logf() followed by Fail(). - func (c *B) Errorf(format string, args ...interface{}) - - // Fail marks the function as having failed but continues ... - func (c *B) Fail() - - // FailNow marks the function as having failed and stops its ... - func (c *B) FailNow() - - // Failed returns whether the function has failed. - func (c *B) Failed() bool - - // Fatal is equivalent to Log() followed by FailNow(). - func (c *B) Fatal(args ...interface{}) - - // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *B) Fatalf(format string, args ...interface{}) - - // Log formats its arguments using default formatting, analogous ... - func (c *B) Log(args ...interface{}) - - // Logf formats its arguments according to the format, analogous ... - func (c *B) Logf(format string, args ...interface{}) - - // ResetTimer sets the elapsed benchmark time to zero. It does not ... - func (b *B) ResetTimer() - - // SetBytes records the number of bytes processed in a single ... - func (b *B) SetBytes(n int64) - - // StartTimer starts timing a test. This function is called ... - func (b *B) StartTimer() - - // StopTimer stops timing a test. This can be used to pause the ... - func (b *B) StopTimer() - - // The results of a benchmark run. - type BenchmarkResult struct { - N int // The number of iterations. - T time.Duration // The total time taken. - Bytes int64 // Bytes processed in one iteration. - } - - // Benchmark benchmarks a single function. Useful for creating ... - func Benchmark(f func(b *B)) BenchmarkResult - - // - func (r BenchmarkResult) NsPerOp() int64 - - // - func (r BenchmarkResult) String() string - - // An internal type but exported because it is cross-package; part ... - type InternalBenchmark struct { - Name string - F func(b *B) - } - - // - type InternalExample struct { - Name string - F func() - Output string - } - - // An internal type but exported because it is cross-package; part ... - type InternalTest struct { - Name string - F func(*T) - } - - // T is a type passed to Test functions to manage test state and ... - type T struct { - // contains filtered or unexported fields - } - - // Error is equivalent to Log() followed by Fail(). - func (c *T) Error(args ...interface{}) - - // Errorf is equivalent to Logf() followed by Fail(). - func (c *T) Errorf(format string, args ...interface{}) - - // Fail marks the function as having failed but continues ... - func (c *T) Fail() - - // FailNow marks the function as having failed and stops its ... - func (c *T) FailNow() - - // Failed returns whether the function has failed. - func (c *T) Failed() bool - - // Fatal is equivalent to Log() followed by FailNow(). - func (c *T) Fatal(args ...interface{}) - - // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *T) Fatalf(format string, args ...interface{}) - - // Log formats its arguments using default formatting, analogous ... - func (c *T) Log(args ...interface{}) - - // Logf formats its arguments according to the format, analogous ... - func (c *T) Logf(format string, args ...interface{}) - - // Parallel signals that this test is to be run in parallel with ... - func (t *T) Parallel() - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/testing.1.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/testing.1.golden deleted file mode 100644 index ffdb5c3b5..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/testing.1.golden +++ /dev/null @@ -1,298 +0,0 @@ -// Package testing provides support for automated testing of Go ... -PACKAGE testing - -IMPORTPATH - testdata/testing - -IMPORTS - bytes - flag - fmt - io - os - runtime - runtime/pprof - strconv - strings - time - -FILENAMES - testdata/benchmark.go - testdata/example.go - testdata/testing.go - -VARIABLES - // - var ( - // The short flag requests that tests run more quickly, but its functionality - // is provided by test writers themselves. The testing package is just its - // home. The all.bash installation script sets it to make installation more - // efficient, but by default the flag is off so a plain "go test" will do a - // full test of the package. - short = flag.Bool("test.short", false, "run smaller test suite to save time") - - // Report as tests are run; default is silent for success. - chatty = flag.Bool("test.v", false, "verbose: print additional output") - match = flag.String("test.run", "", "regular expression to select tests to run") - memProfile = flag.String("test.memprofile", "", "write a memory profile to the named file after execution") - memProfileRate = flag.Int("test.memprofilerate", 0, "if >=0, sets runtime.MemProfileRate") - cpuProfile = flag.String("test.cpuprofile", "", "write a cpu profile to the named file during execution") - timeout = flag.Duration("test.timeout", 0, "if positive, sets an aggregate time limit for all tests") - cpuListStr = flag.String("test.cpu", "", "comma-separated list of number of CPUs to use for each test") - parallel = flag.Int("test.parallel", runtime.GOMAXPROCS(0), "maximum test parallelism") - - cpuList []int - ) - - // - var benchTime = flag.Duration("test.benchtime", 1*time.Second, "approximate run time for each benchmark") - - // - var matchBenchmarks = flag.String("test.bench", "", "regular expression to select benchmarks to run") - - // - var timer *time.Timer - - -FUNCTIONS - // An internal function but exported because it is cross-package; ... - func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) - - // An internal function but exported because it is cross-package; ... - func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) - - // - func RunExamples(examples []InternalExample) (ok bool) - - // - func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) - - // Short reports whether the -test.short flag is set. - func Short() bool - - // after runs after all testing. - func after() - - // alarm is called if the timeout expires. - func alarm() - - // before runs before all testing. - func before() - - // decorate inserts the final newline if needed and indentation ... - func decorate(s string, addFileLine bool) string - - // - func max(x, y int) int - - // - func min(x, y int) int - - // - func parseCpuList() - - // roundDown10 rounds a number down to the nearest power of 10. - func roundDown10(n int) int - - // roundUp rounds x up to a number of the form [1eX, 2eX, 5eX]. - func roundUp(n int) int - - // startAlarm starts an alarm if requested. - func startAlarm() - - // stopAlarm turns off the alarm. - func stopAlarm() - - // - func tRunner(t *T, test *InternalTest) - - -TYPES - // B is a type passed to Benchmark functions to manage benchmark ... - type B struct { - common - N int - benchmark InternalBenchmark - bytes int64 - timerOn bool - result BenchmarkResult - } - - // Error is equivalent to Log() followed by Fail(). - func (c *B) Error(args ...interface{}) - - // Errorf is equivalent to Logf() followed by Fail(). - func (c *B) Errorf(format string, args ...interface{}) - - // Fail marks the function as having failed but continues ... - func (c *B) Fail() - - // FailNow marks the function as having failed and stops its ... - func (c *B) FailNow() - - // Failed returns whether the function has failed. - func (c *B) Failed() bool - - // Fatal is equivalent to Log() followed by FailNow(). - func (c *B) Fatal(args ...interface{}) - - // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *B) Fatalf(format string, args ...interface{}) - - // Log formats its arguments using default formatting, analogous ... - func (c *B) Log(args ...interface{}) - - // Logf formats its arguments according to the format, analogous ... - func (c *B) Logf(format string, args ...interface{}) - - // ResetTimer sets the elapsed benchmark time to zero. It does not ... - func (b *B) ResetTimer() - - // SetBytes records the number of bytes processed in a single ... - func (b *B) SetBytes(n int64) - - // StartTimer starts timing a test. This function is called ... - func (b *B) StartTimer() - - // StopTimer stops timing a test. This can be used to pause the ... - func (b *B) StopTimer() - - // launch launches the benchmark function. It gradually increases ... - func (b *B) launch() - - // log generates the output. It's always at the same stack depth. - func (c *B) log(s string) - - // - func (b *B) nsPerOp() int64 - - // run times the benchmark function in a separate goroutine. - func (b *B) run() BenchmarkResult - - // runN runs a single benchmark for the specified number of ... - func (b *B) runN(n int) - - // trimOutput shortens the output from a benchmark, which can be ... - func (b *B) trimOutput() - - // The results of a benchmark run. - type BenchmarkResult struct { - N int // The number of iterations. - T time.Duration // The total time taken. - Bytes int64 // Bytes processed in one iteration. - } - - // Benchmark benchmarks a single function. Useful for creating ... - func Benchmark(f func(b *B)) BenchmarkResult - - // - func (r BenchmarkResult) NsPerOp() int64 - - // - func (r BenchmarkResult) String() string - - // - func (r BenchmarkResult) mbPerSec() float64 - - // An internal type but exported because it is cross-package; part ... - type InternalBenchmark struct { - Name string - F func(b *B) - } - - // - type InternalExample struct { - Name string - F func() - Output string - } - - // An internal type but exported because it is cross-package; part ... - type InternalTest struct { - Name string - F func(*T) - } - - // T is a type passed to Test functions to manage test state and ... - type T struct { - common - name string // Name of test. - startParallel chan bool // Parallel tests will wait on this. - } - - // Error is equivalent to Log() followed by Fail(). - func (c *T) Error(args ...interface{}) - - // Errorf is equivalent to Logf() followed by Fail(). - func (c *T) Errorf(format string, args ...interface{}) - - // Fail marks the function as having failed but continues ... - func (c *T) Fail() - - // FailNow marks the function as having failed and stops its ... - func (c *T) FailNow() - - // Failed returns whether the function has failed. - func (c *T) Failed() bool - - // Fatal is equivalent to Log() followed by FailNow(). - func (c *T) Fatal(args ...interface{}) - - // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *T) Fatalf(format string, args ...interface{}) - - // Log formats its arguments using default formatting, analogous ... - func (c *T) Log(args ...interface{}) - - // Logf formats its arguments according to the format, analogous ... - func (c *T) Logf(format string, args ...interface{}) - - // Parallel signals that this test is to be run in parallel with ... - func (t *T) Parallel() - - // log generates the output. It's always at the same stack depth. - func (c *T) log(s string) - - // - func (t *T) report() - - // common holds the elements common between T and B and captures ... - type common struct { - output []byte // Output generated by test or benchmark. - failed bool // Test or benchmark has failed. - start time.Time // Time test or benchmark started - duration time.Duration - self interface{} // To be sent on signal channel when done. - signal chan interface{} // Output for serial tests. - } - - // Error is equivalent to Log() followed by Fail(). - func (c *common) Error(args ...interface{}) - - // Errorf is equivalent to Logf() followed by Fail(). - func (c *common) Errorf(format string, args ...interface{}) - - // Fail marks the function as having failed but continues ... - func (c *common) Fail() - - // FailNow marks the function as having failed and stops its ... - func (c *common) FailNow() - - // Failed returns whether the function has failed. - func (c *common) Failed() bool - - // Fatal is equivalent to Log() followed by FailNow(). - func (c *common) Fatal(args ...interface{}) - - // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *common) Fatalf(format string, args ...interface{}) - - // Log formats its arguments using default formatting, analogous ... - func (c *common) Log(args ...interface{}) - - // Logf formats its arguments according to the format, analogous ... - func (c *common) Logf(format string, args ...interface{}) - - // log generates the output. It's always at the same stack depth. - func (c *common) log(s string) - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/testing.2.golden b/gcc-4.8.1/libgo/go/go/doc/testdata/testing.2.golden deleted file mode 100644 index 15a903986..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/testing.2.golden +++ /dev/null @@ -1,156 +0,0 @@ -// Package testing provides support for automated testing of Go ... -PACKAGE testing - -IMPORTPATH - testdata/testing - -IMPORTS - bytes - flag - fmt - io - os - runtime - runtime/pprof - strconv - strings - time - -FILENAMES - testdata/benchmark.go - testdata/example.go - testdata/testing.go - -FUNCTIONS - // An internal function but exported because it is cross-package; ... - func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) - - // An internal function but exported because it is cross-package; ... - func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) - - // - func RunExamples(examples []InternalExample) (ok bool) - - // - func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) - - // Short reports whether the -test.short flag is set. - func Short() bool - - -TYPES - // B is a type passed to Benchmark functions to manage benchmark ... - type B struct { - N int - // contains filtered or unexported fields - } - - // Error is equivalent to Log() followed by Fail(). - func (c *B) Error(args ...interface{}) - - // Errorf is equivalent to Logf() followed by Fail(). - func (c *B) Errorf(format string, args ...interface{}) - - // Fail marks the function as having failed but continues ... - func (c *B) Fail() - - // FailNow marks the function as having failed and stops its ... - func (c *B) FailNow() - - // Failed returns whether the function has failed. - func (c *B) Failed() bool - - // Fatal is equivalent to Log() followed by FailNow(). - func (c *B) Fatal(args ...interface{}) - - // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *B) Fatalf(format string, args ...interface{}) - - // Log formats its arguments using default formatting, analogous ... - func (c *B) Log(args ...interface{}) - - // Logf formats its arguments according to the format, analogous ... - func (c *B) Logf(format string, args ...interface{}) - - // ResetTimer sets the elapsed benchmark time to zero. It does not ... - func (b *B) ResetTimer() - - // SetBytes records the number of bytes processed in a single ... - func (b *B) SetBytes(n int64) - - // StartTimer starts timing a test. This function is called ... - func (b *B) StartTimer() - - // StopTimer stops timing a test. This can be used to pause the ... - func (b *B) StopTimer() - - // The results of a benchmark run. - type BenchmarkResult struct { - N int // The number of iterations. - T time.Duration // The total time taken. - Bytes int64 // Bytes processed in one iteration. - } - - // Benchmark benchmarks a single function. Useful for creating ... - func Benchmark(f func(b *B)) BenchmarkResult - - // - func (r BenchmarkResult) NsPerOp() int64 - - // - func (r BenchmarkResult) String() string - - // An internal type but exported because it is cross-package; part ... - type InternalBenchmark struct { - Name string - F func(b *B) - } - - // - type InternalExample struct { - Name string - F func() - Output string - } - - // An internal type but exported because it is cross-package; part ... - type InternalTest struct { - Name string - F func(*T) - } - - // T is a type passed to Test functions to manage test state and ... - type T struct { - // contains filtered or unexported fields - } - - // Error is equivalent to Log() followed by Fail(). - func (c *T) Error(args ...interface{}) - - // Errorf is equivalent to Logf() followed by Fail(). - func (c *T) Errorf(format string, args ...interface{}) - - // Fail marks the function as having failed but continues ... - func (c *T) Fail() - - // FailNow marks the function as having failed and stops its ... - func (c *T) FailNow() - - // Failed returns whether the function has failed. - func (c *T) Failed() bool - - // Fatal is equivalent to Log() followed by FailNow(). - func (c *T) Fatal(args ...interface{}) - - // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *T) Fatalf(format string, args ...interface{}) - - // Log formats its arguments using default formatting, analogous ... - func (c *T) Log(args ...interface{}) - - // Logf formats its arguments according to the format, analogous ... - func (c *T) Logf(format string, args ...interface{}) - - // Parallel signals that this test is to be run in parallel with ... - func (t *T) Parallel() - diff --git a/gcc-4.8.1/libgo/go/go/doc/testdata/testing.go b/gcc-4.8.1/libgo/go/go/doc/testdata/testing.go deleted file mode 100644 index c2499ad77..000000000 --- a/gcc-4.8.1/libgo/go/go/doc/testdata/testing.go +++ /dev/null @@ -1,404 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package testing provides support for automated testing of Go packages. -// It is intended to be used in concert with the ``go test'' utility, which automates -// execution of any function of the form -// func TestXxx(*testing.T) -// where Xxx can be any alphanumeric string (but the first letter must not be in -// [a-z]) and serves to identify the test routine. -// These TestXxx routines should be declared within the package they are testing. -// -// Functions of the form -// func BenchmarkXxx(*testing.B) -// are considered benchmarks, and are executed by go test when the -test.bench -// flag is provided. -// -// A sample benchmark function looks like this: -// func BenchmarkHello(b *testing.B) { -// for i := 0; i < b.N; i++ { -// fmt.Sprintf("hello") -// } -// } -// The benchmark package will vary b.N until the benchmark function lasts -// long enough to be timed reliably. The output -// testing.BenchmarkHello 10000000 282 ns/op -// means that the loop ran 10000000 times at a speed of 282 ns per loop. -// -// If a benchmark needs some expensive setup before running, the timer -// may be stopped: -// func BenchmarkBigLen(b *testing.B) { -// b.StopTimer() -// big := NewBig() -// b.StartTimer() -// for i := 0; i < b.N; i++ { -// big.Len() -// } -// } -package testing - -import ( - "flag" - "fmt" - "os" - "runtime" - "runtime/pprof" - "strconv" - "strings" - "time" -) - -var ( - // The short flag requests that tests run more quickly, but its functionality - // is provided by test writers themselves. The testing package is just its - // home. The all.bash installation script sets it to make installation more - // efficient, but by default the flag is off so a plain "go test" will do a - // full test of the package. - short = flag.Bool("test.short", false, "run smaller test suite to save time") - - // Report as tests are run; default is silent for success. - chatty = flag.Bool("test.v", false, "verbose: print additional output") - match = flag.String("test.run", "", "regular expression to select tests to run") - memProfile = flag.String("test.memprofile", "", "write a memory profile to the named file after execution") - memProfileRate = flag.Int("test.memprofilerate", 0, "if >=0, sets runtime.MemProfileRate") - cpuProfile = flag.String("test.cpuprofile", "", "write a cpu profile to the named file during execution") - timeout = flag.Duration("test.timeout", 0, "if positive, sets an aggregate time limit for all tests") - cpuListStr = flag.String("test.cpu", "", "comma-separated list of number of CPUs to use for each test") - parallel = flag.Int("test.parallel", runtime.GOMAXPROCS(0), "maximum test parallelism") - - cpuList []int -) - -// common holds the elements common between T and B and -// captures common methods such as Errorf. -type common struct { - output []byte // Output generated by test or benchmark. - failed bool // Test or benchmark has failed. - start time.Time // Time test or benchmark started - duration time.Duration - self interface{} // To be sent on signal channel when done. - signal chan interface{} // Output for serial tests. -} - -// Short reports whether the -test.short flag is set. -func Short() bool { - return *short -} - -// decorate inserts the final newline if needed and indentation tabs for formatting. -// If addFileLine is true, it also prefixes the string with the file and line of the call site. -func decorate(s string, addFileLine bool) string { - if addFileLine { - _, file, line, ok := runtime.Caller(3) // decorate + log + public function. - if ok { - // Truncate file name at last file name separator. - if index := strings.LastIndex(file, "/"); index >= 0 { - file = file[index+1:] - } else if index = strings.LastIndex(file, "\\"); index >= 0 { - file = file[index+1:] - } - } else { - file = "???" - line = 1 - } - s = fmt.Sprintf("%s:%d: %s", file, line, s) - } - s = "\t" + s // Every line is indented at least one tab. - n := len(s) - if n > 0 && s[n-1] != '\n' { - s += "\n" - n++ - } - for i := 0; i < n-1; i++ { // -1 to avoid final newline - if s[i] == '\n' { - // Second and subsequent lines are indented an extra tab. - return s[0:i+1] + "\t" + decorate(s[i+1:n], false) - } - } - return s -} - -// T is a type passed to Test functions to manage test state and support formatted test logs. -// Logs are accumulated during execution and dumped to standard error when done. -type T struct { - common - name string // Name of test. - startParallel chan bool // Parallel tests will wait on this. -} - -// Fail marks the function as having failed but continues execution. -func (c *common) Fail() { c.failed = true } - -// Failed returns whether the function has failed. -func (c *common) Failed() bool { return c.failed } - -// FailNow marks the function as having failed and stops its execution. -// Execution will continue at the next Test. -func (c *common) FailNow() { - c.Fail() - - // Calling runtime.Goexit will exit the goroutine, which - // will run the deferred functions in this goroutine, - // which will eventually run the deferred lines in tRunner, - // which will signal to the test loop that this test is done. - // - // A previous version of this code said: - // - // c.duration = ... - // c.signal <- c.self - // runtime.Goexit() - // - // This previous version duplicated code (those lines are in - // tRunner no matter what), but worse the goroutine teardown - // implicit in runtime.Goexit was not guaranteed to complete - // before the test exited. If a test deferred an important cleanup - // function (like removing temporary files), there was no guarantee - // it would run on a test failure. Because we send on c.signal during - // a top-of-stack deferred function now, we know that the send - // only happens after any other stacked defers have completed. - runtime.Goexit() -} - -// log generates the output. It's always at the same stack depth. -func (c *common) log(s string) { - c.output = append(c.output, decorate(s, true)...) -} - -// Log formats its arguments using default formatting, analogous to Println(), -// and records the text in the error log. -func (c *common) Log(args ...interface{}) { c.log(fmt.Sprintln(args...)) } - -// Logf formats its arguments according to the format, analogous to Printf(), -// and records the text in the error log. -func (c *common) Logf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) } - -// Error is equivalent to Log() followed by Fail(). -func (c *common) Error(args ...interface{}) { - c.log(fmt.Sprintln(args...)) - c.Fail() -} - -// Errorf is equivalent to Logf() followed by Fail(). -func (c *common) Errorf(format string, args ...interface{}) { - c.log(fmt.Sprintf(format, args...)) - c.Fail() -} - -// Fatal is equivalent to Log() followed by FailNow(). -func (c *common) Fatal(args ...interface{}) { - c.log(fmt.Sprintln(args...)) - c.FailNow() -} - -// Fatalf is equivalent to Logf() followed by FailNow(). -func (c *common) Fatalf(format string, args ...interface{}) { - c.log(fmt.Sprintf(format, args...)) - c.FailNow() -} - -// Parallel signals that this test is to be run in parallel with (and only with) -// other parallel tests in this CPU group. -func (t *T) Parallel() { - t.signal <- (*T)(nil) // Release main testing loop - <-t.startParallel // Wait for serial tests to finish -} - -// An internal type but exported because it is cross-package; part of the implementation -// of go test. -type InternalTest struct { - Name string - F func(*T) -} - -func tRunner(t *T, test *InternalTest) { - t.start = time.Now() - - // When this goroutine is done, either because test.F(t) - // returned normally or because a test failure triggered - // a call to runtime.Goexit, record the duration and send - // a signal saying that the test is done. - defer func() { - t.duration = time.Now().Sub(t.start) - t.signal <- t - }() - - test.F(t) -} - -// An internal function but exported because it is cross-package; part of the implementation -// of go test. -func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) { - flag.Parse() - parseCpuList() - - before() - startAlarm() - testOk := RunTests(matchString, tests) - exampleOk := RunExamples(examples) - if !testOk || !exampleOk { - fmt.Println("FAIL") - os.Exit(1) - } - fmt.Println("PASS") - stopAlarm() - RunBenchmarks(matchString, benchmarks) - after() -} - -func (t *T) report() { - tstr := fmt.Sprintf("(%.2f seconds)", t.duration.Seconds()) - format := "--- %s: %s %s\n%s" - if t.failed { - fmt.Printf(format, "FAIL", t.name, tstr, t.output) - } else if *chatty { - fmt.Printf(format, "PASS", t.name, tstr, t.output) - } -} - -func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) { - ok = true - if len(tests) == 0 { - fmt.Fprintln(os.Stderr, "testing: warning: no tests to run") - return - } - for _, procs := range cpuList { - runtime.GOMAXPROCS(procs) - // We build a new channel tree for each run of the loop. - // collector merges in one channel all the upstream signals from parallel tests. - // If all tests pump to the same channel, a bug can occur where a test - // kicks off a goroutine that Fails, yet the test still delivers a completion signal, - // which skews the counting. - var collector = make(chan interface{}) - - numParallel := 0 - startParallel := make(chan bool) - - for i := 0; i < len(tests); i++ { - matched, err := matchString(*match, tests[i].Name) - if err != nil { - fmt.Fprintf(os.Stderr, "testing: invalid regexp for -test.run: %s\n", err) - os.Exit(1) - } - if !matched { - continue - } - testName := tests[i].Name - if procs != 1 { - testName = fmt.Sprintf("%s-%d", tests[i].Name, procs) - } - t := &T{ - common: common{ - signal: make(chan interface{}), - }, - name: testName, - startParallel: startParallel, - } - t.self = t - if *chatty { - fmt.Printf("=== RUN %s\n", t.name) - } - go tRunner(t, &tests[i]) - out := (<-t.signal).(*T) - if out == nil { // Parallel run. - go func() { - collector <- <-t.signal - }() - numParallel++ - continue - } - t.report() - ok = ok && !out.failed - } - - running := 0 - for numParallel+running > 0 { - if running < *parallel && numParallel > 0 { - startParallel <- true - running++ - numParallel-- - continue - } - t := (<-collector).(*T) - t.report() - ok = ok && !t.failed - running-- - } - } - return -} - -// before runs before all testing. -func before() { - if *memProfileRate > 0 { - runtime.MemProfileRate = *memProfileRate - } - if *cpuProfile != "" { - f, err := os.Create(*cpuProfile) - if err != nil { - fmt.Fprintf(os.Stderr, "testing: %s", err) - return - } - if err := pprof.StartCPUProfile(f); err != nil { - fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s", err) - f.Close() - return - } - // Could save f so after can call f.Close; not worth the effort. - } - -} - -// after runs after all testing. -func after() { - if *cpuProfile != "" { - pprof.StopCPUProfile() // flushes profile to disk - } - if *memProfile != "" { - f, err := os.Create(*memProfile) - if err != nil { - fmt.Fprintf(os.Stderr, "testing: %s", err) - return - } - if err = pprof.WriteHeapProfile(f); err != nil { - fmt.Fprintf(os.Stderr, "testing: can't write %s: %s", *memProfile, err) - } - f.Close() - } -} - -var timer *time.Timer - -// startAlarm starts an alarm if requested. -func startAlarm() { - if *timeout > 0 { - timer = time.AfterFunc(*timeout, alarm) - } -} - -// stopAlarm turns off the alarm. -func stopAlarm() { - if *timeout > 0 { - timer.Stop() - } -} - -// alarm is called if the timeout expires. -func alarm() { - panic("test timed out") -} - -func parseCpuList() { - if len(*cpuListStr) == 0 { - cpuList = append(cpuList, runtime.GOMAXPROCS(-1)) - } else { - for _, val := range strings.Split(*cpuListStr, ",") { - cpu, err := strconv.Atoi(val) - if err != nil || cpu <= 0 { - fmt.Fprintf(os.Stderr, "testing: invalid value %q for -test.cpu", val) - os.Exit(1) - } - cpuList = append(cpuList, cpu) - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/format/format.go b/gcc-4.8.1/libgo/go/go/format/format.go deleted file mode 100644 index 65b0e4e4b..000000000 --- a/gcc-4.8.1/libgo/go/go/format/format.go +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package format implements standard formatting of Go source. -package format - -import ( - "bytes" - "fmt" - "go/ast" - "go/parser" - "go/printer" - "go/token" - "io" - "strings" -) - -var config = printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8} - -// Node formats node in canonical gofmt style and writes the result to dst. -// -// The node type must be *ast.File, *printer.CommentedNode, []ast.Decl, -// []ast.Stmt, or assignment-compatible to ast.Expr, ast.Decl, ast.Spec, -// or ast.Stmt. Node does not modify node. Imports are not sorted for -// nodes representing partial source files (i.e., if the node is not an -// *ast.File or a *printer.CommentedNode not wrapping an *ast.File). -// -// The function may return early (before the entire result is written) -// and return a formatting error, for instance due to an incorrect AST. -// -func Node(dst io.Writer, fset *token.FileSet, node interface{}) error { - // Determine if we have a complete source file (file != nil). - var file *ast.File - var cnode *printer.CommentedNode - switch n := node.(type) { - case *ast.File: - file = n - case *printer.CommentedNode: - if f, ok := n.Node.(*ast.File); ok { - file = f - cnode = n - } - } - - // Sort imports if necessary. - if file != nil && hasUnsortedImports(file) { - // Make a copy of the AST because ast.SortImports is destructive. - // TODO(gri) Do this more efficiently. - var buf bytes.Buffer - err := config.Fprint(&buf, fset, file) - if err != nil { - return err - } - file, err = parser.ParseFile(fset, "", buf.Bytes(), parser.ParseComments) - if err != nil { - // We should never get here. If we do, provide good diagnostic. - return fmt.Errorf("format.Node internal error (%s)", err) - } - ast.SortImports(fset, file) - - // Use new file with sorted imports. - node = file - if cnode != nil { - node = &printer.CommentedNode{Node: file, Comments: cnode.Comments} - } - } - - return config.Fprint(dst, fset, node) -} - -// Source formats src in canonical gofmt style and writes the result to dst -// or returns an I/O or syntax error. src is expected to be a syntactically -// correct Go source file, or a list of Go declarations or statements. -// -// If src is a partial source file, the leading and trailing space of src -// is applied to the result (such that it has the same leading and trailing -// space as src), and the formatted src is indented by the same amount as -// the first line of src containing code. Imports are not sorted for partial -// source files. -// -func Source(src []byte) ([]byte, error) { - fset := token.NewFileSet() - node, err := parse(fset, src) - if err != nil { - return nil, err - } - - var buf bytes.Buffer - if file, ok := node.(*ast.File); ok { - // Complete source file. - ast.SortImports(fset, file) - err := config.Fprint(&buf, fset, file) - if err != nil { - return nil, err - } - - } else { - // Partial source file. - // Determine and prepend leading space. - i, j := 0, 0 - for j < len(src) && isSpace(src[j]) { - if src[j] == '\n' { - i = j + 1 // index of last line in leading space - } - j++ - } - buf.Write(src[:i]) - - // Determine indentation of first code line. - // Spaces are ignored unless there are no tabs, - // in which case spaces count as one tab. - indent := 0 - hasSpace := false - for _, b := range src[i:j] { - switch b { - case ' ': - hasSpace = true - case '\t': - indent++ - } - } - if indent == 0 && hasSpace { - indent = 1 - } - - // Format the source. - cfg := config - cfg.Indent = indent - err := cfg.Fprint(&buf, fset, node) - if err != nil { - return nil, err - } - - // Determine and append trailing space. - i = len(src) - for i > 0 && isSpace(src[i-1]) { - i-- - } - buf.Write(src[i:]) - } - - return buf.Bytes(), nil -} - -func hasUnsortedImports(file *ast.File) bool { - for _, d := range file.Decls { - d, ok := d.(*ast.GenDecl) - if !ok || d.Tok != token.IMPORT { - // Not an import declaration, so we're done. - // Imports are always first. - return false - } - if d.Lparen.IsValid() { - // For now assume all grouped imports are unsorted. - // TODO(gri) Should check if they are sorted already. - return true - } - // Ungrouped imports are sorted by default. - } - return false -} - -func isSpace(b byte) bool { - return b == ' ' || b == '\t' || b == '\n' || b == '\r' -} - -func parse(fset *token.FileSet, src []byte) (interface{}, error) { - // Try as a complete source file. - file, err := parser.ParseFile(fset, "", src, parser.ParseComments) - if err == nil { - return file, nil - } - // If the source is missing a package clause, try as a source fragment; otherwise fail. - if !strings.Contains(err.Error(), "expected 'package'") { - return nil, err - } - - // Try as a declaration list by prepending a package clause in front of src. - // Use ';' not '\n' to keep line numbers intact. - psrc := append([]byte("package p;"), src...) - file, err = parser.ParseFile(fset, "", psrc, parser.ParseComments) - if err == nil { - return file.Decls, nil - } - // If the source is missing a declaration, try as a statement list; otherwise fail. - if !strings.Contains(err.Error(), "expected declaration") { - return nil, err - } - - // Try as statement list by wrapping a function around src. - fsrc := append(append([]byte("package p; func _() {"), src...), '}') - file, err = parser.ParseFile(fset, "", fsrc, parser.ParseComments) - if err == nil { - return file.Decls[0].(*ast.FuncDecl).Body.List, nil - } - - // Failed, and out of options. - return nil, err -} diff --git a/gcc-4.8.1/libgo/go/go/format/format_test.go b/gcc-4.8.1/libgo/go/go/format/format_test.go deleted file mode 100644 index 7d7940bb5..000000000 --- a/gcc-4.8.1/libgo/go/go/format/format_test.go +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package format - -import ( - "bytes" - "go/parser" - "go/token" - "io/ioutil" - "strings" - "testing" -) - -const testfile = "format_test.go" - -func diff(t *testing.T, dst, src []byte) { - line := 1 - offs := 0 // line offset - for i := 0; i < len(dst) && i < len(src); i++ { - d := dst[i] - s := src[i] - if d != s { - t.Errorf("dst:%d: %s\n", line, dst[offs:i+1]) - t.Errorf("src:%d: %s\n", line, src[offs:i+1]) - return - } - if s == '\n' { - line++ - offs = i + 1 - } - } - if len(dst) != len(src) { - t.Errorf("len(dst) = %d, len(src) = %d\nsrc = %q", len(dst), len(src), src) - } -} - -func TestNode(t *testing.T) { - src, err := ioutil.ReadFile(testfile) - if err != nil { - t.Fatal(err) - } - - fset := token.NewFileSet() - file, err := parser.ParseFile(fset, testfile, src, parser.ParseComments) - if err != nil { - t.Fatal(err) - } - - var buf bytes.Buffer - - if err = Node(&buf, fset, file); err != nil { - t.Fatal("Node failed:", err) - } - - diff(t, buf.Bytes(), src) -} - -func TestSource(t *testing.T) { - src, err := ioutil.ReadFile(testfile) - if err != nil { - t.Fatal(err) - } - - res, err := Source(src) - if err != nil { - t.Fatal("Source failed:", err) - } - - diff(t, res, src) -} - -// Test cases that are expected to fail are marked by the prefix "ERROR". -var tests = []string{ - // declaration lists - `import "go/format"`, - "var x int", - "var x int\n\ntype T struct{}", - - // statement lists - "x := 0", - "f(a, b, c)\nvar x int = f(1, 2, 3)", - - // indentation, leading and trailing space - "\tx := 0\n\tgo f()", - "\tx := 0\n\tgo f()\n\n\n", - "\n\t\t\n\n\tx := 0\n\tgo f()\n\n\n", - "\n\t\t\n\n\t\t\tx := 0\n\t\t\tgo f()\n\n\n", - "\n\t\t\n\n\t\t\tx := 0\n\t\t\tconst s = `\nfoo\n`\n\n\n", // no indentation inside raw strings - - // erroneous programs - "ERRORvar x", - "ERROR1 + 2 +", - "ERRORx := 0", -} - -func String(s string) (string, error) { - res, err := Source([]byte(s)) - if err != nil { - return "", err - } - return string(res), nil -} - -func TestPartial(t *testing.T) { - for _, src := range tests { - if strings.HasPrefix(src, "ERROR") { - // test expected to fail - src = src[5:] // remove ERROR prefix - res, err := String(src) - if err == nil && res == src { - t.Errorf("formatting succeeded but was expected to fail:\n%q", src) - } - } else { - // test expected to succeed - res, err := String(src) - if err != nil { - t.Errorf("formatting failed (%s):\n%q", err, src) - } else if res != src { - t.Errorf("formatting incorrect:\nsource: %q\nresult: %q", src, res) - } - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/parser/error_test.go b/gcc-4.8.1/libgo/go/go/parser/error_test.go deleted file mode 100644 index 8d06d1c84..000000000 --- a/gcc-4.8.1/libgo/go/go/parser/error_test.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements a parser test harness. The files in the testdata -// directory are parsed and the errors reported are compared against the -// error messages expected in the test files. The test files must end in -// .src rather than .go so that they are not disturbed by gofmt runs. -// -// Expected errors are indicated in the test files by putting a comment -// of the form /* ERROR "rx" */ immediately following an offending token. -// The harness will verify that an error matching the regular expression -// rx is reported at that source position. -// -// For instance, the following test file indicates that a "not declared" -// error should be reported for the undeclared variable x: -// -// package p -// func f() { -// _ = x /* ERROR "not declared" */ + 1 -// } - -package parser - -import ( - "go/scanner" - "go/token" - "io/ioutil" - "path/filepath" - "regexp" - "strings" - "testing" -) - -const testdata = "testdata" - -var fsetErrs *token.FileSet - -// getFile assumes that each filename occurs at most once -func getFile(filename string) (file *token.File) { - fsetErrs.Iterate(func(f *token.File) bool { - if f.Name() == filename { - if file != nil { - panic(filename + " used multiple times") - } - file = f - } - return true - }) - return file -} - -func getPos(filename string, offset int) token.Pos { - if f := getFile(filename); f != nil { - return f.Pos(offset) - } - return token.NoPos -} - -// ERROR comments must be of the form /* ERROR "rx" */ and rx is -// a regular expression that matches the expected error message. -// -var errRx = regexp.MustCompile(`^/\* *ERROR *"([^"]*)" *\*/$`) - -// expectedErrors collects the regular expressions of ERROR comments found -// in files and returns them as a map of error positions to error messages. -// -func expectedErrors(t *testing.T, filename string, src []byte) map[token.Pos]string { - errors := make(map[token.Pos]string) - - var s scanner.Scanner - // file was parsed already - do not add it again to the file - // set otherwise the position information returned here will - // not match the position information collected by the parser - s.Init(getFile(filename), src, nil, scanner.ScanComments) - var prev token.Pos // position of last non-comment, non-semicolon token - - for { - pos, tok, lit := s.Scan() - switch tok { - case token.EOF: - return errors - case token.COMMENT: - s := errRx.FindStringSubmatch(lit) - if len(s) == 2 { - errors[prev] = string(s[1]) - } - default: - prev = pos - } - } - - panic("unreachable") -} - -// compareErrors compares the map of expected error messages with the list -// of found errors and reports discrepancies. -// -func compareErrors(t *testing.T, expected map[token.Pos]string, found scanner.ErrorList) { - for _, error := range found { - // error.Pos is a token.Position, but we want - // a token.Pos so we can do a map lookup - pos := getPos(error.Pos.Filename, error.Pos.Offset) - if msg, found := expected[pos]; found { - // we expect a message at pos; check if it matches - rx, err := regexp.Compile(msg) - if err != nil { - t.Errorf("%s: %v", error.Pos, err) - continue - } - if match := rx.MatchString(error.Msg); !match { - t.Errorf("%s: %q does not match %q", error.Pos, error.Msg, msg) - continue - } - // we have a match - eliminate this error - delete(expected, pos) - } else { - // To keep in mind when analyzing failed test output: - // If the same error position occurs multiple times in errors, - // this message will be triggered (because the first error at - // the position removes this position from the expected errors). - t.Errorf("%s: unexpected error: %s", error.Pos, error.Msg) - } - } - - // there should be no expected errors left - if len(expected) > 0 { - t.Errorf("%d errors not reported:", len(expected)) - for pos, msg := range expected { - t.Errorf("%s: %s\n", fsetErrs.Position(pos), msg) - } - } -} - -func checkErrors(t *testing.T, filename string, input interface{}) { - src, err := readSource(filename, input) - if err != nil { - t.Error(err) - return - } - - _, err = ParseFile(fsetErrs, filename, src, DeclarationErrors) - found, ok := err.(scanner.ErrorList) - if err != nil && !ok { - t.Error(err) - return - } - - // we are expecting the following errors - // (collect these after parsing a file so that it is found in the file set) - expected := expectedErrors(t, filename, src) - - // verify errors returned by the parser - compareErrors(t, expected, found) -} - -func TestErrors(t *testing.T) { - fsetErrs = token.NewFileSet() - list, err := ioutil.ReadDir(testdata) - if err != nil { - t.Fatal(err) - } - for _, fi := range list { - name := fi.Name() - if !fi.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".src") { - checkErrors(t, filepath.Join(testdata, name), nil) - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/parser/interface.go b/gcc-4.8.1/libgo/go/go/parser/interface.go deleted file mode 100644 index fac513e55..000000000 --- a/gcc-4.8.1/libgo/go/go/parser/interface.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains the exported entry points for invoking the parser. - -package parser - -import ( - "bytes" - "errors" - "go/ast" - "go/token" - "io" - "io/ioutil" - "os" - "path/filepath" -) - -// If src != nil, readSource converts src to a []byte if possible; -// otherwise it returns an error. If src == nil, readSource returns -// the result of reading the file specified by filename. -// -func readSource(filename string, src interface{}) ([]byte, error) { - if src != nil { - switch s := src.(type) { - case string: - return []byte(s), nil - case []byte: - return s, nil - case *bytes.Buffer: - // is io.Reader, but src is already available in []byte form - if s != nil { - return s.Bytes(), nil - } - case io.Reader: - var buf bytes.Buffer - if _, err := io.Copy(&buf, s); err != nil { - return nil, err - } - return buf.Bytes(), nil - } - return nil, errors.New("invalid source") - } - return ioutil.ReadFile(filename) -} - -// A Mode value is a set of flags (or 0). -// They control the amount of source code parsed and other optional -// parser functionality. -// -type Mode uint - -const ( - PackageClauseOnly Mode = 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 - DeclarationErrors // report declaration errors - SpuriousErrors // report all (not just the first) errors per line -) - -// ParseFile parses the source code of a single Go source file and returns -// the corresponding ast.File node. The source code may be provided via -// the filename of the source file, or via the src parameter. -// -// If src != nil, ParseFile parses the source from src and the filename is -// only used when recording position information. The type of the argument -// for the src parameter must be string, []byte, or io.Reader. -// If src == nil, ParseFile parses the file specified by filename. -// -// The mode parameter controls the amount of source text parsed and other -// optional parser functionality. Position information is recorded in the -// file set fset. -// -// If the source couldn't be read, the returned AST is nil and the error -// indicates the specific failure. If the source was read but syntax -// errors were found, the result is a partial AST (with ast.Bad* nodes -// representing the fragments of erroneous source code). Multiple errors -// are returned via a scanner.ErrorList which is sorted by file position. -// -func ParseFile(fset *token.FileSet, filename string, src interface{}, mode Mode) (*ast.File, error) { - // get source - text, err := readSource(filename, src) - if err != nil { - return nil, err - } - - // parse source - var p parser - p.init(fset, filename, text, mode) - f := p.parseFile() - if f == nil { - // source is not a valid Go source file - satisfy - // ParseFile API and return a valid (but) empty - // *ast.File - f = &ast.File{ - Name: new(ast.Ident), - Scope: ast.NewScope(nil), - } - } - - // sort errors - if p.mode&SpuriousErrors == 0 { - p.errors.RemoveMultiples() - } else { - p.errors.Sort() - } - - return f, p.errors.Err() -} - -// ParseDir calls ParseFile for the files in the directory specified by path and -// returns a map of package name -> package AST with all the packages found. If -// filter != nil, only the files with os.FileInfo entries passing through the filter -// are considered. The mode bits are passed to ParseFile unchanged. Position -// information is recorded in the file set fset. -// -// If the directory couldn't be read, a nil map and the respective error are -// returned. If a parse error occurred, a non-nil but incomplete map and the -// first error encountered are returned. -// -func ParseDir(fset *token.FileSet, path string, filter func(os.FileInfo) bool, mode Mode) (pkgs map[string]*ast.Package, first error) { - fd, err := os.Open(path) - if err != nil { - return nil, err - } - defer fd.Close() - - list, err := fd.Readdir(-1) - if err != nil { - return nil, err - } - - pkgs = make(map[string]*ast.Package) - for _, d := range list { - if filter == nil || filter(d) { - filename := filepath.Join(path, d.Name()) - if src, err := ParseFile(fset, filename, nil, mode); err == nil { - name := src.Name.Name - pkg, found := pkgs[name] - if !found { - pkg = &ast.Package{ - Name: name, - Files: make(map[string]*ast.File), - } - pkgs[name] = pkg - } - pkg.Files[filename] = src - } else if first == nil { - first = err - } - } - } - - return -} - -// ParseExpr is a convenience function for obtaining the AST of an expression x. -// The position information recorded in the AST is undefined. -// -func ParseExpr(x string) (ast.Expr, error) { - // parse x within the context of a complete package for correct scopes; - // use //line directive for correct positions in error messages and put - // x alone on a separate line (handles line comments), followed by a ';' - // to force an error if the expression is incomplete - file, err := ParseFile(token.NewFileSet(), "", "package p;func _(){_=\n//line :1\n"+x+"\n;}", 0) - if err != nil { - return nil, err - } - return file.Decls[0].(*ast.FuncDecl).Body.List[0].(*ast.AssignStmt).Rhs[0], nil -} diff --git a/gcc-4.8.1/libgo/go/go/parser/parser.go b/gcc-4.8.1/libgo/go/go/parser/parser.go deleted file mode 100644 index 959af3872..000000000 --- a/gcc-4.8.1/libgo/go/go/parser/parser.go +++ /dev/null @@ -1,2392 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package parser implements a parser for Go source files. Input may be -// provided in a variety of forms (see the various Parse* functions); the -// output is an abstract syntax tree (AST) representing the Go source. The -// parser is invoked through one of the Parse* functions. -// -package parser - -import ( - "fmt" - "go/ast" - "go/scanner" - "go/token" - "strconv" - "strings" - "unicode" -) - -// The parser structure holds the parser's internal state. -type parser struct { - file *token.File - errors scanner.ErrorList - scanner scanner.Scanner - - // Tracing/debugging - mode Mode // parsing mode - trace bool // == (mode & Trace != 0) - indent int // indentation used for tracing output - - // Comments - comments []*ast.CommentGroup - leadComment *ast.CommentGroup // last lead comment - lineComment *ast.CommentGroup // last line comment - - // Next token - pos token.Pos // token position - tok token.Token // one token look-ahead - lit string // token literal - - // Error recovery - // (used to limit the number of calls to syncXXX functions - // w/o making scanning progress - avoids potential endless - // loops across multiple parser functions during error recovery) - syncPos token.Pos // last synchronization position - syncCnt int // number of calls to syncXXX without progress - - // Non-syntactic parser control - exprLev int // < 0: in control clause, >= 0: in expression - - // Ordinary identifier scopes - pkgScope *ast.Scope // pkgScope.Outer == nil - topScope *ast.Scope // top-most scope; may be pkgScope - unresolved []*ast.Ident // unresolved identifiers - imports []*ast.ImportSpec // list of imports - - // Label scopes - // (maintained by open/close LabelScope) - labelScope *ast.Scope // label scope for current function - targetStack [][]*ast.Ident // stack of unresolved labels -} - -func (p *parser) init(fset *token.FileSet, filename string, src []byte, mode Mode) { - p.file = fset.AddFile(filename, fset.Base(), len(src)) - var m scanner.Mode - if mode&ParseComments != 0 { - m = scanner.ScanComments - } - eh := func(pos token.Position, msg string) { p.errors.Add(pos, msg) } - p.scanner.Init(p.file, src, eh, m) - - p.mode = mode - p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently) - - p.next() -} - -// ---------------------------------------------------------------------------- -// Scoping support - -func (p *parser) openScope() { - p.topScope = ast.NewScope(p.topScope) -} - -func (p *parser) closeScope() { - p.topScope = p.topScope.Outer -} - -func (p *parser) openLabelScope() { - p.labelScope = ast.NewScope(p.labelScope) - p.targetStack = append(p.targetStack, nil) -} - -func (p *parser) closeLabelScope() { - // resolve labels - n := len(p.targetStack) - 1 - scope := p.labelScope - for _, ident := range p.targetStack[n] { - ident.Obj = scope.Lookup(ident.Name) - if ident.Obj == nil && p.mode&DeclarationErrors != 0 { - p.error(ident.Pos(), fmt.Sprintf("label %s undefined", ident.Name)) - } - } - // pop label scope - p.targetStack = p.targetStack[0:n] - p.labelScope = p.labelScope.Outer -} - -func (p *parser) declare(decl, data interface{}, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) { - for _, ident := range idents { - assert(ident.Obj == nil, "identifier already declared or resolved") - obj := ast.NewObj(kind, ident.Name) - // remember the corresponding declaration for redeclaration - // errors and global variable resolution/typechecking phase - obj.Decl = decl - obj.Data = data - ident.Obj = obj - if ident.Name != "_" { - if alt := scope.Insert(obj); alt != nil && p.mode&DeclarationErrors != 0 { - prevDecl := "" - if pos := alt.Pos(); pos.IsValid() { - prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", p.file.Position(pos)) - } - p.error(ident.Pos(), fmt.Sprintf("%s redeclared in this block%s", ident.Name, prevDecl)) - } - } - } -} - -func (p *parser) shortVarDecl(decl *ast.AssignStmt, list []ast.Expr) { - // Go spec: A short variable declaration may redeclare variables - // provided they were originally declared in the same block with - // the same type, and at least one of the non-blank variables is new. - n := 0 // number of new variables - for _, x := range list { - if ident, isIdent := x.(*ast.Ident); isIdent { - assert(ident.Obj == nil, "identifier already declared or resolved") - obj := ast.NewObj(ast.Var, ident.Name) - // remember corresponding assignment for other tools - obj.Decl = decl - ident.Obj = obj - if ident.Name != "_" { - if alt := p.topScope.Insert(obj); alt != nil { - ident.Obj = alt // redeclaration - } else { - n++ // new declaration - } - } - } else { - p.errorExpected(x.Pos(), "identifier on left side of :=") - } - } - if n == 0 && p.mode&DeclarationErrors != 0 { - p.error(list[0].Pos(), "no new variables on left side of :=") - } -} - -// The unresolved object is a sentinel to mark identifiers that have been added -// to the list of unresolved identifiers. The sentinel is only used for verifying -// internal consistency. -var unresolved = new(ast.Object) - -// If x is an identifier, tryResolve attempts to resolve x by looking up -// the object it denotes. If no object is found and collectUnresolved is -// set, x is marked as unresolved and collected in the list of unresolved -// identifiers. -// -func (p *parser) tryResolve(x ast.Expr, collectUnresolved bool) { - // nothing to do if x is not an identifier or the blank identifier - ident, _ := x.(*ast.Ident) - if ident == nil { - return - } - assert(ident.Obj == nil, "identifier already declared or resolved") - if ident.Name == "_" { - return - } - // try to resolve the identifier - for s := p.topScope; s != nil; s = s.Outer { - if obj := s.Lookup(ident.Name); obj != nil { - ident.Obj = obj - return - } - } - // all local scopes are known, so any unresolved identifier - // must be found either in the file scope, package scope - // (perhaps in another file), or universe scope --- collect - // them so that they can be resolved later - if collectUnresolved { - ident.Obj = unresolved - p.unresolved = append(p.unresolved, ident) - } -} - -func (p *parser) resolve(x ast.Expr) { - p.tryResolve(x, true) -} - -// ---------------------------------------------------------------------------- -// Parsing support - -func (p *parser) printTrace(a ...interface{}) { - const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " - const n = len(dots) - pos := p.file.Position(p.pos) - fmt.Printf("%5d:%3d: ", pos.Line, pos.Column) - i := 2 * p.indent - for i > n { - fmt.Print(dots) - i -= n - } - // i <= n - fmt.Print(dots[0:i]) - fmt.Println(a...) -} - -func trace(p *parser, msg string) *parser { - p.printTrace(msg, "(") - p.indent++ - return p -} - -// Usage pattern: defer un(trace(p, "...")) -func un(p *parser) { - p.indent-- - p.printTrace(")") -} - -// Advance to the next token. -func (p *parser) next0() { - // Because of one-token look-ahead, print the previous token - // when tracing as it provides a more readable output. The - // very first token (!p.pos.IsValid()) is not initialized - // (it is token.ILLEGAL), so don't print it . - if p.trace && p.pos.IsValid() { - s := p.tok.String() - switch { - case p.tok.IsLiteral(): - p.printTrace(s, p.lit) - case p.tok.IsOperator(), p.tok.IsKeyword(): - p.printTrace("\"" + s + "\"") - default: - p.printTrace(s) - } - } - - 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.file.Line(p.pos) - if p.lit[1] == '*' { - // don't use range here - no need to decode Unicode code points - for i := 0; i < len(p.lit); i++ { - if p.lit[i] == '\n' { - endline++ - } - } - } - - comment = &ast.Comment{Slash: p.pos, Text: p.lit} - p.next0() - - return -} - -// Consume a group of adjacent comments, add it to the parser's -// comments list, and return it together with the line at which -// the last comment in the group ends. A non-comment token or n -// empty lines terminate a comment group. -// -func (p *parser) consumeCommentGroup(n int) (comments *ast.CommentGroup, endline int) { - var list []*ast.Comment - endline = p.file.Line(p.pos) - for p.tok == token.COMMENT && p.file.Line(p.pos) <= endline+n { - var comment *ast.Comment - comment, endline = p.consumeComment() - list = append(list, comment) - } - - // add comment group to the comments list - comments = &ast.CommentGroup{List: list} - p.comments = append(p.comments, comments) - - return -} - -// Advance to the next non-comment token. In the process, collect -// any comment groups encountered, and remember the last lead and -// and line comments. -// -// A lead comment is a comment group that starts and ends in a -// line without any other tokens and that is followed by a non-comment -// token on the line immediately after the comment group. -// -// A line comment is a comment group that follows a non-comment -// token on the same line, and that has no tokens after it on the line -// where it ends. -// -// Lead and line comments may be considered documentation that is -// stored in the AST. -// -func (p *parser) next() { - p.leadComment = nil - p.lineComment = nil - prev := p.pos - p.next0() - - if p.tok == token.COMMENT { - var comment *ast.CommentGroup - var endline int - - if p.file.Line(p.pos) == p.file.Line(prev) { - // The comment is on same line as the previous token; it - // cannot be a lead comment but may be a line comment. - comment, endline = p.consumeCommentGroup(0) - if p.file.Line(p.pos) != endline { - // The next token is on a different line, thus - // the last comment group is a line comment. - p.lineComment = comment - } - } - - // consume successor comments, if any - endline = -1 - for p.tok == token.COMMENT { - comment, endline = p.consumeCommentGroup(1) - } - - if endline+1 == p.file.Line(p.pos) { - // The next token is following on the line immediately after the - // comment group, thus the last comment group is a lead comment. - p.leadComment = comment - } - } -} - -func (p *parser) error(pos token.Pos, msg string) { - p.errors.Add(p.file.Position(pos), msg) -} - -func (p *parser) errorExpected(pos token.Pos, msg string) { - msg = "expected " + msg - if pos == p.pos { - // the error happened at the current position; - // make the error message more specific - if p.tok == token.SEMICOLON && p.lit == "\n" { - msg += ", found newline" - } else { - msg += ", found '" + p.tok.String() + "'" - if p.tok.IsLiteral() { - msg += " " + p.lit - } - } - } - p.error(pos, msg) -} - -func (p *parser) expect(tok token.Token) token.Pos { - pos := p.pos - if p.tok != tok { - p.errorExpected(pos, "'"+tok.String()+"'") - } - p.next() // make progress - return pos -} - -// expectClosing is like expect but provides a better error message -// for the common case of a missing comma before a newline. -// -func (p *parser) expectClosing(tok token.Token, context string) token.Pos { - if p.tok != tok && p.tok == token.SEMICOLON && p.lit == "\n" { - p.error(p.pos, "missing ',' before newline in "+context) - p.next() - } - return p.expect(tok) -} - -func (p *parser) expectSemi() { - // semicolon is optional before a closing ')' or '}' - if p.tok != token.RPAREN && p.tok != token.RBRACE { - if p.tok == token.SEMICOLON { - p.next() - } else { - p.errorExpected(p.pos, "';'") - syncStmt(p) - } - } -} - -func (p *parser) atComma(context string) bool { - if p.tok == token.COMMA { - return true - } - if p.tok == token.SEMICOLON && p.lit == "\n" { - p.error(p.pos, "missing ',' before newline in "+context) - return true // "insert" the comma and continue - - } - return false -} - -func assert(cond bool, msg string) { - if !cond { - panic("go/parser internal error: " + msg) - } -} - -// syncStmt advances to the next statement. -// Used for synchronization after an error. -// -func syncStmt(p *parser) { - for { - switch p.tok { - case token.BREAK, token.CONST, token.CONTINUE, token.DEFER, - token.FALLTHROUGH, token.FOR, token.GO, token.GOTO, - token.IF, token.RETURN, token.SELECT, token.SWITCH, - token.TYPE, token.VAR: - // Return only if parser made some progress since last - // sync or if it has not reached 10 sync calls without - // progress. Otherwise consume at least one token to - // avoid an endless parser loop (it is possible that - // both parseOperand and parseStmt call syncStmt and - // correctly do not advance, thus the need for the - // invocation limit p.syncCnt). - if p.pos == p.syncPos && p.syncCnt < 10 { - p.syncCnt++ - return - } - if p.pos > p.syncPos { - p.syncPos = p.pos - p.syncCnt = 0 - return - } - // Reaching here indicates a parser bug, likely an - // incorrect token list in this function, but it only - // leads to skipping of possibly correct code if a - // previous error is present, and thus is preferred - // over a non-terminating parse. - case token.EOF: - return - } - p.next() - } -} - -// syncDecl advances to the next declaration. -// Used for synchronization after an error. -// -func syncDecl(p *parser) { - for { - switch p.tok { - case token.CONST, token.TYPE, token.VAR: - // see comments in syncStmt - if p.pos == p.syncPos && p.syncCnt < 10 { - p.syncCnt++ - return - } - if p.pos > p.syncPos { - p.syncPos = p.pos - p.syncCnt = 0 - return - } - case token.EOF: - return - } - p.next() - } -} - -// ---------------------------------------------------------------------------- -// Identifiers - -func (p *parser) parseIdent() *ast.Ident { - pos := p.pos - name := "_" - if p.tok == token.IDENT { - name = p.lit - p.next() - } else { - p.expect(token.IDENT) // use expect() error handling - } - return &ast.Ident{NamePos: pos, Name: name} -} - -func (p *parser) parseIdentList() (list []*ast.Ident) { - if p.trace { - defer un(trace(p, "IdentList")) - } - - list = append(list, p.parseIdent()) - for p.tok == token.COMMA { - p.next() - list = append(list, p.parseIdent()) - } - - return -} - -// ---------------------------------------------------------------------------- -// Common productions - -// If lhs is set, result list elements which are identifiers are not resolved. -func (p *parser) parseExprList(lhs bool) (list []ast.Expr) { - if p.trace { - defer un(trace(p, "ExpressionList")) - } - - list = append(list, p.checkExpr(p.parseExpr(lhs))) - for p.tok == token.COMMA { - p.next() - list = append(list, p.checkExpr(p.parseExpr(lhs))) - } - - return -} - -func (p *parser) parseLhsList() []ast.Expr { - list := p.parseExprList(true) - switch p.tok { - case token.DEFINE: - // lhs of a short variable declaration - // but doesn't enter scope until later: - // caller must call p.shortVarDecl(p.makeIdentList(list)) - // at appropriate time. - case token.COLON: - // lhs of a label declaration or a communication clause of a select - // statement (parseLhsList is not called when parsing the case clause - // of a switch statement): - // - labels are declared by the caller of parseLhsList - // - for communication clauses, if there is a stand-alone identifier - // followed by a colon, we have a syntax error; there is no need - // to resolve the identifier in that case - default: - // identifiers must be declared elsewhere - for _, x := range list { - p.resolve(x) - } - } - return list -} - -func (p *parser) parseRhsList() []ast.Expr { - return p.parseExprList(false) -} - -// ---------------------------------------------------------------------------- -// Types - -func (p *parser) parseType() ast.Expr { - if p.trace { - defer un(trace(p, "Type")) - } - - typ := p.tryType() - - if typ == nil { - pos := p.pos - p.errorExpected(pos, "type") - p.next() // make progress - return &ast.BadExpr{From: pos, To: p.pos} - } - - return typ -} - -// If the result is an identifier, it is not resolved. -func (p *parser) parseTypeName() ast.Expr { - if p.trace { - defer un(trace(p, "TypeName")) - } - - ident := p.parseIdent() - // don't resolve ident yet - it may be a parameter or field name - - if p.tok == token.PERIOD { - // ident is a package name - p.next() - p.resolve(ident) - sel := p.parseIdent() - return &ast.SelectorExpr{X: ident, Sel: sel} - } - - return ident -} - -func (p *parser) parseArrayType() ast.Expr { - if p.trace { - defer un(trace(p, "ArrayType")) - } - - lbrack := p.expect(token.LBRACK) - var len ast.Expr - // always permit ellipsis for more fault-tolerant parsing - if p.tok == token.ELLIPSIS { - len = &ast.Ellipsis{Ellipsis: p.pos} - p.next() - } else if p.tok != token.RBRACK { - len = p.parseRhs() - } - p.expect(token.RBRACK) - elt := p.parseType() - - return &ast.ArrayType{Lbrack: lbrack, Len: len, Elt: elt} -} - -func (p *parser) makeIdentList(list []ast.Expr) []*ast.Ident { - idents := make([]*ast.Ident, len(list)) - for i, x := range list { - ident, isIdent := x.(*ast.Ident) - if !isIdent { - if _, isBad := x.(*ast.BadExpr); !isBad { - // only report error if it's a new one - p.errorExpected(x.Pos(), "identifier") - } - ident = &ast.Ident{NamePos: x.Pos(), Name: "_"} - } - idents[i] = ident - } - return idents -} - -func (p *parser) parseFieldDecl(scope *ast.Scope) *ast.Field { - if p.trace { - defer un(trace(p, "FieldDecl")) - } - - doc := p.leadComment - - // FieldDecl - list, typ := p.parseVarList(false) - - // Tag - var tag *ast.BasicLit - if p.tok == token.STRING { - tag = &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit} - p.next() - } - - // analyze case - var idents []*ast.Ident - if typ != nil { - // IdentifierList Type - idents = p.makeIdentList(list) - } else { - // ["*"] TypeName (AnonymousField) - typ = list[0] // we always have at least one element - if n := len(list); n > 1 || !isTypeName(deref(typ)) { - pos := typ.Pos() - p.errorExpected(pos, "anonymous field") - typ = &ast.BadExpr{From: pos, To: list[n-1].End()} - } - } - - p.expectSemi() // call before accessing p.linecomment - - field := &ast.Field{Doc: doc, Names: idents, Type: typ, Tag: tag, Comment: p.lineComment} - p.declare(field, nil, scope, ast.Var, idents...) - p.resolve(typ) - - return field -} - -func (p *parser) parseStructType() *ast.StructType { - if p.trace { - defer un(trace(p, "StructType")) - } - - pos := p.expect(token.STRUCT) - lbrace := p.expect(token.LBRACE) - scope := ast.NewScope(nil) // struct scope - var list []*ast.Field - for p.tok == token.IDENT || p.tok == token.MUL || p.tok == token.LPAREN { - // a field declaration cannot start with a '(' but we accept - // it here for more robust parsing and better error messages - // (parseFieldDecl will check and complain if necessary) - list = append(list, p.parseFieldDecl(scope)) - } - rbrace := p.expect(token.RBRACE) - - return &ast.StructType{ - Struct: pos, - Fields: &ast.FieldList{ - Opening: lbrace, - List: list, - Closing: rbrace, - }, - } -} - -func (p *parser) parsePointerType() *ast.StarExpr { - if p.trace { - defer un(trace(p, "PointerType")) - } - - star := p.expect(token.MUL) - base := p.parseType() - - return &ast.StarExpr{Star: star, X: base} -} - -// If the result is an identifier, it is not resolved. -func (p *parser) tryVarType(isParam bool) ast.Expr { - if isParam && p.tok == token.ELLIPSIS { - pos := p.pos - p.next() - typ := p.tryIdentOrType() // don't use parseType so we can provide better error message - if typ != nil { - p.resolve(typ) - } else { - p.error(pos, "'...' parameter is missing type") - typ = &ast.BadExpr{From: pos, To: p.pos} - } - return &ast.Ellipsis{Ellipsis: pos, Elt: typ} - } - return p.tryIdentOrType() -} - -// If the result is an identifier, it is not resolved. -func (p *parser) parseVarType(isParam bool) ast.Expr { - typ := p.tryVarType(isParam) - if typ == nil { - pos := p.pos - p.errorExpected(pos, "type") - p.next() // make progress - typ = &ast.BadExpr{From: pos, To: p.pos} - } - return typ -} - -// If any of the results are identifiers, they are not resolved. -func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) { - if p.trace { - defer un(trace(p, "VarList")) - } - - // a list of identifiers looks like a list of type names - // - // parse/tryVarType accepts any type (including parenthesized - // ones) even though the syntax does not permit them here: we - // accept them all for more robust parsing and complain later - for typ := p.parseVarType(isParam); typ != nil; { - list = append(list, typ) - if p.tok != token.COMMA { - break - } - p.next() - typ = p.tryVarType(isParam) // maybe nil as in: func f(int,) {} - } - - // if we had a list of identifiers, it must be followed by a type - typ = p.tryVarType(isParam) - - return -} - -func (p *parser) parseParameterList(scope *ast.Scope, ellipsisOk bool) (params []*ast.Field) { - if p.trace { - defer un(trace(p, "ParameterList")) - } - - // ParameterDecl - list, typ := p.parseVarList(ellipsisOk) - - // analyze case - if typ != nil { - // IdentifierList Type - idents := p.makeIdentList(list) - field := &ast.Field{Names: idents, Type: typ} - params = append(params, field) - // Go spec: The scope of an identifier denoting a function - // parameter or result variable is the function body. - p.declare(field, nil, scope, ast.Var, idents...) - p.resolve(typ) - if p.tok == token.COMMA { - p.next() - } - for p.tok != token.RPAREN && p.tok != token.EOF { - idents := p.parseIdentList() - typ := p.parseVarType(ellipsisOk) - field := &ast.Field{Names: idents, Type: typ} - params = append(params, field) - // Go spec: The scope of an identifier denoting a function - // parameter or result variable is the function body. - p.declare(field, nil, scope, ast.Var, idents...) - p.resolve(typ) - if !p.atComma("parameter list") { - break - } - p.next() - } - } else { - // Type { "," Type } (anonymous parameters) - params = make([]*ast.Field, len(list)) - for i, typ := range list { - p.resolve(typ) - params[i] = &ast.Field{Type: typ} - } - } - - return -} - -func (p *parser) parseParameters(scope *ast.Scope, ellipsisOk bool) *ast.FieldList { - if p.trace { - defer un(trace(p, "Parameters")) - } - - var params []*ast.Field - lparen := p.expect(token.LPAREN) - if p.tok != token.RPAREN { - params = p.parseParameterList(scope, ellipsisOk) - } - rparen := p.expect(token.RPAREN) - - return &ast.FieldList{Opening: lparen, List: params, Closing: rparen} -} - -func (p *parser) parseResult(scope *ast.Scope) *ast.FieldList { - if p.trace { - defer un(trace(p, "Result")) - } - - if p.tok == token.LPAREN { - return p.parseParameters(scope, false) - } - - typ := p.tryType() - if typ != nil { - list := make([]*ast.Field, 1) - list[0] = &ast.Field{Type: typ} - return &ast.FieldList{List: list} - } - - return nil -} - -func (p *parser) parseSignature(scope *ast.Scope) (params, results *ast.FieldList) { - if p.trace { - defer un(trace(p, "Signature")) - } - - params = p.parseParameters(scope, true) - results = p.parseResult(scope) - - return -} - -func (p *parser) parseFuncType() (*ast.FuncType, *ast.Scope) { - if p.trace { - defer un(trace(p, "FuncType")) - } - - pos := p.expect(token.FUNC) - scope := ast.NewScope(p.topScope) // function scope - params, results := p.parseSignature(scope) - - return &ast.FuncType{Func: pos, Params: params, Results: results}, scope -} - -func (p *parser) parseMethodSpec(scope *ast.Scope) *ast.Field { - if p.trace { - defer un(trace(p, "MethodSpec")) - } - - doc := p.leadComment - var idents []*ast.Ident - var typ ast.Expr - x := p.parseTypeName() - if ident, isIdent := x.(*ast.Ident); isIdent && p.tok == token.LPAREN { - // method - idents = []*ast.Ident{ident} - scope := ast.NewScope(nil) // method scope - params, results := p.parseSignature(scope) - typ = &ast.FuncType{Func: token.NoPos, Params: params, Results: results} - } else { - // embedded interface - typ = x - p.resolve(typ) - } - p.expectSemi() // call before accessing p.linecomment - - spec := &ast.Field{Doc: doc, Names: idents, Type: typ, Comment: p.lineComment} - p.declare(spec, nil, scope, ast.Fun, idents...) - - return spec -} - -func (p *parser) parseInterfaceType() *ast.InterfaceType { - if p.trace { - defer un(trace(p, "InterfaceType")) - } - - pos := p.expect(token.INTERFACE) - lbrace := p.expect(token.LBRACE) - scope := ast.NewScope(nil) // interface scope - var list []*ast.Field - for p.tok == token.IDENT { - list = append(list, p.parseMethodSpec(scope)) - } - rbrace := p.expect(token.RBRACE) - - return &ast.InterfaceType{ - Interface: pos, - Methods: &ast.FieldList{ - Opening: lbrace, - List: list, - Closing: rbrace, - }, - } -} - -func (p *parser) parseMapType() *ast.MapType { - if p.trace { - defer un(trace(p, "MapType")) - } - - pos := p.expect(token.MAP) - p.expect(token.LBRACK) - key := p.parseType() - p.expect(token.RBRACK) - value := p.parseType() - - return &ast.MapType{Map: pos, Key: key, Value: value} -} - -func (p *parser) parseChanType() *ast.ChanType { - if p.trace { - defer un(trace(p, "ChanType")) - } - - pos := p.pos - dir := ast.SEND | ast.RECV - var arrow token.Pos - if p.tok == token.CHAN { - p.next() - if p.tok == token.ARROW { - arrow = p.pos - p.next() - dir = ast.SEND - } - } else { - arrow = p.expect(token.ARROW) - p.expect(token.CHAN) - dir = ast.RECV - } - value := p.parseType() - - return &ast.ChanType{Begin: pos, Arrow: arrow, Dir: dir, Value: value} -} - -// If the result is an identifier, it is not resolved. -func (p *parser) tryIdentOrType() ast.Expr { - switch p.tok { - case token.IDENT: - return p.parseTypeName() - case token.LBRACK: - return p.parseArrayType() - case token.STRUCT: - return p.parseStructType() - case token.MUL: - return p.parsePointerType() - case token.FUNC: - typ, _ := p.parseFuncType() - return typ - case token.INTERFACE: - return p.parseInterfaceType() - case token.MAP: - return p.parseMapType() - 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: lparen, X: typ, Rparen: rparen} - } - - // no type found - return nil -} - -func (p *parser) tryType() ast.Expr { - typ := p.tryIdentOrType() - if typ != nil { - p.resolve(typ) - } - return typ -} - -// ---------------------------------------------------------------------------- -// Blocks - -func (p *parser) parseStmtList() (list []ast.Stmt) { - if p.trace { - defer un(trace(p, "StatementList")) - } - - for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF { - list = append(list, p.parseStmt()) - } - - return -} - -func (p *parser) parseBody(scope *ast.Scope) *ast.BlockStmt { - if p.trace { - defer un(trace(p, "Body")) - } - - lbrace := p.expect(token.LBRACE) - p.topScope = scope // open function scope - p.openLabelScope() - list := p.parseStmtList() - p.closeLabelScope() - p.closeScope() - rbrace := p.expect(token.RBRACE) - - return &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace} -} - -func (p *parser) parseBlockStmt() *ast.BlockStmt { - if p.trace { - defer un(trace(p, "BlockStmt")) - } - - lbrace := p.expect(token.LBRACE) - p.openScope() - list := p.parseStmtList() - p.closeScope() - rbrace := p.expect(token.RBRACE) - - return &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace} -} - -// ---------------------------------------------------------------------------- -// Expressions - -func (p *parser) parseFuncTypeOrLit() ast.Expr { - if p.trace { - defer un(trace(p, "FuncTypeOrLit")) - } - - typ, scope := p.parseFuncType() - if p.tok != token.LBRACE { - // function type only - return typ - } - - p.exprLev++ - body := p.parseBody(scope) - p.exprLev-- - - return &ast.FuncLit{Type: typ, Body: body} -} - -// parseOperand may return an expression or a raw type (incl. array -// types of the form [...]T. Callers must verify the result. -// If lhs is set and the result is an identifier, it is not resolved. -// -func (p *parser) parseOperand(lhs bool) ast.Expr { - if p.trace { - defer un(trace(p, "Operand")) - } - - switch p.tok { - case token.IDENT: - x := p.parseIdent() - if !lhs { - p.resolve(x) - } - return x - - case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING: - x := &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit} - p.next() - return x - - case token.LPAREN: - lparen := p.pos - p.next() - p.exprLev++ - x := p.parseRhsOrType() // types may be parenthesized: (some type) - p.exprLev-- - rparen := p.expect(token.RPAREN) - return &ast.ParenExpr{Lparen: lparen, X: x, Rparen: rparen} - - case token.FUNC: - return p.parseFuncTypeOrLit() - } - - if typ := p.tryIdentOrType(); typ != nil { - // could be type for composite literal or conversion - _, isIdent := typ.(*ast.Ident) - assert(!isIdent, "type cannot be identifier") - return typ - } - - // we have an error - pos := p.pos - p.errorExpected(pos, "operand") - syncStmt(p) - return &ast.BadExpr{From: pos, To: p.pos} -} - -func (p *parser) parseSelector(x ast.Expr) ast.Expr { - if p.trace { - defer un(trace(p, "Selector")) - } - - sel := p.parseIdent() - - return &ast.SelectorExpr{X: x, Sel: sel} -} - -func (p *parser) parseTypeAssertion(x ast.Expr) ast.Expr { - if p.trace { - defer un(trace(p, "TypeAssertion")) - } - - 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) - - return &ast.TypeAssertExpr{X: x, Type: typ} -} - -func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr { - if p.trace { - defer un(trace(p, "IndexOrSlice")) - } - - lbrack := p.expect(token.LBRACK) - p.exprLev++ - var low, high ast.Expr - isSlice := false - if p.tok != token.COLON { - low = p.parseRhs() - } - if p.tok == token.COLON { - isSlice = true - p.next() - if p.tok != token.RBRACK { - high = p.parseRhs() - } - } - p.exprLev-- - rbrack := p.expect(token.RBRACK) - - if isSlice { - return &ast.SliceExpr{X: x, Lbrack: lbrack, Low: low, High: high, Rbrack: rbrack} - } - return &ast.IndexExpr{X: x, Lbrack: lbrack, Index: low, Rbrack: rbrack} -} - -func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr { - if p.trace { - defer un(trace(p, "CallOrConversion")) - } - - lparen := p.expect(token.LPAREN) - p.exprLev++ - var list []ast.Expr - var ellipsis token.Pos - for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() { - list = append(list, p.parseRhsOrType()) // builtins may expect a type: make(some type, ...) - if p.tok == token.ELLIPSIS { - ellipsis = p.pos - p.next() - } - if !p.atComma("argument list") { - break - } - p.next() - } - p.exprLev-- - rparen := p.expectClosing(token.RPAREN, "argument list") - - return &ast.CallExpr{Fun: fun, Lparen: lparen, Args: list, Ellipsis: ellipsis, Rparen: rparen} -} - -func (p *parser) parseElement(keyOk bool) ast.Expr { - if p.trace { - defer un(trace(p, "Element")) - } - - if p.tok == token.LBRACE { - return p.parseLiteralValue(nil) - } - - // Because the parser doesn't know the composite literal type, it cannot - // know if a key that's an identifier is a struct field name or a name - // denoting a value. The former is not resolved by the parser or the - // resolver. - // - // Instead, _try_ to resolve such a key if possible. If it resolves, - // it a) has correctly resolved, or b) incorrectly resolved because - // the key is a struct field with a name matching another identifier. - // In the former case we are done, and in the latter case we don't - // care because the type checker will do a separate field lookup. - // - // If the key does not resolve, it must a) be defined at the top- - // level in another file of the same package or be undeclared, or - // b) it is a struct field. In the former case, the type checker - // can do a top-level lookup, and in the latter case it will do a - // separate field lookup. - x := p.checkExpr(p.parseExpr(keyOk)) - if keyOk { - if p.tok == token.COLON { - colon := p.pos - p.next() - // Try to resolve the key but don't collect it - // as unresolved identifier if it fails so that - // we don't get (possibly false) errors about - // undeclared names. - p.tryResolve(x, false) - return &ast.KeyValueExpr{Key: x, Colon: colon, Value: p.parseElement(false)} - } - p.resolve(x) // not a key - } - - return x -} - -func (p *parser) parseElementList() (list []ast.Expr) { - if p.trace { - defer un(trace(p, "ElementList")) - } - - for p.tok != token.RBRACE && p.tok != token.EOF { - list = append(list, p.parseElement(true)) - if !p.atComma("composite literal") { - break - } - p.next() - } - - return -} - -func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr { - if p.trace { - defer un(trace(p, "LiteralValue")) - } - - lbrace := p.expect(token.LBRACE) - var elts []ast.Expr - p.exprLev++ - if p.tok != token.RBRACE { - elts = p.parseElementList() - } - p.exprLev-- - rbrace := p.expectClosing(token.RBRACE, "composite literal") - return &ast.CompositeLit{Type: typ, Lbrace: lbrace, Elts: elts, Rbrace: rbrace} -} - -// checkExpr checks that x is an expression (and not a type). -func (p *parser) checkExpr(x ast.Expr) ast.Expr { - switch unparen(x).(type) { - case *ast.BadExpr: - case *ast.Ident: - case *ast.BasicLit: - case *ast.FuncLit: - case *ast.CompositeLit: - case *ast.ParenExpr: - panic("unreachable") - case *ast.SelectorExpr: - case *ast.IndexExpr: - case *ast.SliceExpr: - case *ast.TypeAssertExpr: - // If t.Type == nil we have a type assertion of the form - // y.(type), which is only allowed in type switch expressions. - // It's hard to exclude those but for the case where we are in - // a type switch. Instead be lenient and test this in the type - // checker. - case *ast.CallExpr: - case *ast.StarExpr: - case *ast.UnaryExpr: - case *ast.BinaryExpr: - default: - // all other nodes are not proper expressions - p.errorExpected(x.Pos(), "expression") - x = &ast.BadExpr{From: x.Pos(), To: x.End()} - } - return x -} - -// isTypeName returns true iff x is a (qualified) TypeName. -func isTypeName(x ast.Expr) bool { - switch t := x.(type) { - case *ast.BadExpr: - case *ast.Ident: - case *ast.SelectorExpr: - _, isIdent := t.X.(*ast.Ident) - return isIdent - default: - return false // all other nodes are not type names - } - return true -} - -// isLiteralType returns true iff x is a legal composite literal type. -func isLiteralType(x ast.Expr) bool { - switch t := x.(type) { - case *ast.BadExpr: - case *ast.Ident: - case *ast.SelectorExpr: - _, isIdent := t.X.(*ast.Ident) - return isIdent - case *ast.ArrayType: - case *ast.StructType: - case *ast.MapType: - default: - return false // all other nodes are not legal composite literal types - } - return true -} - -// If x is of the form *T, deref returns T, otherwise it returns x. -func deref(x ast.Expr) ast.Expr { - if p, isPtr := x.(*ast.StarExpr); isPtr { - x = p.X - } - return x -} - -// If x is of the form (T), unparen returns unparen(T), otherwise it returns x. -func unparen(x ast.Expr) ast.Expr { - if p, isParen := x.(*ast.ParenExpr); isParen { - x = unparen(p.X) - } - return x -} - -// checkExprOrType checks that x is an expression or a type -// (and not a raw type such as [...]T). -// -func (p *parser) checkExprOrType(x ast.Expr) ast.Expr { - switch t := unparen(x).(type) { - case *ast.ParenExpr: - panic("unreachable") - case *ast.UnaryExpr: - case *ast.ArrayType: - if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis { - p.error(len.Pos(), "expected array length, found '...'") - x = &ast.BadExpr{From: x.Pos(), To: x.End()} - } - } - - // all other nodes are expressions or types - return x -} - -// If lhs is set and the result is an identifier, it is not resolved. -func (p *parser) parsePrimaryExpr(lhs bool) ast.Expr { - if p.trace { - defer un(trace(p, "PrimaryExpr")) - } - - x := p.parseOperand(lhs) -L: - for { - switch p.tok { - case token.PERIOD: - p.next() - if lhs { - p.resolve(x) - } - switch p.tok { - case token.IDENT: - x = p.parseSelector(p.checkExpr(x)) - case token.LPAREN: - x = p.parseTypeAssertion(p.checkExpr(x)) - default: - pos := p.pos - p.errorExpected(pos, "selector or type assertion") - p.next() // make progress - x = &ast.BadExpr{From: pos, To: p.pos} - } - case token.LBRACK: - if lhs { - p.resolve(x) - } - x = p.parseIndexOrSlice(p.checkExpr(x)) - case token.LPAREN: - if lhs { - p.resolve(x) - } - x = p.parseCallOrConversion(p.checkExprOrType(x)) - case token.LBRACE: - if isLiteralType(x) && (p.exprLev >= 0 || !isTypeName(x)) { - if lhs { - p.resolve(x) - } - x = p.parseLiteralValue(x) - } else { - break L - } - default: - break L - } - lhs = false // no need to try to resolve again - } - - return x -} - -// If lhs is set and the result is an identifier, it is not resolved. -func (p *parser) parseUnaryExpr(lhs bool) ast.Expr { - if p.trace { - defer un(trace(p, "UnaryExpr")) - } - - switch p.tok { - case token.ADD, token.SUB, token.NOT, token.XOR, token.AND: - pos, op := p.pos, p.tok - p.next() - x := p.parseUnaryExpr(false) - return &ast.UnaryExpr{OpPos: pos, Op: op, X: p.checkExpr(x)} - - case token.ARROW: - // channel type or receive expression - arrow := p.pos - p.next() - - // If the next token is token.CHAN we still don't know if it - // is a channel type or a receive operation - we only know - // once we have found the end of the unary expression. There - // are two cases: - // - // <- type => (<-type) must be channel type - // <- expr => <-(expr) is a receive from an expression - // - // In the first case, the arrow must be re-associated with - // the channel type parsed already: - // - // <- (chan type) => (<-chan type) - // <- (chan<- type) => (<-chan (<-type)) - - x := p.parseUnaryExpr(false) - - // determine which case we have - if typ, ok := x.(*ast.ChanType); ok { - // (<-type) - - // re-associate position info and <- - dir := ast.SEND - for ok && dir == ast.SEND { - if typ.Dir == ast.RECV { - // error: (<-type) is (<-(<-chan T)) - p.errorExpected(typ.Arrow, "'chan'") - } - arrow, typ.Begin, typ.Arrow = typ.Arrow, arrow, arrow - dir, typ.Dir = typ.Dir, ast.RECV - typ, ok = typ.Value.(*ast.ChanType) - } - if dir == ast.SEND { - p.errorExpected(arrow, "channel type") - } - - return x - } - - // <-(expr) - return &ast.UnaryExpr{OpPos: arrow, Op: token.ARROW, X: p.checkExpr(x)} - - case token.MUL: - // pointer type or unary "*" expression - pos := p.pos - p.next() - x := p.parseUnaryExpr(false) - return &ast.StarExpr{Star: pos, X: p.checkExprOrType(x)} - } - - return p.parsePrimaryExpr(lhs) -} - -// If lhs is set and the result is an identifier, it is not resolved. -func (p *parser) parseBinaryExpr(lhs bool, prec1 int) ast.Expr { - if p.trace { - defer un(trace(p, "BinaryExpr")) - } - - x := p.parseUnaryExpr(lhs) - for prec := p.tok.Precedence(); prec >= prec1; prec-- { - for p.tok.Precedence() == prec { - pos, op := p.pos, p.tok - p.next() - if lhs { - p.resolve(x) - lhs = false - } - y := p.parseBinaryExpr(false, prec+1) - x = &ast.BinaryExpr{X: p.checkExpr(x), OpPos: pos, Op: op, Y: p.checkExpr(y)} - } - } - - return x -} - -// If lhs is set and the result is an identifier, it is not resolved. -// The result may be a type or even a raw type ([...]int). Callers must -// check the result (using checkExpr or checkExprOrType), depending on -// context. -func (p *parser) parseExpr(lhs bool) ast.Expr { - if p.trace { - defer un(trace(p, "Expression")) - } - - return p.parseBinaryExpr(lhs, token.LowestPrec+1) -} - -func (p *parser) parseRhs() ast.Expr { - return p.checkExpr(p.parseExpr(false)) -} - -func (p *parser) parseRhsOrType() ast.Expr { - return p.checkExprOrType(p.parseExpr(false)) -} - -// ---------------------------------------------------------------------------- -// Statements - -// Parsing modes for parseSimpleStmt. -const ( - basic = iota - labelOk - rangeOk -) - -// parseSimpleStmt returns true as 2nd result if it parsed the assignment -// of a range clause (with mode == rangeOk). The returned statement is an -// assignment with a right-hand side that is a single unary expression of -// the form "range x". No guarantees are given for the left-hand side. -func (p *parser) parseSimpleStmt(mode int) (ast.Stmt, bool) { - if p.trace { - defer un(trace(p, "SimpleStmt")) - } - - x := p.parseLhsList() - - switch p.tok { - case - token.DEFINE, token.ASSIGN, token.ADD_ASSIGN, - token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN, - token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN, - token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN: - // assignment statement, possibly part of a range clause - pos, tok := p.pos, p.tok - p.next() - var y []ast.Expr - isRange := false - if mode == rangeOk && p.tok == token.RANGE && (tok == token.DEFINE || tok == token.ASSIGN) { - pos := p.pos - p.next() - y = []ast.Expr{&ast.UnaryExpr{OpPos: pos, Op: token.RANGE, X: p.parseRhs()}} - isRange = true - } else { - y = p.parseRhsList() - } - as := &ast.AssignStmt{Lhs: x, TokPos: pos, Tok: tok, Rhs: y} - if tok == token.DEFINE { - p.shortVarDecl(as, x) - } - return as, isRange - } - - if len(x) > 1 { - p.errorExpected(x[0].Pos(), "1 expression") - // continue with first expression - } - - switch p.tok { - case token.COLON: - // labeled statement - colon := p.pos - p.next() - if label, isIdent := x[0].(*ast.Ident); mode == labelOk && isIdent { - // Go spec: The scope of a label is the body of the function - // in which it is declared and excludes the body of any nested - // function. - stmt := &ast.LabeledStmt{Label: label, Colon: colon, Stmt: p.parseStmt()} - p.declare(stmt, nil, p.labelScope, ast.Lbl, label) - return stmt, false - } - // The label declaration typically starts at x[0].Pos(), but the label - // declaration may be erroneous due to a token after that position (and - // before the ':'). If SpuriousErrors is not set, the (only) error re- - // ported for the line is the illegal label error instead of the token - // before the ':' that caused the problem. Thus, use the (latest) colon - // position for error reporting. - p.error(colon, "illegal label declaration") - return &ast.BadStmt{From: x[0].Pos(), To: colon + 1}, false - - case token.ARROW: - // send statement - arrow := p.pos - p.next() - y := p.parseRhs() - return &ast.SendStmt{Chan: x[0], Arrow: arrow, Value: y}, false - - case token.INC, token.DEC: - // increment or decrement - s := &ast.IncDecStmt{X: x[0], TokPos: p.pos, Tok: p.tok} - p.next() - return s, false - } - - // expression - return &ast.ExprStmt{X: x[0]}, false -} - -func (p *parser) parseCallExpr() *ast.CallExpr { - x := p.parseRhsOrType() // could be a conversion: (some type)(x) - if call, isCall := x.(*ast.CallExpr); isCall { - return call - } - if _, isBad := x.(*ast.BadExpr); !isBad { - // only report error if it's a new one - p.errorExpected(x.Pos(), "function/method call") - } - return nil -} - -func (p *parser) parseGoStmt() ast.Stmt { - if p.trace { - defer un(trace(p, "GoStmt")) - } - - pos := p.expect(token.GO) - call := p.parseCallExpr() - p.expectSemi() - if call == nil { - return &ast.BadStmt{From: pos, To: pos + 2} // len("go") - } - - return &ast.GoStmt{Go: pos, Call: call} -} - -func (p *parser) parseDeferStmt() ast.Stmt { - if p.trace { - defer un(trace(p, "DeferStmt")) - } - - pos := p.expect(token.DEFER) - call := p.parseCallExpr() - p.expectSemi() - if call == nil { - return &ast.BadStmt{From: pos, To: pos + 5} // len("defer") - } - - return &ast.DeferStmt{Defer: pos, Call: call} -} - -func (p *parser) parseReturnStmt() *ast.ReturnStmt { - if p.trace { - defer un(trace(p, "ReturnStmt")) - } - - pos := p.pos - p.expect(token.RETURN) - var x []ast.Expr - if p.tok != token.SEMICOLON && p.tok != token.RBRACE { - x = p.parseRhsList() - } - p.expectSemi() - - return &ast.ReturnStmt{Return: pos, Results: x} -} - -func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt { - if p.trace { - defer un(trace(p, "BranchStmt")) - } - - pos := p.expect(tok) - var label *ast.Ident - if tok != token.FALLTHROUGH && p.tok == token.IDENT { - label = p.parseIdent() - // add to list of unresolved targets - n := len(p.targetStack) - 1 - p.targetStack[n] = append(p.targetStack[n], label) - } - p.expectSemi() - - return &ast.BranchStmt{TokPos: pos, Tok: tok, Label: label} -} - -func (p *parser) makeExpr(s ast.Stmt) ast.Expr { - if s == nil { - return nil - } - if es, isExpr := s.(*ast.ExprStmt); isExpr { - return p.checkExpr(es.X) - } - p.error(s.Pos(), "expected condition, found simple statement") - return &ast.BadExpr{From: s.Pos(), To: s.End()} -} - -func (p *parser) parseIfStmt() *ast.IfStmt { - if p.trace { - defer un(trace(p, "IfStmt")) - } - - pos := p.expect(token.IF) - p.openScope() - defer p.closeScope() - - var s ast.Stmt - var x ast.Expr - { - prevLev := p.exprLev - p.exprLev = -1 - if p.tok == token.SEMICOLON { - p.next() - x = p.parseRhs() - } else { - s, _ = p.parseSimpleStmt(basic) - if p.tok == token.SEMICOLON { - p.next() - x = p.parseRhs() - } else { - x = p.makeExpr(s) - s = nil - } - } - p.exprLev = prevLev - } - - body := p.parseBlockStmt() - var else_ ast.Stmt - if p.tok == token.ELSE { - p.next() - else_ = p.parseStmt() - } else { - p.expectSemi() - } - - return &ast.IfStmt{If: pos, Init: s, Cond: x, Body: body, Else: else_} -} - -func (p *parser) parseTypeList() (list []ast.Expr) { - if p.trace { - defer un(trace(p, "TypeList")) - } - - list = append(list, p.parseType()) - for p.tok == token.COMMA { - p.next() - list = append(list, p.parseType()) - } - - return -} - -func (p *parser) parseCaseClause(typeSwitch bool) *ast.CaseClause { - if p.trace { - defer un(trace(p, "CaseClause")) - } - - pos := p.pos - var list []ast.Expr - if p.tok == token.CASE { - p.next() - if typeSwitch { - list = p.parseTypeList() - } else { - list = p.parseRhsList() - } - } else { - p.expect(token.DEFAULT) - } - - colon := p.expect(token.COLON) - p.openScope() - body := p.parseStmtList() - p.closeScope() - - return &ast.CaseClause{Case: pos, List: list, Colon: colon, Body: body} -} - -func isTypeSwitchAssert(x ast.Expr) bool { - a, ok := x.(*ast.TypeAssertExpr) - return ok && a.Type == nil -} - -func isTypeSwitchGuard(s ast.Stmt) bool { - switch t := s.(type) { - case *ast.ExprStmt: - // x.(nil) - return isTypeSwitchAssert(t.X) - case *ast.AssignStmt: - // v := x.(nil) - return len(t.Lhs) == 1 && t.Tok == token.DEFINE && len(t.Rhs) == 1 && isTypeSwitchAssert(t.Rhs[0]) - } - return false -} - -func (p *parser) parseSwitchStmt() ast.Stmt { - if p.trace { - defer un(trace(p, "SwitchStmt")) - } - - pos := p.expect(token.SWITCH) - p.openScope() - defer p.closeScope() - - var s1, s2 ast.Stmt - if p.tok != token.LBRACE { - prevLev := p.exprLev - p.exprLev = -1 - if p.tok != token.SEMICOLON { - s2, _ = p.parseSimpleStmt(basic) - } - if p.tok == token.SEMICOLON { - p.next() - s1 = s2 - s2 = nil - if p.tok != token.LBRACE { - // A TypeSwitchGuard may declare a variable in addition - // to the variable declared in the initial SimpleStmt. - // Introduce extra scope to avoid redeclaration errors: - // - // switch t := 0; t := x.(T) { ... } - // - // (this code is not valid Go because the first t - // cannot be accessed and thus is never used, the extra - // scope is needed for the correct error message). - // - // If we don't have a type switch, s2 must be an expression. - // Having the extra nested but empty scope won't affect it. - p.openScope() - defer p.closeScope() - s2, _ = p.parseSimpleStmt(basic) - } - } - p.exprLev = prevLev - } - - typeSwitch := isTypeSwitchGuard(s2) - lbrace := p.expect(token.LBRACE) - var list []ast.Stmt - for p.tok == token.CASE || p.tok == token.DEFAULT { - list = append(list, p.parseCaseClause(typeSwitch)) - } - rbrace := p.expect(token.RBRACE) - p.expectSemi() - body := &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace} - - if typeSwitch { - return &ast.TypeSwitchStmt{Switch: pos, Init: s1, Assign: s2, Body: body} - } - - return &ast.SwitchStmt{Switch: pos, Init: s1, Tag: p.makeExpr(s2), Body: body} -} - -func (p *parser) parseCommClause() *ast.CommClause { - if p.trace { - defer un(trace(p, "CommClause")) - } - - p.openScope() - pos := p.pos - var comm ast.Stmt - if p.tok == token.CASE { - p.next() - lhs := p.parseLhsList() - if p.tok == token.ARROW { - // SendStmt - if len(lhs) > 1 { - p.errorExpected(lhs[0].Pos(), "1 expression") - // continue with first expression - } - arrow := p.pos - p.next() - rhs := p.parseRhs() - comm = &ast.SendStmt{Chan: lhs[0], Arrow: arrow, Value: rhs} - } else { - // RecvStmt - if tok := p.tok; tok == token.ASSIGN || tok == token.DEFINE { - // RecvStmt with assignment - if len(lhs) > 2 { - p.errorExpected(lhs[0].Pos(), "1 or 2 expressions") - // continue with first two expressions - lhs = lhs[0:2] - } - pos := p.pos - p.next() - rhs := p.parseRhs() - as := &ast.AssignStmt{Lhs: lhs, TokPos: pos, Tok: tok, Rhs: []ast.Expr{rhs}} - if tok == token.DEFINE { - p.shortVarDecl(as, lhs) - } - comm = as - } else { - // lhs must be single receive operation - if len(lhs) > 1 { - p.errorExpected(lhs[0].Pos(), "1 expression") - // continue with first expression - } - comm = &ast.ExprStmt{X: lhs[0]} - } - } - } else { - p.expect(token.DEFAULT) - } - - colon := p.expect(token.COLON) - body := p.parseStmtList() - p.closeScope() - - return &ast.CommClause{Case: pos, Comm: comm, Colon: colon, Body: body} -} - -func (p *parser) parseSelectStmt() *ast.SelectStmt { - if p.trace { - defer un(trace(p, "SelectStmt")) - } - - pos := p.expect(token.SELECT) - lbrace := p.expect(token.LBRACE) - var list []ast.Stmt - for p.tok == token.CASE || p.tok == token.DEFAULT { - list = append(list, p.parseCommClause()) - } - rbrace := p.expect(token.RBRACE) - p.expectSemi() - body := &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace} - - return &ast.SelectStmt{Select: pos, Body: body} -} - -func (p *parser) parseForStmt() ast.Stmt { - if p.trace { - defer un(trace(p, "ForStmt")) - } - - pos := p.expect(token.FOR) - p.openScope() - defer p.closeScope() - - var s1, s2, s3 ast.Stmt - var isRange bool - if p.tok != token.LBRACE { - prevLev := p.exprLev - p.exprLev = -1 - if p.tok != token.SEMICOLON { - s2, isRange = p.parseSimpleStmt(rangeOk) - } - if !isRange && p.tok == token.SEMICOLON { - p.next() - s1 = s2 - s2 = nil - if p.tok != token.SEMICOLON { - s2, _ = p.parseSimpleStmt(basic) - } - p.expectSemi() - if p.tok != token.LBRACE { - s3, _ = p.parseSimpleStmt(basic) - } - } - p.exprLev = prevLev - } - - body := p.parseBlockStmt() - p.expectSemi() - - if isRange { - as := s2.(*ast.AssignStmt) - // check lhs - var key, value ast.Expr - switch len(as.Lhs) { - case 2: - key, value = as.Lhs[0], as.Lhs[1] - case 1: - key = as.Lhs[0] - default: - p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions") - return &ast.BadStmt{From: pos, To: body.End()} - } - // parseSimpleStmt returned a right-hand side that - // is a single unary expression of the form "range x" - x := as.Rhs[0].(*ast.UnaryExpr).X - return &ast.RangeStmt{ - For: pos, - Key: key, - Value: value, - TokPos: as.TokPos, - Tok: as.Tok, - X: x, - Body: body, - } - } - - // regular for statement - return &ast.ForStmt{ - For: pos, - Init: s1, - Cond: p.makeExpr(s2), - Post: s3, - Body: body, - } -} - -func (p *parser) parseStmt() (s ast.Stmt) { - if p.trace { - defer un(trace(p, "Statement")) - } - - switch p.tok { - case token.CONST, token.TYPE, token.VAR: - s = &ast.DeclStmt{Decl: p.parseDecl(syncStmt)} - case - // tokens that may start an expression - token.IDENT, token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING, token.FUNC, token.LPAREN, // operands - token.LBRACK, token.STRUCT, // composite types - token.ADD, token.SUB, token.MUL, token.AND, token.XOR, token.ARROW, token.NOT: // unary operators - s, _ = p.parseSimpleStmt(labelOk) - // because of the required look-ahead, labeled statements are - // parsed by parseSimpleStmt - don't expect a semicolon after - // them - if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt { - p.expectSemi() - } - case token.GO: - s = p.parseGoStmt() - case token.DEFER: - s = p.parseDeferStmt() - case token.RETURN: - s = p.parseReturnStmt() - case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH: - s = p.parseBranchStmt(p.tok) - case token.LBRACE: - s = p.parseBlockStmt() - p.expectSemi() - case token.IF: - s = p.parseIfStmt() - case token.SWITCH: - s = p.parseSwitchStmt() - case token.SELECT: - s = p.parseSelectStmt() - case token.FOR: - s = p.parseForStmt() - case token.SEMICOLON: - s = &ast.EmptyStmt{Semicolon: p.pos} - p.next() - case token.RBRACE: - // a semicolon may be omitted before a closing "}" - s = &ast.EmptyStmt{Semicolon: p.pos} - default: - // no statement found - pos := p.pos - p.errorExpected(pos, "statement") - syncStmt(p) - s = &ast.BadStmt{From: pos, To: p.pos} - } - - return -} - -// ---------------------------------------------------------------------------- -// Declarations - -type parseSpecFunction func(p *parser, doc *ast.CommentGroup, keyword token.Token, iota int) ast.Spec - -func isValidImport(lit string) bool { - const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD" - s, _ := strconv.Unquote(lit) // go/scanner returns a legal string literal - for _, r := range s { - if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) { - return false - } - } - return s != "" -} - -func (p *parser) parseImportSpec(doc *ast.CommentGroup, _ token.Token, _ int) ast.Spec { - if p.trace { - defer un(trace(p, "ImportSpec")) - } - - var ident *ast.Ident - switch p.tok { - case token.PERIOD: - ident = &ast.Ident{NamePos: p.pos, Name: "."} - p.next() - case token.IDENT: - ident = p.parseIdent() - } - - var path *ast.BasicLit - if p.tok == token.STRING { - if !isValidImport(p.lit) { - p.error(p.pos, "invalid import path: "+p.lit) - } - path = &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit} - p.next() - } else { - p.expect(token.STRING) // use expect() error handling - } - p.expectSemi() // call before accessing p.linecomment - - // collect imports - spec := &ast.ImportSpec{ - Doc: doc, - Name: ident, - Path: path, - Comment: p.lineComment, - } - p.imports = append(p.imports, spec) - - return spec -} - -func (p *parser) parseValueSpec(doc *ast.CommentGroup, keyword token.Token, iota int) ast.Spec { - if p.trace { - defer un(trace(p, keyword.String()+"Spec")) - } - - idents := p.parseIdentList() - typ := p.tryType() - var values []ast.Expr - if p.tok == token.ASSIGN || keyword == token.CONST && (typ != nil || iota == 0) || keyword == token.VAR && typ == nil { - p.expect(token.ASSIGN) - values = p.parseRhsList() - } - p.expectSemi() // call before accessing p.linecomment - - // Go spec: The scope of a constant or variable identifier declared inside - // a function begins at the end of the ConstSpec or VarSpec and ends at - // the end of the innermost containing block. - // (Global identifiers are resolved in a separate phase after parsing.) - spec := &ast.ValueSpec{ - Doc: doc, - Names: idents, - Type: typ, - Values: values, - Comment: p.lineComment, - } - kind := ast.Con - if keyword == token.VAR { - kind = ast.Var - } - p.declare(spec, iota, p.topScope, kind, idents...) - - return spec -} - -func (p *parser) parseTypeSpec(doc *ast.CommentGroup, _ token.Token, _ int) ast.Spec { - if p.trace { - defer un(trace(p, "TypeSpec")) - } - - ident := p.parseIdent() - - // Go spec: The scope of a type identifier declared inside a function begins - // at the identifier in the TypeSpec and ends at the end of the innermost - // containing block. - // (Global identifiers are resolved in a separate phase after parsing.) - spec := &ast.TypeSpec{Doc: doc, Name: ident} - p.declare(spec, nil, p.topScope, ast.Typ, ident) - - spec.Type = p.parseType() - p.expectSemi() // call before accessing p.linecomment - spec.Comment = p.lineComment - - return spec -} - -func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl { - if p.trace { - defer un(trace(p, "GenDecl("+keyword.String()+")")) - } - - doc := p.leadComment - pos := p.expect(keyword) - var lparen, rparen token.Pos - var list []ast.Spec - if p.tok == token.LPAREN { - lparen = p.pos - p.next() - for iota := 0; p.tok != token.RPAREN && p.tok != token.EOF; iota++ { - list = append(list, f(p, p.leadComment, keyword, iota)) - } - rparen = p.expect(token.RPAREN) - p.expectSemi() - } else { - list = append(list, f(p, nil, keyword, 0)) - } - - return &ast.GenDecl{ - Doc: doc, - TokPos: pos, - Tok: keyword, - Lparen: lparen, - Specs: list, - Rparen: rparen, - } -} - -func (p *parser) parseReceiver(scope *ast.Scope) *ast.FieldList { - if p.trace { - defer un(trace(p, "Receiver")) - } - - par := p.parseParameters(scope, false) - - // must have exactly one receiver - if par.NumFields() != 1 { - p.errorExpected(par.Opening, "exactly one receiver") - par.List = []*ast.Field{{Type: &ast.BadExpr{From: par.Opening, To: par.Closing + 1}}} - return par - } - - // recv type must be of the form ["*"] identifier - recv := par.List[0] - base := deref(recv.Type) - if _, isIdent := base.(*ast.Ident); !isIdent { - if _, isBad := base.(*ast.BadExpr); !isBad { - // only report error if it's a new one - p.errorExpected(base.Pos(), "(unqualified) identifier") - } - par.List = []*ast.Field{ - {Type: &ast.BadExpr{From: recv.Pos(), To: recv.End()}}, - } - } - - return par -} - -func (p *parser) parseFuncDecl() *ast.FuncDecl { - if p.trace { - defer un(trace(p, "FunctionDecl")) - } - - doc := p.leadComment - pos := p.expect(token.FUNC) - scope := ast.NewScope(p.topScope) // function scope - - var recv *ast.FieldList - if p.tok == token.LPAREN { - recv = p.parseReceiver(scope) - } - - ident := p.parseIdent() - - params, results := p.parseSignature(scope) - - var body *ast.BlockStmt - if p.tok == token.LBRACE { - body = p.parseBody(scope) - } - p.expectSemi() - - decl := &ast.FuncDecl{ - Doc: doc, - Recv: recv, - Name: ident, - Type: &ast.FuncType{ - Func: pos, - Params: params, - Results: results, - }, - Body: body, - } - if recv == nil { - // Go spec: The scope of an identifier denoting a constant, type, - // variable, or function (but not method) declared at top level - // (outside any function) is the package block. - // - // init() functions cannot be referred to and there may - // be more than one - don't put them in the pkgScope - if ident.Name != "init" { - p.declare(decl, nil, p.pkgScope, ast.Fun, ident) - } - } - - return decl -} - -func (p *parser) parseDecl(sync func(*parser)) ast.Decl { - if p.trace { - defer un(trace(p, "Declaration")) - } - - var f parseSpecFunction - switch p.tok { - case token.CONST, token.VAR: - f = (*parser).parseValueSpec - - case token.TYPE: - f = (*parser).parseTypeSpec - - case token.FUNC: - return p.parseFuncDecl() - - default: - pos := p.pos - p.errorExpected(pos, "declaration") - sync(p) - return &ast.BadDecl{From: pos, To: p.pos} - } - - return p.parseGenDecl(p.tok, f) -} - -// ---------------------------------------------------------------------------- -// Source files - -func (p *parser) parseFile() *ast.File { - if p.trace { - defer un(trace(p, "File")) - } - - // Don't bother parsing the rest if we had errors scanning the first token. - // Likely not a Go source file at all. - if p.errors.Len() != 0 { - return nil - } - - // package clause - doc := p.leadComment - pos := p.expect(token.PACKAGE) - // Go spec: The package clause is not a declaration; - // the package name does not appear in any scope. - ident := p.parseIdent() - if ident.Name == "_" { - p.error(p.pos, "invalid package name _") - } - p.expectSemi() - - // Don't bother parsing the rest if we had errors parsing the package clause. - // Likely not a Go source file at all. - if p.errors.Len() != 0 { - return nil - } - - p.openScope() - p.pkgScope = p.topScope - var decls []ast.Decl - if p.mode&PackageClauseOnly == 0 { - // import decls - for p.tok == token.IMPORT { - decls = append(decls, p.parseGenDecl(token.IMPORT, (*parser).parseImportSpec)) - } - - if p.mode&ImportsOnly == 0 { - // rest of package body - for p.tok != token.EOF { - decls = append(decls, p.parseDecl(syncDecl)) - } - } - } - p.closeScope() - assert(p.topScope == nil, "unbalanced scopes") - assert(p.labelScope == nil, "unbalanced label scopes") - - // resolve global identifiers within the same file - i := 0 - for _, ident := range p.unresolved { - // i <= index for current ident - assert(ident.Obj == unresolved, "object already resolved") - ident.Obj = p.pkgScope.Lookup(ident.Name) // also removes unresolved sentinel - if ident.Obj == nil { - p.unresolved[i] = ident - i++ - } - } - - return &ast.File{ - Doc: doc, - Package: pos, - Name: ident, - Decls: decls, - Scope: p.pkgScope, - Imports: p.imports, - Unresolved: p.unresolved[0:i], - Comments: p.comments, - } -} diff --git a/gcc-4.8.1/libgo/go/go/parser/parser_test.go b/gcc-4.8.1/libgo/go/go/parser/parser_test.go deleted file mode 100644 index 1960377b0..000000000 --- a/gcc-4.8.1/libgo/go/go/parser/parser_test.go +++ /dev/null @@ -1,411 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package parser - -import ( - "bytes" - "fmt" - "go/ast" - "go/token" - "os" - "strings" - "testing" -) - -var fset = token.NewFileSet() - -var validFiles = []string{ - "parser.go", - "parser_test.go", - "error_test.go", - "short_test.go", -} - -func TestParse(t *testing.T) { - for _, filename := range validFiles { - _, err := ParseFile(fset, filename, nil, DeclarationErrors) - if err != nil { - t.Fatalf("ParseFile(%s): %v", filename, err) - } - } -} - -func nameFilter(filename string) bool { - switch filename { - case "parser.go": - case "interface.go": - case "parser_test.go": - default: - return false - } - return true -} - -func dirFilter(f os.FileInfo) bool { return nameFilter(f.Name()) } - -func TestParseDir(t *testing.T) { - path := "." - pkgs, err := ParseDir(fset, path, dirFilter, 0) - if err != nil { - t.Fatalf("ParseDir(%s): %v", path, err) - } - if len(pkgs) != 1 { - t.Errorf("incorrect number of packages: %d", len(pkgs)) - } - pkg := pkgs["parser"] - if pkg == nil { - t.Errorf(`package "parser" not found`) - return - } - for filename := range pkg.Files { - if !nameFilter(filename) { - t.Errorf("unexpected package file: %s", filename) - } - } -} - -func TestParseExpr(t *testing.T) { - // just kicking the tires: - // a valid expression - src := "a + b" - x, err := ParseExpr(src) - if err != nil { - t.Fatalf("ParseExpr(%s): %v", src, err) - } - // sanity check - if _, ok := x.(*ast.BinaryExpr); !ok { - t.Errorf("ParseExpr(%s): got %T, expected *ast.BinaryExpr", src, x) - } - - // an invalid expression - src = "a + *" - _, err = ParseExpr(src) - if err == nil { - t.Fatalf("ParseExpr(%s): %v", src, err) - } - - // it must not crash - for _, src := range valids { - ParseExpr(src) - } -} - -func TestColonEqualsScope(t *testing.T) { - f, err := ParseFile(fset, "", `package p; func f() { x, y, z := x, y, z }`, 0) - if err != nil { - t.Fatal(err) - } - - // RHS refers to undefined globals; LHS does not. - as := f.Decls[0].(*ast.FuncDecl).Body.List[0].(*ast.AssignStmt) - for _, v := range as.Rhs { - id := v.(*ast.Ident) - if id.Obj != nil { - t.Errorf("rhs %s has Obj, should not", id.Name) - } - } - for _, v := range as.Lhs { - id := v.(*ast.Ident) - if id.Obj == nil { - t.Errorf("lhs %s does not have Obj, should", id.Name) - } - } -} - -func TestVarScope(t *testing.T) { - f, err := ParseFile(fset, "", `package p; func f() { var x, y, z = x, y, z }`, 0) - if err != nil { - t.Fatal(err) - } - - // RHS refers to undefined globals; LHS does not. - as := f.Decls[0].(*ast.FuncDecl).Body.List[0].(*ast.DeclStmt).Decl.(*ast.GenDecl).Specs[0].(*ast.ValueSpec) - for _, v := range as.Values { - id := v.(*ast.Ident) - if id.Obj != nil { - t.Errorf("rhs %s has Obj, should not", id.Name) - } - } - for _, id := range as.Names { - if id.Obj == nil { - t.Errorf("lhs %s does not have Obj, should", id.Name) - } - } -} - -func TestObjects(t *testing.T) { - const src = ` -package p -import fmt "fmt" -const pi = 3.14 -type T struct{} -var x int -func f() { L: } -` - - f, err := ParseFile(fset, "", src, 0) - if err != nil { - t.Fatal(err) - } - - objects := map[string]ast.ObjKind{ - "p": ast.Bad, // not in a scope - "fmt": ast.Bad, // not resolved yet - "pi": ast.Con, - "T": ast.Typ, - "x": ast.Var, - "int": ast.Bad, // not resolved yet - "f": ast.Fun, - "L": ast.Lbl, - } - - ast.Inspect(f, func(n ast.Node) bool { - if ident, ok := n.(*ast.Ident); ok { - obj := ident.Obj - if obj == nil { - if objects[ident.Name] != ast.Bad { - t.Errorf("no object for %s", ident.Name) - } - return true - } - if obj.Name != ident.Name { - t.Errorf("names don't match: obj.Name = %s, ident.Name = %s", obj.Name, ident.Name) - } - kind := objects[ident.Name] - if obj.Kind != kind { - t.Errorf("%s: obj.Kind = %s; want %s", ident.Name, obj.Kind, kind) - } - } - return true - }) -} - -func TestUnresolved(t *testing.T) { - f, err := ParseFile(fset, "", ` -package p -// -func f1a(int) -func f2a(byte, int, float) -func f3a(a, b int, c float) -func f4a(...complex) -func f5a(a s1a, b ...complex) -// -func f1b(*int) -func f2b([]byte, (int), *float) -func f3b(a, b *int, c []float) -func f4b(...*complex) -func f5b(a s1a, b ...[]complex) -// -type s1a struct { int } -type s2a struct { byte; int; s1a } -type s3a struct { a, b int; c float } -// -type s1b struct { *int } -type s2b struct { byte; int; *float } -type s3b struct { a, b *s3b; c []float } -`, 0) - if err != nil { - t.Fatal(err) - } - - want := "int " + // f1a - "byte int float " + // f2a - "int float " + // f3a - "complex " + // f4a - "complex " + // f5a - // - "int " + // f1b - "byte int float " + // f2b - "int float " + // f3b - "complex " + // f4b - "complex " + // f5b - // - "int " + // s1a - "byte int " + // s2a - "int float " + // s3a - // - "int " + // s1a - "byte int float " + // s2a - "float " // s3a - - // collect unresolved identifiers - var buf bytes.Buffer - for _, u := range f.Unresolved { - buf.WriteString(u.Name) - buf.WriteByte(' ') - } - got := buf.String() - - if got != want { - t.Errorf("\ngot: %s\nwant: %s", got, want) - } -} - -var imports = map[string]bool{ - `"a"`: true, - "`a`": true, - `"a/b"`: true, - `"a.b"`: true, - `"m\x61th"`: true, - `"greek/αβ"`: true, - `""`: false, - - // Each of these pairs tests both `` vs "" strings - // and also use of invalid characters spelled out as - // escape sequences and written directly. - // For example `"\x00"` tests import "\x00" - // while "`\x00`" tests import `<actual-NUL-byte>`. - `"\x00"`: false, - "`\x00`": false, - `"\x7f"`: false, - "`\x7f`": false, - `"a!"`: false, - "`a!`": false, - `"a b"`: false, - "`a b`": false, - `"a\\b"`: false, - "`a\\b`": false, - "\"`a`\"": false, - "`\"a\"`": false, - `"\x80\x80"`: false, - "`\x80\x80`": false, - `"\xFFFD"`: false, - "`\xFFFD`": false, -} - -func TestImports(t *testing.T) { - for path, isValid := range imports { - src := fmt.Sprintf("package p; import %s", path) - _, err := ParseFile(fset, "", src, 0) - switch { - case err != nil && isValid: - t.Errorf("ParseFile(%s): got %v; expected no error", src, err) - case err == nil && !isValid: - t.Errorf("ParseFile(%s): got no error; expected one", src) - } - } -} - -func TestCommentGroups(t *testing.T) { - f, err := ParseFile(fset, "", ` -package p /* 1a */ /* 1b */ /* 1c */ // 1d -/* 2a -*/ -// 2b -const pi = 3.1415 -/* 3a */ // 3b -/* 3c */ const e = 2.7182 - -// Example from issue 3139 -func ExampleCount() { - fmt.Println(strings.Count("cheese", "e")) - fmt.Println(strings.Count("five", "")) // before & after each rune - // Output: - // 3 - // 5 -} -`, ParseComments) - if err != nil { - t.Fatal(err) - } - expected := [][]string{ - {"/* 1a */", "/* 1b */", "/* 1c */", "// 1d"}, - {"/* 2a\n*/", "// 2b"}, - {"/* 3a */", "// 3b", "/* 3c */"}, - {"// Example from issue 3139"}, - {"// before & after each rune"}, - {"// Output:", "// 3", "// 5"}, - } - if len(f.Comments) != len(expected) { - t.Fatalf("got %d comment groups; expected %d", len(f.Comments), len(expected)) - } - for i, exp := range expected { - got := f.Comments[i].List - if len(got) != len(exp) { - t.Errorf("got %d comments in group %d; expected %d", len(got), i, len(exp)) - continue - } - for j, exp := range exp { - got := got[j].Text - if got != exp { - t.Errorf("got %q in group %d; expected %q", got, i, exp) - } - } - } -} - -func getField(file *ast.File, fieldname string) *ast.Field { - parts := strings.Split(fieldname, ".") - for _, d := range file.Decls { - if d, ok := d.(*ast.GenDecl); ok && d.Tok == token.TYPE { - for _, s := range d.Specs { - if s, ok := s.(*ast.TypeSpec); ok && s.Name.Name == parts[0] { - if s, ok := s.Type.(*ast.StructType); ok { - for _, f := range s.Fields.List { - for _, name := range f.Names { - if name.Name == parts[1] { - return f - } - } - } - } - } - } - } - } - return nil -} - -// Don't use ast.CommentGroup.Text() - we want to see exact comment text. -func commentText(c *ast.CommentGroup) string { - var buf bytes.Buffer - if c != nil { - for _, c := range c.List { - buf.WriteString(c.Text) - } - } - return buf.String() -} - -func checkFieldComments(t *testing.T, file *ast.File, fieldname, lead, line string) { - f := getField(file, fieldname) - if f == nil { - t.Fatalf("field not found: %s", fieldname) - } - if got := commentText(f.Doc); got != lead { - t.Errorf("got lead comment %q; expected %q", got, lead) - } - if got := commentText(f.Comment); got != line { - t.Errorf("got line comment %q; expected %q", got, line) - } -} - -func TestLeadAndLineComments(t *testing.T) { - f, err := ParseFile(fset, "", ` -package p -type T struct { - /* F1 lead comment */ - // - F1 int /* F1 */ // line comment - // F2 lead - // comment - F2 int // F2 line comment - // f3 lead comment - f3 int // f3 line comment -} -`, ParseComments) - if err != nil { - t.Fatal(err) - } - checkFieldComments(t, f, "T.F1", "/* F1 lead comment *///", "/* F1 */// line comment") - checkFieldComments(t, f, "T.F2", "// F2 lead// comment", "// F2 line comment") - checkFieldComments(t, f, "T.f3", "// f3 lead comment", "// f3 line comment") - ast.FileExports(f) - checkFieldComments(t, f, "T.F1", "/* F1 lead comment *///", "/* F1 */// line comment") - checkFieldComments(t, f, "T.F2", "// F2 lead// comment", "// F2 line comment") - if getField(f, "T.f3") != nil { - t.Error("not expected to find T.f3") - } -} diff --git a/gcc-4.8.1/libgo/go/go/parser/performance_test.go b/gcc-4.8.1/libgo/go/go/parser/performance_test.go deleted file mode 100644 index f2732c0e2..000000000 --- a/gcc-4.8.1/libgo/go/go/parser/performance_test.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package parser - -import ( - "go/token" - "io/ioutil" - "testing" -) - -var src = readFile("parser.go") - -func readFile(filename string) []byte { - data, err := ioutil.ReadFile(filename) - if err != nil { - panic(err) - } - return data -} - -func BenchmarkParse(b *testing.B) { - b.SetBytes(int64(len(src))) - for i := 0; i < b.N; i++ { - if _, err := ParseFile(token.NewFileSet(), "", src, ParseComments); err != nil { - b.Fatalf("benchmark failed due to parse error: %s", err) - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/parser/short_test.go b/gcc-4.8.1/libgo/go/go/parser/short_test.go deleted file mode 100644 index c62f7e050..000000000 --- a/gcc-4.8.1/libgo/go/go/parser/short_test.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains test cases for short valid and invalid programs. - -package parser - -import "testing" - -var valids = []string{ - "package p\n", - `package p;`, - `package p; import "fmt"; func f() { fmt.Println("Hello, World!") };`, - `package p; func f() { if f(T{}) {} };`, - `package p; func f() { _ = <-chan int(nil) };`, - `package p; func f() { _ = (<-chan int)(nil) };`, - `package p; func f() { _ = (<-chan <-chan int)(nil) };`, - `package p; func f() { _ = <-chan <-chan <-chan <-chan <-int(nil) };`, - `package p; func f(func() func() func());`, - `package p; func f(...T);`, - `package p; func f(float, ...int);`, - `package p; func f(x int, a ...int) { f(0, a...); f(1, a...,) };`, - `package p; func f(int,) {};`, - `package p; func f(...int,) {};`, - `package p; func f(x ...int,) {};`, - `package p; type T []int; var a []bool; func f() { if a[T{42}[0]] {} };`, - `package p; type T []int; func g(int) bool { return true }; func f() { if g(T{42}[0]) {} };`, - `package p; type T []int; func f() { for _ = range []int{T{42}[0]} {} };`, - `package p; var a = T{{1, 2}, {3, 4}}`, - `package p; func f() { select { case <- c: case c <- d: case c <- <- d: case <-c <- d: } };`, - `package p; func f() { select { case x := (<-c): } };`, - `package p; func f() { if ; true {} };`, - `package p; func f() { switch ; {} };`, - `package p; func f() { for _ = range "foo" + "bar" {} };`, -} - -func TestValid(t *testing.T) { - for _, src := range valids { - checkErrors(t, src, src) - } -} - -var invalids = []string{ - `foo /* ERROR "expected 'package'" */ !`, - `package p; func f() { if { /* ERROR "expected operand" */ } };`, - `package p; func f() { if ; { /* ERROR "expected operand" */ } };`, - `package p; func f() { if f(); { /* ERROR "expected operand" */ } };`, - `package p; const c; /* ERROR "expected '='" */`, - `package p; func f() { if _ /* ERROR "expected condition" */ = range x; true {} };`, - `package p; func f() { switch _ /* ERROR "expected condition" */ = range x; true {} };`, - `package p; func f() { for _ = range x ; /* ERROR "expected '{'" */ ; {} };`, - `package p; func f() { for ; ; _ = range /* ERROR "expected operand" */ x {} };`, - `package p; func f() { for ; _ /* ERROR "expected condition" */ = range x ; {} };`, - `package p; func f() { switch t /* ERROR "expected condition" */ = t.(type) {} };`, - `package p; func f() { switch t /* ERROR "expected condition" */ , t = t.(type) {} };`, - `package p; func f() { switch t /* ERROR "expected condition" */ = t.(type), t {} };`, - `package p; var a = [ /* ERROR "expected expression" */ 1]int;`, - `package p; var a = [ /* ERROR "expected expression" */ ...]int;`, - `package p; var a = struct /* ERROR "expected expression" */ {}`, - `package p; var a = func /* ERROR "expected expression" */ ();`, - `package p; var a = interface /* ERROR "expected expression" */ {}`, - `package p; var a = [ /* ERROR "expected expression" */ ]int`, - `package p; var a = map /* ERROR "expected expression" */ [int]int`, - `package p; var a = chan /* ERROR "expected expression" */ int;`, - `package p; var a = []int{[ /* ERROR "expected expression" */ ]int};`, - `package p; var a = ( /* ERROR "expected expression" */ []int);`, - `package p; var a = a[[ /* ERROR "expected expression" */ ]int:[]int];`, - `package p; var a = <- /* ERROR "expected expression" */ chan int;`, - `package p; func f() { select { case _ <- chan /* ERROR "expected expression" */ int: } };`, - `package p; func f() { _ = (<-<- /* ERROR "expected 'chan'" */ chan int)(nil) };`, - `package p; func f() { _ = (<-chan<-chan<-chan<-chan<-chan<- /* ERROR "expected channel type" */ int)(nil) };`, - `package p; func f() { var t []int; t /* ERROR "expected identifier on left side of :=" */ [0] := 0 };`, -} - -func TestInvalid(t *testing.T) { - for _, src := range invalids { - checkErrors(t, src, src) - } -} diff --git a/gcc-4.8.1/libgo/go/go/parser/testdata/commas.src b/gcc-4.8.1/libgo/go/go/parser/testdata/commas.src deleted file mode 100644 index af6e70645..000000000 --- a/gcc-4.8.1/libgo/go/go/parser/testdata/commas.src +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Test case for error messages/parser synchronization -// after missing commas. - -package p - -var _ = []int{ - 0 /* ERROR "missing ','" */ -} - -var _ = []int{ - 0, - 1, - 2, - 3 /* ERROR "missing ','" */ -} diff --git a/gcc-4.8.1/libgo/go/go/parser/testdata/issue3106.src b/gcc-4.8.1/libgo/go/go/parser/testdata/issue3106.src deleted file mode 100644 index 82796c8ce..000000000 --- a/gcc-4.8.1/libgo/go/go/parser/testdata/issue3106.src +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Test case for issue 3106: Better synchronization of -// parser after certain syntax errors. - -package main - -func f() { - var m Mutex - c := MakeCond(&m) - percent := 0 - const step = 10 - for i := 0; i < 5; i++ { - go func() { - for { - // Emulates some useful work. - time.Sleep(1e8) - m.Lock() - defer - if /* ERROR "expected operand, found 'if'" */ percent == 100 { - m.Unlock() - break - } - percent++ - if percent % step == 0 { - //c.Signal() - } - m.Unlock() - } - }() - } - for { - m.Lock() - if percent == 0 || percent % step != 0 { - c.Wait() - } - fmt.Print(",") - if percent == 100 { - m.Unlock() - break - } - m.Unlock() - } -} diff --git a/gcc-4.8.1/libgo/go/go/printer/nodes.go b/gcc-4.8.1/libgo/go/go/printer/nodes.go deleted file mode 100644 index ee0bbf1ed..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/nodes.go +++ /dev/null @@ -1,1575 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements printing of AST nodes; specifically -// expressions, statements, declarations, and files. It uses -// the print functionality implemented in printer.go. - -package printer - -import ( - "bytes" - "go/ast" - "go/token" - "unicode/utf8" -) - -// Formatting issues: -// - better comment formatting for /*-style comments at the end of a line (e.g. a declaration) -// when the comment spans multiple lines; if such a comment is just two lines, formatting is -// not idempotent -// - formatting of expression lists -// - should use blank instead of tab to separate one-line function bodies from -// the function header unless there is a group of consecutive one-liners - -// ---------------------------------------------------------------------------- -// Common AST nodes. - -// Print as many newlines as necessary (but at least min newlines) to get to -// the current line. ws is printed before the first line break. If newSection -// is set, the first line break is printed as formfeed. Returns true if any -// line break was printed; returns false otherwise. -// -// TODO(gri): linebreak may add too many lines if the next statement at "line" -// is preceded by comments because the computation of n assumes -// the current position before the comment and the target position -// after the comment. Thus, after interspersing such comments, the -// space taken up by them is not considered to reduce the number of -// linebreaks. At the moment there is no easy way to know about -// future (not yet interspersed) comments in this function. -// -func (p *printer) linebreak(line, min int, ws whiteSpace, newSection bool) (printedBreak bool) { - n := nlimit(line - p.pos.Line) - if n < min { - n = min - } - if n > 0 { - p.print(ws) - if newSection { - p.print(formfeed) - n-- - } - for ; n > 0; n-- { - p.print(newline) - } - printedBreak = true - } - return -} - -// setComment sets g as the next comment if g != nil and if node comments -// are enabled - this mode is used when printing source code fragments such -// as exports only. It assumes that there is no pending comment in p.comments -// and at most one pending comment in the p.comment cache. -func (p *printer) setComment(g *ast.CommentGroup) { - if g == nil || !p.useNodeComments { - return - } - if p.comments == nil { - // initialize p.comments lazily - p.comments = make([]*ast.CommentGroup, 1) - } else if p.cindex < len(p.comments) { - // for some reason there are pending comments; this - // should never happen - handle gracefully and flush - // all comments up to g, ignore anything after that - p.flush(p.posFor(g.List[0].Pos()), token.ILLEGAL) - p.comments = p.comments[0:1] - // in debug mode, report error - p.internalError("setComment found pending comments") - } - p.comments[0] = g - p.cindex = 0 - // don't overwrite any pending comment in the p.comment cache - // (there may be a pending comment when a line comment is - // immediately followed by a lead comment with no other - // tokens between) - if p.commentOffset == infinity { - p.nextComment() // get comment ready for use - } -} - -type exprListMode uint - -const ( - commaTerm exprListMode = 1 << iota // list is optionally terminated by a comma - noIndent // no extra indentation in multi-line lists -) - -// If indent is set, a multi-line identifier list is indented after the -// first linebreak encountered. -func (p *printer) identList(list []*ast.Ident, indent bool) { - // convert into an expression list so we can re-use exprList formatting - xlist := make([]ast.Expr, len(list)) - for i, x := range list { - xlist[i] = x - } - var mode exprListMode - if !indent { - mode = noIndent - } - p.exprList(token.NoPos, xlist, 1, mode, token.NoPos) -} - -// Print a list of expressions. If the list spans multiple -// source lines, the original line breaks are respected between -// expressions. -// -// TODO(gri) Consider rewriting this to be independent of []ast.Expr -// so that we can use the algorithm for any kind of list -// (e.g., pass list via a channel over which to range). -func (p *printer) exprList(prev0 token.Pos, list []ast.Expr, depth int, mode exprListMode, next0 token.Pos) { - if len(list) == 0 { - return - } - - prev := p.posFor(prev0) - next := p.posFor(next0) - line := p.lineFor(list[0].Pos()) - endLine := p.lineFor(list[len(list)-1].End()) - - if prev.IsValid() && prev.Line == line && line == endLine { - // all list entries on a single line - for i, x := range list { - if i > 0 { - // use position of expression following the comma as - // comma position for correct comment placement - p.print(x.Pos(), token.COMMA, blank) - } - p.expr0(x, depth) - } - return - } - - // list entries span multiple lines; - // use source code positions to guide line breaks - - // don't add extra indentation if noIndent is set; - // i.e., pretend that the first line is already indented - ws := ignore - if mode&noIndent == 0 { - ws = indent - } - - // the first linebreak is always a formfeed since this section must not - // depend on any previous formatting - prevBreak := -1 // index of last expression that was followed by a linebreak - if prev.IsValid() && prev.Line < line && p.linebreak(line, 0, ws, true) { - ws = ignore - prevBreak = 0 - } - - // initialize expression/key size: a zero value indicates expr/key doesn't fit on a single line - size := 0 - - // print all list elements - for i, x := range list { - prevLine := line - line = p.lineFor(x.Pos()) - - // determine if the next linebreak, if any, needs to use formfeed: - // in general, use the entire node size to make the decision; for - // key:value expressions, use the key size - // TODO(gri) for a better result, should probably incorporate both - // the key and the node size into the decision process - useFF := true - - // determine element size: all bets are off if we don't have - // position information for the previous and next token (likely - // generated code - simply ignore the size in this case by setting - // it to 0) - prevSize := size - const infinity = 1e6 // larger than any source line - size = p.nodeSize(x, infinity) - pair, isPair := x.(*ast.KeyValueExpr) - if size <= infinity && prev.IsValid() && next.IsValid() { - // x fits on a single line - if isPair { - size = p.nodeSize(pair.Key, infinity) // size <= infinity - } - } else { - // size too large or we don't have good layout information - size = 0 - } - - // if the previous line and the current line had single- - // line-expressions and the key sizes are small or the - // the ratio between the key sizes does not exceed a - // threshold, align columns and do not use formfeed - if prevSize > 0 && size > 0 { - const smallSize = 20 - if prevSize <= smallSize && size <= smallSize { - useFF = false - } else { - const r = 4 // threshold - ratio := float64(size) / float64(prevSize) - useFF = ratio <= 1.0/r || r <= ratio - } - } - - if i > 0 { - needsLinebreak := prevLine < line && prevLine > 0 && line > 0 - // use position of expression following the comma as - // comma position for correct comment placement, but - // only if the expression is on the same line - if !needsLinebreak { - p.print(x.Pos()) - } - p.print(token.COMMA) - needsBlank := true - if needsLinebreak { - // lines are broken using newlines so comments remain aligned - // unless forceFF is set or there are multiple expressions on - // the same line in which case formfeed is used - if p.linebreak(line, 0, ws, useFF || prevBreak+1 < i) { - ws = ignore - prevBreak = i - needsBlank = false // we got a line break instead - } - } - if needsBlank { - p.print(blank) - } - } - - if isPair && size > 0 && len(list) > 1 { - // we have a key:value expression that fits onto one line and - // is in a list with more then one entry: use a column for the - // key such that consecutive entries can align if possible - p.expr(pair.Key) - p.print(pair.Colon, token.COLON, vtab) - p.expr(pair.Value) - } else { - p.expr0(x, depth) - } - } - - if mode&commaTerm != 0 && next.IsValid() && p.pos.Line < next.Line { - // print a terminating comma if the next token is on a new line - 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 - } - - if ws == ignore && mode&noIndent == 0 { - // unindent if we indented - p.print(unindent) - } -} - -func (p *printer) parameters(fields *ast.FieldList) { - p.print(fields.Opening, token.LPAREN) - if len(fields.List) > 0 { - prevLine := p.lineFor(fields.Opening) - ws := indent - for i, par := range fields.List { - // determine par begin and end line (may be different - // if there are multiple parameter names for this par - // or the type is on a separate line) - var parLineBeg int - var parLineEnd = p.lineFor(par.Type.Pos()) - if len(par.Names) > 0 { - parLineBeg = p.lineFor(par.Names[0].Pos()) - } else { - parLineBeg = parLineEnd - } - // separating "," if needed - needsLinebreak := 0 < prevLine && prevLine < parLineBeg - if i > 0 { - // use position of parameter following the comma as - // comma position for correct comma placement, but - // only if the next parameter is on the same line - if !needsLinebreak { - p.print(par.Pos()) - } - p.print(token.COMMA) - } - // separator if needed (linebreak or blank) - if needsLinebreak && p.linebreak(parLineBeg, 0, ws, true) { - // break line if the opening "(" or previous parameter ended on a different line - ws = ignore - } else if i > 0 { - p.print(blank) - } - // parameter names - if len(par.Names) > 0 { - // Very subtle: If we indented before (ws == ignore), identList - // won't indent again. If we didn't (ws == indent), identList will - // indent if the identList spans multiple lines, and it will outdent - // again at the end (and still ws == indent). Thus, a subsequent indent - // by a linebreak call after a type, or in the next multi-line identList - // will do the right thing. - p.identList(par.Names, ws == indent) - p.print(blank) - } - // parameter type - p.expr(stripParensAlways(par.Type)) - prevLine = parLineEnd - } - // if the closing ")" is on a separate line from the last parameter, - // print an additional "," and line break - if closing := p.lineFor(fields.Closing); 0 < prevLine && prevLine < closing { - p.print(token.COMMA) - p.linebreak(closing, 0, ignore, true) - } - // unindent if we indented - if ws == ignore { - p.print(unindent) - } - } - p.print(fields.Closing, token.RPAREN) -} - -func (p *printer) signature(params, result *ast.FieldList) { - if params != nil { - p.parameters(params) - } else { - p.print(token.LPAREN, token.RPAREN) - } - n := result.NumFields() - if n > 0 { - // result != nil - p.print(blank) - if n == 1 && result.List[0].Names == nil { - // single anonymous result; no ()'s - p.expr(stripParensAlways(result.List[0].Type)) - return - } - p.parameters(result) - } -} - -func identListSize(list []*ast.Ident, maxSize int) (size int) { - for i, x := range list { - if i > 0 { - size += len(", ") - } - size += utf8.RuneCountInString(x.Name) - if size >= maxSize { - break - } - } - return -} - -func (p *printer) isOneLineFieldList(list []*ast.Field) bool { - if len(list) != 1 { - return false // allow only one field - } - f := list[0] - if f.Tag != nil || f.Comment != nil { - 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) - if namesSize > 0 { - namesSize = 1 // blank between names and types - } - typeSize := p.nodeSize(f.Type, maxSize) - return namesSize+typeSize <= maxSize -} - -func (p *printer) setLineComment(text string) { - p.setComment(&ast.CommentGroup{List: []*ast.Comment{{Slash: token.NoPos, Text: text}}}) -} - -func (p *printer) isMultiLine(n ast.Node) bool { - return p.lineFor(n.End())-p.lineFor(n.Pos()) > 0 -} - -func (p *printer) fieldList(fields *ast.FieldList, isStruct, isIncomplete bool) { - lbrace := fields.Opening - list := fields.List - rbrace := fields.Closing - hasComments := isIncomplete || p.commentBefore(p.posFor(rbrace)) - srcIsOneLine := lbrace.IsValid() && rbrace.IsValid() && p.lineFor(lbrace) == p.lineFor(rbrace) - - if !hasComments && srcIsOneLine { - // 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 - } else if isStruct && 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] - for i, x := range f.Names { - if i > 0 { - // no comments so no need for comma position - p.print(token.COMMA, blank) - } - p.expr(x) - } - if len(f.Names) > 0 { - p.print(blank) - } - p.expr(f.Type) - p.print(blank, rbrace, token.RBRACE) - return - } - } - // hasComments || !srcIsOneLine - - p.print(blank, lbrace, token.LBRACE, indent) - if hasComments || len(list) > 0 { - p.print(formfeed) - } - - if isStruct { - - sep := vtab - if len(list) == 1 { - sep = blank - } - newSection := false - for i, f := range list { - if i > 0 { - p.linebreak(p.lineFor(f.Pos()), 1, ignore, newSection) - } - extraTabs := 0 - p.setComment(f.Doc) - if len(f.Names) > 0 { - // named fields - p.identList(f.Names, false) - p.print(sep) - p.expr(f.Type) - extraTabs = 1 - } else { - // anonymous field - p.expr(f.Type) - extraTabs = 2 - } - if f.Tag != nil { - if len(f.Names) > 0 && sep == vtab { - p.print(sep) - } - p.print(sep) - p.expr(f.Tag) - extraTabs = 0 - } - if f.Comment != nil { - for ; extraTabs > 0; extraTabs-- { - p.print(sep) - } - p.setComment(f.Comment) - } - newSection = p.isMultiLine(f) - } - if isIncomplete { - if len(list) > 0 { - p.print(formfeed) - } - p.flush(p.posFor(rbrace), token.RBRACE) // make sure we don't lose the last line comment - p.setLineComment("// contains filtered or unexported fields") - } - - } else { // interface - - newSection := false - for i, f := range list { - if i > 0 { - p.linebreak(p.lineFor(f.Pos()), 1, ignore, newSection) - } - p.setComment(f.Doc) - if ftyp, isFtyp := f.Type.(*ast.FuncType); isFtyp { - // method - p.expr(f.Names[0]) - p.signature(ftyp.Params, ftyp.Results) - } else { - // embedded interface - p.expr(f.Type) - } - p.setComment(f.Comment) - newSection = p.isMultiLine(f) - } - if isIncomplete { - if len(list) > 0 { - p.print(formfeed) - } - p.flush(p.posFor(rbrace), token.RBRACE) // make sure we don't lose the last line comment - p.setLineComment("// contains filtered or unexported methods") - } - - } - p.print(unindent, formfeed, rbrace, token.RBRACE) -} - -// ---------------------------------------------------------------------------- -// Expressions - -func walkBinary(e *ast.BinaryExpr) (has4, has5 bool, maxProblem int) { - switch e.Op.Precedence() { - case 4: - has4 = true - case 5: - has5 = true - } - - switch l := e.X.(type) { - case *ast.BinaryExpr: - if l.Op.Precedence() < e.Op.Precedence() { - // parens will be inserted. - // pretend this is an *ast.ParenExpr and do nothing. - break - } - h4, h5, mp := walkBinary(l) - has4 = has4 || h4 - has5 = has5 || h5 - if maxProblem < mp { - maxProblem = mp - } - } - - switch r := e.Y.(type) { - case *ast.BinaryExpr: - if r.Op.Precedence() <= e.Op.Precedence() { - // parens will be inserted. - // pretend this is an *ast.ParenExpr and do nothing. - break - } - h4, h5, mp := walkBinary(r) - has4 = has4 || h4 - has5 = has5 || h5 - if maxProblem < mp { - maxProblem = mp - } - - case *ast.StarExpr: - if e.Op == token.QUO { // `*/` - maxProblem = 5 - } - - case *ast.UnaryExpr: - switch e.Op.String() + r.Op.String() { - case "/*", "&&", "&^": - maxProblem = 5 - case "++", "--": - if maxProblem < 4 { - maxProblem = 4 - } - } - } - return -} - -func cutoff(e *ast.BinaryExpr, depth int) int { - has4, has5, maxProblem := walkBinary(e) - if maxProblem > 0 { - return maxProblem + 1 - } - if has4 && has5 { - if depth == 1 { - return 5 - } - return 4 - } - if depth == 1 { - return 6 - } - return 4 -} - -func diffPrec(expr ast.Expr, prec int) int { - x, ok := expr.(*ast.BinaryExpr) - if !ok || prec != x.Op.Precedence() { - return 1 - } - return 0 -} - -func reduceDepth(depth int) int { - depth-- - if depth < 1 { - depth = 1 - } - return depth -} - -// Format the binary expression: decide the cutoff and then format. -// Let's call depth == 1 Normal mode, and depth > 1 Compact mode. -// (Algorithm suggestion by Russ Cox.) -// -// The precedences are: -// 5 * / % << >> & &^ -// 4 + - | ^ -// 3 == != < <= > >= -// 2 && -// 1 || -// -// The only decision is whether there will be spaces around levels 4 and 5. -// There are never spaces at level 6 (unary), and always spaces at levels 3 and below. -// -// To choose the cutoff, look at the whole expression but excluding primary -// expressions (function calls, parenthesized exprs), and apply these rules: -// -// 1) If there is a binary operator with a right side unary operand -// that would clash without a space, the cutoff must be (in order): -// -// /* 6 -// && 6 -// &^ 6 -// ++ 5 -// -- 5 -// -// (Comparison operators always have spaces around them.) -// -// 2) If there is a mix of level 5 and level 4 operators, then the cutoff -// is 5 (use spaces to distinguish precedence) in Normal mode -// and 4 (never use spaces) in Compact mode. -// -// 3) If there are no level 4 operators or no level 5 operators, then the -// cutoff is 6 (always use spaces) in Normal mode -// and 4 (never use spaces) in Compact mode. -// -func (p *printer) binaryExpr(x *ast.BinaryExpr, prec1, cutoff, depth int) { - 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, reduceDepth(depth)) // parentheses undo one level of depth - p.print(token.RPAREN) - return - } - - printBlank := prec < cutoff - - ws := indent - p.expr1(x.X, prec, depth+diffPrec(x.X, prec)) - if printBlank { - p.print(blank) - } - xline := p.pos.Line // before the operator (it may be on the next line!) - yline := p.lineFor(x.Y.Pos()) - p.print(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, ws, true) { - ws = ignore - printBlank = false // no blank after line break - } - } - if printBlank { - p.print(blank) - } - p.expr1(x.Y, prec+1, depth+1) - if ws == ignore { - p.print(unindent) - } -} - -func isBinary(expr ast.Expr) bool { - _, ok := expr.(*ast.BinaryExpr) - return ok -} - -func (p *printer) expr1(expr ast.Expr, prec1, depth int) { - p.print(expr.Pos()) - - switch x := expr.(type) { - case *ast.BadExpr: - p.print("BadExpr") - - case *ast.Ident: - p.print(x) - - case *ast.BinaryExpr: - if depth < 1 { - p.internalError("depth < 1:", depth) - depth = 1 - } - p.binaryExpr(x, prec1, cutoff(x, depth), depth) - - case *ast.KeyValueExpr: - p.expr(x.Key) - p.print(x.Colon, token.COLON, blank) - p.expr(x.Value) - - case *ast.StarExpr: - const prec = token.UnaryPrec - if prec < prec1 { - // parenthesis needed - p.print(token.LPAREN) - p.print(token.MUL) - p.expr(x.X) - p.print(token.RPAREN) - } else { - // no parenthesis needed - p.print(token.MUL) - p.expr(x.X) - } - - case *ast.UnaryExpr: - const prec = token.UnaryPrec - if prec < prec1 { - // parenthesis needed - p.print(token.LPAREN) - p.expr(x) - p.print(token.RPAREN) - } else { - // no parenthesis needed - p.print(x.Op) - if x.Op == token.RANGE { - // TODO(gri) Remove this code if it cannot be reached. - p.print(blank) - } - p.expr1(x.X, prec, depth) - } - - case *ast.BasicLit: - p.print(x) - - case *ast.FuncLit: - p.expr(x.Type) - p.adjBlock(p.distanceFrom(x.Type.Pos()), blank, x.Body) - - case *ast.ParenExpr: - if _, hasParens := x.X.(*ast.ParenExpr); hasParens { - // don't print parentheses around an already parenthesized expression - // TODO(gri) consider making this more general and incorporate precedence levels - p.expr0(x.X, reduceDepth(depth)) // parentheses undo one level of depth - } else { - p.print(token.LPAREN) - p.expr0(x.X, reduceDepth(depth)) // parentheses undo one level of depth - p.print(x.Rparen, token.RPAREN) - } - - case *ast.SelectorExpr: - p.expr1(x.X, token.HighestPrec, depth) - p.print(token.PERIOD) - if line := p.lineFor(x.Sel.Pos()); p.pos.IsValid() && p.pos.Line < line { - p.print(indent, newline, x.Sel.Pos(), x.Sel, unindent) - } else { - p.print(x.Sel.Pos(), x.Sel) - } - - case *ast.TypeAssertExpr: - p.expr1(x.X, token.HighestPrec, depth) - p.print(token.PERIOD, token.LPAREN) - if x.Type != nil { - p.expr(x.Type) - } else { - p.print(token.TYPE) - } - 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) - p.print(x.Lbrack, token.LBRACK) - p.expr0(x.Index, depth+1) - p.print(x.Rbrack, token.RBRACK) - - case *ast.SliceExpr: - // TODO(gri): should treat[] like parentheses and undo one level of depth - p.expr1(x.X, token.HighestPrec, 1) - p.print(x.Lbrack, token.LBRACK) - if x.Low != nil { - p.expr0(x.Low, depth+1) - } - // blanks around ":" if both sides exist and either side is a binary expression - if depth <= 1 && x.Low != nil && x.High != nil && (isBinary(x.Low) || isBinary(x.High)) { - p.print(blank, token.COLON, blank) - } else { - p.print(token.COLON) - } - if x.High != nil { - p.expr0(x.High, depth+1) - } - p.print(x.Rbrack, token.RBRACK) - - case *ast.CallExpr: - if len(x.Args) > 1 { - depth++ - } - if _, ok := x.Fun.(*ast.FuncType); ok { - // conversions to literal function types require parentheses around the type - p.print(token.LPAREN) - p.expr1(x.Fun, token.HighestPrec, depth) - p.print(token.RPAREN) - } else { - p.expr1(x.Fun, token.HighestPrec, depth) - } - p.print(x.Lparen, token.LPAREN) - if x.Ellipsis.IsValid() { - p.exprList(x.Lparen, x.Args, depth, 0, x.Ellipsis) - p.print(x.Ellipsis, token.ELLIPSIS) - if x.Rparen.IsValid() && p.lineFor(x.Ellipsis) < p.lineFor(x.Rparen) { - p.print(token.COMMA, formfeed) - } - } else { - p.exprList(x.Lparen, x.Args, depth, commaTerm, x.Rparen) - } - p.print(x.Rparen, token.RPAREN) - - case *ast.CompositeLit: - // composite literal elements that are composite literals themselves may have the type omitted - if x.Type != nil { - p.expr1(x.Type, token.HighestPrec, depth) - } - p.print(x.Lbrace, token.LBRACE) - p.exprList(x.Lbrace, x.Elts, 1, commaTerm, x.Rbrace) - // do not insert extra line breaks because of comments before - // the closing '}' as it might break the code if there is no - // trailing ',' - p.print(noExtraLinebreak, x.Rbrace, token.RBRACE, noExtraLinebreak) - - case *ast.Ellipsis: - p.print(token.ELLIPSIS) - if x.Elt != nil { - p.expr(x.Elt) - } - - case *ast.ArrayType: - p.print(token.LBRACK) - if x.Len != nil { - p.expr(x.Len) - } - p.print(token.RBRACK) - p.expr(x.Elt) - - case *ast.StructType: - p.print(token.STRUCT) - p.fieldList(x.Fields, true, x.Incomplete) - - case *ast.FuncType: - p.print(token.FUNC) - p.signature(x.Params, x.Results) - - case *ast.InterfaceType: - p.print(token.INTERFACE) - p.fieldList(x.Methods, false, x.Incomplete) - - case *ast.MapType: - p.print(token.MAP, token.LBRACK) - p.expr(x.Key) - p.print(token.RBRACK) - p.expr(x.Value) - - case *ast.ChanType: - switch x.Dir { - case ast.SEND | ast.RECV: - p.print(token.CHAN) - case ast.RECV: - p.print(token.ARROW, token.CHAN) // x.Arrow and x.Pos() are the same - case ast.SEND: - p.print(token.CHAN, x.Arrow, token.ARROW) - } - p.print(blank) - p.expr(x.Value) - - default: - panic("unreachable") - } - - return -} - -func (p *printer) expr0(x ast.Expr, depth int) { - p.expr1(x, token.LowestPrec, depth) -} - -func (p *printer) expr(x ast.Expr) { - const depth = 1 - p.expr1(x, token.LowestPrec, depth) -} - -// ---------------------------------------------------------------------------- -// 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 -// empty line is printed between statements. -func (p *printer) stmtList(list []ast.Stmt, nindent int, nextIsRBrace bool) { - if nindent > 0 { - p.print(indent) - } - multiLine := false - i := 0 - for _, s := range list { - // ignore empty statements (was issue 3466) - if _, isEmpty := s.(*ast.EmptyStmt); !isEmpty { - // _indent == 0 only for lists of switch/select case clauses; - // in those cases each clause is a new section - if len(p.output) > 0 { - // only print line break if we are not at the beginning of the output - // (i.e., we are not printing only a partial program) - p.linebreak(p.lineFor(s.Pos()), 1, ignore, i == 0 || nindent == 0 || multiLine) - } - p.stmt(s, nextIsRBrace && i == len(list)-1) - multiLine = p.isMultiLine(s) - i++ - } - } - if nindent > 0 { - p.print(unindent) - } -} - -// block prints an *ast.BlockStmt; it always spans at least two lines. -func (p *printer) block(b *ast.BlockStmt, nindent int) { - p.print(b.Lbrace, token.LBRACE) - p.stmtList(b.List, nindent, true) - p.linebreak(p.lineFor(b.Rbrace), 1, ignore, true) - p.print(b.Rbrace, token.RBRACE) -} - -func isTypeName(x ast.Expr) bool { - switch t := x.(type) { - case *ast.Ident: - return true - case *ast.SelectorExpr: - return isTypeName(t.X) - } - return false -} - -func stripParens(x ast.Expr) ast.Expr { - if px, strip := x.(*ast.ParenExpr); strip { - // parentheses must not be stripped if there are any - // unparenthesized composite literals starting with - // a type name - ast.Inspect(px.X, func(node ast.Node) bool { - switch x := node.(type) { - case *ast.ParenExpr: - // parentheses protect enclosed composite literals - return false - case *ast.CompositeLit: - if isTypeName(x.Type) { - strip = false // do not strip parentheses - } - return false - } - // in all other cases, keep inspecting - return true - }) - if strip { - return stripParens(px.X) - } - } - return x -} - -func stripParensAlways(x ast.Expr) ast.Expr { - if x, ok := x.(*ast.ParenExpr); ok { - return stripParensAlways(x.X) - } - return x -} - -func (p *printer) controlClause(isForStmt bool, init ast.Stmt, expr ast.Expr, post ast.Stmt) { - p.print(blank) - needsBlank := false - if init == nil && post == nil { - // no semicolons required - if expr != nil { - p.expr(stripParens(expr)) - needsBlank = true - } - } else { - // all semicolons required - // (they are not separators, print them explicitly) - if init != nil { - p.stmt(init, false) - } - p.print(token.SEMICOLON, blank) - if expr != nil { - p.expr(stripParens(expr)) - needsBlank = true - } - if isForStmt { - p.print(token.SEMICOLON, blank) - needsBlank = false - if post != nil { - p.stmt(post, false) - needsBlank = true - } - } - } - if needsBlank { - p.print(blank) - } -} - -// indentList reports whether an expression list would look better if it -// were indented wholesale (starting with the very first element, rather -// than starting at the first line break). -// -func (p *printer) indentList(list []ast.Expr) bool { - // Heuristic: indentList returns true if there are more than one multi- - // line element in the list, or if there is any element that is not - // starting on the same line as the previous one ends. - if len(list) >= 2 { - var b = p.lineFor(list[0].Pos()) - var e = p.lineFor(list[len(list)-1].End()) - if 0 < b && b < e { - // list spans multiple lines - n := 0 // multi-line element count - line := b - for _, x := range list { - xb := p.lineFor(x.Pos()) - xe := p.lineFor(x.End()) - if line < xb { - // x is not starting on the same - // line as the previous one ended - return true - } - if xb < xe { - // x is a multi-line element - n++ - } - line = xe - } - return n > 1 - } - } - return false -} - -func (p *printer) stmt(stmt ast.Stmt, nextIsRBrace bool) { - p.print(stmt.Pos()) - - switch s := stmt.(type) { - case *ast.BadStmt: - p.print("BadStmt") - - case *ast.DeclStmt: - p.decl(s.Decl) - - case *ast.EmptyStmt: - // nothing to do - - case *ast.LabeledStmt: - // 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) - p.print(s.Colon, token.COLON, indent) - if e, isEmpty := s.Stmt.(*ast.EmptyStmt); isEmpty { - if !nextIsRBrace { - p.print(newline, e.Pos(), token.SEMICOLON) - break - } - } else { - p.linebreak(p.lineFor(s.Stmt.Pos()), 1, ignore, true) - } - p.stmt(s.Stmt, nextIsRBrace) - - case *ast.ExprStmt: - const depth = 1 - p.expr0(s.X, depth) - - case *ast.SendStmt: - const depth = 1 - p.expr0(s.Chan, depth) - p.print(blank, s.Arrow, token.ARROW, blank) - p.expr0(s.Value, depth) - - case *ast.IncDecStmt: - const depth = 1 - p.expr0(s.X, depth+1) - p.print(s.TokPos, s.Tok) - - case *ast.AssignStmt: - var depth = 1 - if len(s.Lhs) > 1 && len(s.Rhs) > 1 { - depth++ - } - p.exprList(s.Pos(), s.Lhs, depth, 0, s.TokPos) - p.print(blank, s.TokPos, s.Tok, blank) - p.exprList(s.TokPos, s.Rhs, depth, 0, token.NoPos) - - case *ast.GoStmt: - p.print(token.GO, blank) - p.expr(s.Call) - - case *ast.DeferStmt: - p.print(token.DEFER, blank) - p.expr(s.Call) - - case *ast.ReturnStmt: - p.print(token.RETURN) - if s.Results != nil { - p.print(blank) - // Use indentList heuristic to make corner cases look - // better (issue 1207). A more systematic approach would - // always indent, but this would cause significant - // reformatting of the code base and not necessarily - // lead to more nicely formatted code in general. - if p.indentList(s.Results) { - p.print(indent) - p.exprList(s.Pos(), s.Results, 1, noIndent, token.NoPos) - p.print(unindent) - } else { - p.exprList(s.Pos(), s.Results, 1, 0, token.NoPos) - } - } - - case *ast.BranchStmt: - p.print(s.Tok) - if s.Label != nil { - p.print(blank) - p.expr(s.Label) - } - - case *ast.BlockStmt: - p.block(s, 1) - - case *ast.IfStmt: - p.print(token.IF) - p.controlClause(false, s.Init, s.Cond, nil) - p.block(s.Body, 1) - if s.Else != nil { - p.print(blank, token.ELSE, blank) - switch s.Else.(type) { - case *ast.BlockStmt, *ast.IfStmt: - p.stmt(s.Else, nextIsRBrace) - default: - p.print(token.LBRACE, indent, formfeed) - p.stmt(s.Else, true) - p.print(unindent, formfeed, token.RBRACE) - } - } - - case *ast.CaseClause: - if s.List != nil { - p.print(token.CASE, blank) - p.exprList(s.Pos(), s.List, 1, 0, s.Colon) - } else { - p.print(token.DEFAULT) - } - p.print(s.Colon, token.COLON) - p.stmtList(s.Body, 1, nextIsRBrace) - - case *ast.SwitchStmt: - p.print(token.SWITCH) - p.controlClause(false, s.Init, s.Tag, nil) - p.block(s.Body, 0) - - case *ast.TypeSwitchStmt: - p.print(token.SWITCH) - if s.Init != nil { - p.print(blank) - p.stmt(s.Init, false) - p.print(token.SEMICOLON) - } - p.print(blank) - p.stmt(s.Assign, false) - p.print(blank) - p.block(s.Body, 0) - - case *ast.CommClause: - if s.Comm != nil { - p.print(token.CASE, blank) - p.stmt(s.Comm, false) - } else { - p.print(token.DEFAULT) - } - p.print(s.Colon, token.COLON) - p.stmtList(s.Body, 1, nextIsRBrace) - - case *ast.SelectStmt: - p.print(token.SELECT, blank) - body := s.Body - if len(body.List) == 0 && !p.commentBefore(p.posFor(body.Rbrace)) { - // print empty select statement w/o comments on one line - p.print(body.Lbrace, token.LBRACE, body.Rbrace, token.RBRACE) - } else { - p.block(body, 0) - } - - case *ast.ForStmt: - p.print(token.FOR) - p.controlClause(true, s.Init, s.Cond, s.Post) - p.block(s.Body, 1) - - case *ast.RangeStmt: - p.print(token.FOR, blank) - p.expr(s.Key) - if s.Value != nil { - // use position of value following the comma as - // comma position for correct comment placement - p.print(s.Value.Pos(), token.COMMA, blank) - p.expr(s.Value) - } - p.print(blank, s.TokPos, s.Tok, blank, token.RANGE, blank) - p.expr(stripParens(s.X)) - p.print(blank) - p.block(s.Body, 1) - - default: - panic("unreachable") - } - - return -} - -// ---------------------------------------------------------------------------- -// Declarations - -// The keepTypeColumn function determines if the type column of a series of -// consecutive const or var declarations must be kept, or if initialization -// values (V) can be placed in the type column (T) instead. The i'th entry -// in the result slice is true if the type column in spec[i] must be kept. -// -// For example, the declaration: -// -// const ( -// foobar int = 42 // comment -// x = 7 // comment -// foo -// bar = 991 -// ) -// -// leads to the type/values matrix below. A run of value columns (V) can -// be moved into the type column if there is no type for any of the values -// in that column (we only move entire columns so that they align properly). -// -// matrix formatted result -// matrix -// T V -> T V -> true there is a T and so the type -// - V - V true column must be kept -// - - - - false -// - V V - false V is moved into T column -// -func keepTypeColumn(specs []ast.Spec) []bool { - m := make([]bool, len(specs)) - - populate := func(i, j int, keepType bool) { - if keepType { - for ; i < j; i++ { - m[i] = true - } - } - } - - i0 := -1 // if i0 >= 0 we are in a run and i0 is the start of the run - var keepType bool - for i, s := range specs { - t := s.(*ast.ValueSpec) - if t.Values != nil { - if i0 < 0 { - // start of a run of ValueSpecs with non-nil Values - i0 = i - keepType = false - } - } else { - if i0 >= 0 { - // end of a run - populate(i0, i, keepType) - i0 = -1 - } - } - if t.Type != nil { - keepType = true - } - } - if i0 >= 0 { - // end of a run - populate(i0, len(specs), keepType) - } - - return m -} - -func (p *printer) valueSpec(s *ast.ValueSpec, keepType bool) { - p.setComment(s.Doc) - p.identList(s.Names, false) // always present - extraTabs := 3 - if s.Type != nil || keepType { - p.print(vtab) - extraTabs-- - } - if s.Type != nil { - p.expr(s.Type) - } - if s.Values != nil { - p.print(vtab, token.ASSIGN, blank) - p.exprList(token.NoPos, s.Values, 1, 0, token.NoPos) - extraTabs-- - } - if s.Comment != nil { - for ; extraTabs > 0; extraTabs-- { - p.print(vtab) - } - p.setComment(s.Comment) - } -} - -// The parameter n is the number of specs in the group. If doIndent is set, -// multi-line identifier lists in the spec are indented when the first -// linebreak is encountered. -// -func (p *printer) spec(spec ast.Spec, n int, doIndent bool) { - switch s := spec.(type) { - case *ast.ImportSpec: - p.setComment(s.Doc) - if s.Name != nil { - p.expr(s.Name) - p.print(blank) - } - p.expr(s.Path) - p.setComment(s.Comment) - p.print(s.EndPos) - - case *ast.ValueSpec: - if n != 1 { - p.internalError("expected n = 1; got", n) - } - p.setComment(s.Doc) - p.identList(s.Names, doIndent) // always present - if s.Type != nil { - p.print(blank) - p.expr(s.Type) - } - if s.Values != nil { - p.print(blank, token.ASSIGN, blank) - p.exprList(token.NoPos, s.Values, 1, 0, token.NoPos) - } - p.setComment(s.Comment) - - case *ast.TypeSpec: - p.setComment(s.Doc) - p.expr(s.Name) - if n == 1 { - p.print(blank) - } else { - p.print(vtab) - } - p.expr(s.Type) - p.setComment(s.Comment) - - default: - panic("unreachable") - } -} - -func (p *printer) genDecl(d *ast.GenDecl) { - p.setComment(d.Doc) - p.print(d.Pos(), d.Tok, blank) - - if d.Lparen.IsValid() { - // group of parenthesized declarations - p.print(d.Lparen, token.LPAREN) - if n := len(d.Specs); n > 0 { - p.print(indent, formfeed) - if n > 1 && (d.Tok == token.CONST || d.Tok == token.VAR) { - // two or more grouped const/var declarations: - // determine if the type column must be kept - keepType := keepTypeColumn(d.Specs) - newSection := false - for i, s := range d.Specs { - if i > 0 { - p.linebreak(p.lineFor(s.Pos()), 1, ignore, newSection) - } - p.valueSpec(s.(*ast.ValueSpec), keepType[i]) - newSection = p.isMultiLine(s) - } - } else { - newSection := false - for i, s := range d.Specs { - if i > 0 { - p.linebreak(p.lineFor(s.Pos()), 1, ignore, newSection) - } - p.spec(s, n, false) - newSection = p.isMultiLine(s) - } - } - p.print(unindent, formfeed) - } - p.print(d.Rparen, token.RPAREN) - - } else { - // single declaration - p.spec(d.Specs[0], 1, true) - } -} - -// nodeSize determines the size of n in chars after formatting. -// The result is <= maxSize if the node fits on one line with at -// most maxSize chars and the formatted output doesn't contain -// any control chars. Otherwise, the result is > maxSize. -// -func (p *printer) nodeSize(n ast.Node, maxSize int) (size int) { - // nodeSize invokes the printer, which may invoke nodeSize - // recursively. For deep composite literal nests, this can - // lead to an exponential algorithm. Remember previous - // results to prune the recursion (was issue 1628). - if size, found := p.nodeSizes[n]; found { - return size - } - - size = maxSize + 1 // assume n doesn't fit - p.nodeSizes[n] = size - - // nodeSize computation must be independent of particular - // style so that we always get the same decision; print - // in RawFormat - cfg := Config{Mode: RawFormat} - var buf bytes.Buffer - if err := cfg.fprint(&buf, p.fset, n, p.nodeSizes); err != nil { - return - } - if buf.Len() <= maxSize { - for _, ch := range buf.Bytes() { - if ch < ' ' { - return - } - } - size = buf.Len() // n fits - p.nodeSizes[n] = size - } - return -} - -// bodySize is like nodeSize but it is specialized for *ast.BlockStmt's. -func (p *printer) bodySize(b *ast.BlockStmt, maxSize int) int { - pos1 := b.Pos() - pos2 := b.Rbrace - if pos1.IsValid() && pos2.IsValid() && p.lineFor(pos1) != p.lineFor(pos2) { - // opening and closing brace are on different lines - don't make it a one-liner - return maxSize + 1 - } - if len(b.List) > 5 || p.commentBefore(p.posFor(pos2)) { - // too many statements or there is a comment inside - don't make it a one-liner - return maxSize + 1 - } - // otherwise, estimate body size - bodySize := 0 - for i, s := range b.List { - if i > 0 { - bodySize += 2 // space for a semicolon and blank - } - bodySize += p.nodeSize(s, maxSize) - } - return bodySize -} - -// adjBlock prints an "adjacent" block (e.g., a for-loop or function body) following -// a header (e.g., a for-loop control clause or function signature) of given headerSize. -// If the header's and block's size are "small enough" and the block is "simple enough", -// the block is printed on the current line, without line breaks, spaced from the header -// by sep. Otherwise the block's opening "{" is printed on the current line, followed by -// lines for the block's statements and its closing "}". -// -func (p *printer) adjBlock(headerSize int, sep whiteSpace, b *ast.BlockStmt) { - if b == nil { - return - } - - const maxSize = 100 - if headerSize+p.bodySize(b, maxSize) <= maxSize { - p.print(sep, b.Lbrace, token.LBRACE) - if len(b.List) > 0 { - p.print(blank) - for i, s := range b.List { - if i > 0 { - p.print(token.SEMICOLON, blank) - } - p.stmt(s, i == len(b.List)-1) - } - p.print(blank) - } - p.print(b.Rbrace, token.RBRACE) - return - } - - if sep != ignore { - p.print(blank) // always use blank - } - p.block(b, 1) -} - -// distanceFrom returns the column difference between from and p.pos (the current -// estimated position) if both are on the same line; if they are on different lines -// (or unknown) the result is infinity. -func (p *printer) distanceFrom(from token.Pos) int { - if from.IsValid() && p.pos.IsValid() { - if f := p.posFor(from); f.Line == p.pos.Line { - return p.pos.Column - f.Column - } - } - return infinity -} - -func (p *printer) funcDecl(d *ast.FuncDecl) { - p.setComment(d.Doc) - p.print(d.Pos(), token.FUNC, blank) - if d.Recv != nil { - p.parameters(d.Recv) // method: print receiver - p.print(blank) - } - p.expr(d.Name) - p.signature(d.Type.Params, d.Type.Results) - p.adjBlock(p.distanceFrom(d.Pos()), vtab, d.Body) -} - -func (p *printer) decl(decl ast.Decl) { - switch d := decl.(type) { - case *ast.BadDecl: - p.print(d.Pos(), "BadDecl") - case *ast.GenDecl: - p.genDecl(d) - case *ast.FuncDecl: - p.funcDecl(d) - default: - panic("unreachable") - } -} - -// ---------------------------------------------------------------------------- -// Files - -func declToken(decl ast.Decl) (tok token.Token) { - tok = token.ILLEGAL - switch d := decl.(type) { - case *ast.GenDecl: - tok = d.Tok - case *ast.FuncDecl: - tok = token.FUNC - } - return -} - -func (p *printer) declList(list []ast.Decl) { - tok := token.ILLEGAL - for _, d := range list { - prev := tok - tok = declToken(d) - // If the declaration token changed (e.g., from CONST to TYPE) - // or the next declaration has documentation associated with it, - // print an empty line between top-level declarations. - // (because p.linebreak is called with the position of d, which - // is past any documentation, the minimum requirement is satisfied - // even w/o the extra getDoc(d) nil-check - leave it in case the - // linebreak logic improves - there's already a TODO). - if len(p.output) > 0 { - // only print line break if we are not at the beginning of the output - // (i.e., we are not printing only a partial program) - min := 1 - if prev != tok || getDoc(d) != nil { - min = 2 - } - p.linebreak(p.lineFor(d.Pos()), min, ignore, false) - } - p.decl(d) - } -} - -func (p *printer) file(src *ast.File) { - p.setComment(src.Doc) - p.print(src.Pos(), token.PACKAGE, blank) - p.expr(src.Name) - p.declList(src.Decls) - p.print(newline) -} diff --git a/gcc-4.8.1/libgo/go/go/printer/performance_test.go b/gcc-4.8.1/libgo/go/go/printer/performance_test.go deleted file mode 100644 index 5b29affcb..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/performance_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements a simple printer performance benchmark: -// go test -bench=BenchmarkPrint - -package printer - -import ( - "bytes" - "go/ast" - "go/parser" - "io" - "io/ioutil" - "log" - "testing" -) - -var testfile *ast.File - -func testprint(out io.Writer, file *ast.File) { - if err := (&Config{TabIndent | UseSpaces, 8, 0}).Fprint(out, fset, file); err != nil { - log.Fatalf("print error: %s", err) - } -} - -// cannot initialize in init because (printer) Fprint launches goroutines. -func initialize() { - const filename = "testdata/parser.go" - - src, err := ioutil.ReadFile(filename) - if err != nil { - log.Fatalf("%s", err) - } - - file, err := parser.ParseFile(fset, filename, src, parser.ParseComments) - if err != nil { - log.Fatalf("%s", err) - } - - var buf bytes.Buffer - testprint(&buf, file) - if !bytes.Equal(buf.Bytes(), src) { - log.Fatalf("print error: %s not idempotent", filename) - } - - testfile = file -} - -func BenchmarkPrint(b *testing.B) { - if testfile == nil { - initialize() - } - for i := 0; i < b.N; i++ { - testprint(ioutil.Discard, testfile) - } -} diff --git a/gcc-4.8.1/libgo/go/go/printer/printer.go b/gcc-4.8.1/libgo/go/go/printer/printer.go deleted file mode 100644 index f1c07bd3b..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/printer.go +++ /dev/null @@ -1,1262 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package printer implements printing of AST nodes. -package printer - -import ( - "fmt" - "go/ast" - "go/token" - "io" - "os" - "strconv" - "strings" - "text/tabwriter" - "unicode" -) - -const ( - maxNewlines = 2 // max. number of newlines between source text - debug = false // enable for debugging - infinity = 1 << 30 -) - -type whiteSpace byte - -const ( - ignore = whiteSpace(0) - blank = whiteSpace(' ') - vtab = whiteSpace('\v') - newline = whiteSpace('\n') - formfeed = whiteSpace('\f') - indent = whiteSpace('>') - unindent = whiteSpace('<') -) - -// A pmode value represents the current printer mode. -type pmode int - -const ( - noExtraLinebreak pmode = 1 << iota -) - -type printer struct { - // Configuration (does not change after initialization) - Config - fset *token.FileSet - - // Current state - output []byte // raw printer result - indent int // current indentation - mode pmode // current printer mode - impliedSemi bool // if set, a linebreak implies a semicolon - lastTok token.Token // the last token printed (token.ILLEGAL if it's whitespace) - wsbuf []whiteSpace // delayed white space - - // Positions - // The out position differs from the pos position when the result - // formatting differs from the source formatting (in the amount of - // white space). If there's a difference and SourcePos is set in - // ConfigMode, //line comments are used in the output to restore - // original source positions for a reader. - pos token.Position // current position in AST (source) space - out token.Position // current position in output space - last token.Position // value of pos after calling writeString - - // The list of all source comments, in order of appearance. - comments []*ast.CommentGroup // may be nil - cindex int // current comment index - useNodeComments bool // if not set, ignore lead and line comments of nodes - - // Information about p.comments[p.cindex]; set up by nextComment. - comment *ast.CommentGroup // = p.comments[p.cindex]; or nil - commentOffset int // = p.posFor(p.comments[p.cindex].List[0].Pos()).Offset; or infinity - commentNewline bool // true if the comment group contains newlines - - // Cache of already computed node sizes. - nodeSizes map[ast.Node]int - - // Cache of most recently computed line position. - cachedPos token.Pos - cachedLine int // line corresponding to cachedPos -} - -func (p *printer) init(cfg *Config, fset *token.FileSet, nodeSizes map[ast.Node]int) { - p.Config = *cfg - p.fset = fset - p.pos = token.Position{Line: 1, Column: 1} - p.out = token.Position{Line: 1, Column: 1} - p.wsbuf = make([]whiteSpace, 0, 16) // whitespace sequences are short - p.nodeSizes = nodeSizes - p.cachedPos = -1 -} - -// commentsHaveNewline reports whether a list of comments belonging to -// an *ast.CommentGroup contains newlines. Because the position information -// may only be partially correct, we also have to read the comment text. -func (p *printer) commentsHaveNewline(list []*ast.Comment) bool { - // len(list) > 0 - line := p.lineFor(list[0].Pos()) - for i, c := range list { - if i > 0 && p.lineFor(list[i].Pos()) != line { - // not all comments on the same line - return true - } - if t := c.Text; len(t) >= 2 && (t[1] == '/' || strings.Contains(t, "\n")) { - return true - } - } - _ = line - return false -} - -func (p *printer) nextComment() { - for p.cindex < len(p.comments) { - c := p.comments[p.cindex] - p.cindex++ - if list := c.List; len(list) > 0 { - p.comment = c - p.commentOffset = p.posFor(list[0].Pos()).Offset - p.commentNewline = p.commentsHaveNewline(list) - return - } - // we should not reach here (correct ASTs don't have empty - // ast.CommentGroup nodes), but be conservative and try again - } - // no more comments - p.commentOffset = infinity -} - -func (p *printer) internalError(msg ...interface{}) { - if debug { - fmt.Print(p.pos.String() + ": ") - fmt.Println(msg...) - panic("go/printer") - } -} - -func (p *printer) posFor(pos token.Pos) token.Position { - // not used frequently enough to cache entire token.Position - return p.fset.Position(pos) -} - -func (p *printer) lineFor(pos token.Pos) int { - if pos != p.cachedPos { - p.cachedPos = pos - p.cachedLine = p.fset.Position(pos).Line - } - return p.cachedLine -} - -// atLineBegin emits a //line comment if necessary and prints indentation. -func (p *printer) atLineBegin(pos token.Position) { - // write a //line comment if necessary - if p.Config.Mode&SourcePos != 0 && pos.IsValid() && (p.out.Line != pos.Line || p.out.Filename != pos.Filename) { - p.output = append(p.output, tabwriter.Escape) // protect '\n' in //line from tabwriter interpretation - p.output = append(p.output, fmt.Sprintf("//line %s:%d\n", pos.Filename, pos.Line)...) - p.output = append(p.output, tabwriter.Escape) - // p.out must match the //line comment - p.out.Filename = pos.Filename - p.out.Line = pos.Line - } - - // write indentation - // use "hard" htabs - indentation columns - // must not be discarded by the tabwriter - n := p.Config.Indent + p.indent // include base indentation - for i := 0; i < n; i++ { - p.output = append(p.output, '\t') - } - - // update positions - p.pos.Offset += n - p.pos.Column += n - p.out.Column += n -} - -// writeByte writes ch n times to p.output and updates p.pos. -func (p *printer) writeByte(ch byte, n int) { - if p.out.Column == 1 { - p.atLineBegin(p.pos) - } - - for i := 0; i < n; i++ { - p.output = append(p.output, ch) - } - - // update positions - p.pos.Offset += n - if ch == '\n' || ch == '\f' { - p.pos.Line += n - p.out.Line += n - p.pos.Column = 1 - p.out.Column = 1 - return - } - p.pos.Column += n - p.out.Column += n -} - -// writeString writes the string s to p.output and updates p.pos, p.out, -// and p.last. If isLit is set, s is escaped w/ tabwriter.Escape characters -// to protect s from being interpreted by the tabwriter. -// -// Note: writeString is only used to write Go tokens, literals, and -// comments, all of which must be written literally. Thus, it is correct -// to always set isLit = true. However, setting it explicitly only when -// needed (i.e., when we don't know that s contains no tabs or line breaks) -// avoids processing extra escape characters and reduces run time of the -// printer benchmark by up to 10%. -// -func (p *printer) writeString(pos token.Position, s string, isLit bool) { - if p.out.Column == 1 { - p.atLineBegin(pos) - } - - if pos.IsValid() { - // update p.pos (if pos is invalid, continue with existing p.pos) - // Note: Must do this after handling line beginnings because - // atLineBegin updates p.pos if there's indentation, but p.pos - // is the position of s. - p.pos = pos - } - - if isLit { - // Protect s such that is passes through the tabwriter - // unchanged. Note that valid Go programs cannot contain - // tabwriter.Escape bytes since they do not appear in legal - // UTF-8 sequences. - p.output = append(p.output, tabwriter.Escape) - } - - if debug { - p.output = append(p.output, fmt.Sprintf("/*%s*/", pos)...) // do not update p.pos! - } - p.output = append(p.output, s...) - - // update positions - nlines := 0 - var li int // index of last newline; valid if nlines > 0 - for i := 0; i < len(s); i++ { - // Go tokens cannot contain '\f' - no need to look for it - if s[i] == '\n' { - nlines++ - li = i - } - } - p.pos.Offset += len(s) - if nlines > 0 { - p.pos.Line += nlines - p.out.Line += nlines - c := len(s) - li - p.pos.Column = c - p.out.Column = c - } else { - p.pos.Column += len(s) - p.out.Column += len(s) - } - - if isLit { - p.output = append(p.output, tabwriter.Escape) - } - - p.last = p.pos -} - -// writeCommentPrefix writes the whitespace before a comment. -// If there is any pending whitespace, it consumes as much of -// it as is likely to help position the comment nicely. -// pos is the comment position, next the position of the item -// after all pending comments, prev is the previous comment in -// a group of comments (or nil), and tok is the next token. -// -func (p *printer) writeCommentPrefix(pos, next token.Position, prev, comment *ast.Comment, tok token.Token) { - if len(p.output) == 0 { - // the comment is the first item to be printed - don't write any whitespace - return - } - - if pos.IsValid() && pos.Filename != p.last.Filename { - // comment in a different file - separate with newlines - p.writeByte('\f', maxNewlines) - return - } - - if pos.Line == p.last.Line && (prev == nil || prev.Text[1] != '/') { - // comment on the same line as last item: - // separate with at least one separator - hasSep := false - if prev == nil { - // first comment of a comment group - j := 0 - for i, ch := range p.wsbuf { - switch ch { - case blank: - // ignore any blanks before a comment - p.wsbuf[i] = ignore - continue - case vtab: - // respect existing tabs - important - // for proper formatting of commented structs - hasSep = true - continue - case indent: - // apply pending indentation - continue - } - j = i - break - } - p.writeWhitespace(j) - } - // make sure there is at least one separator - if !hasSep { - sep := byte('\t') - if pos.Line == next.Line { - // next item is on the same line as the comment - // (which must be a /*-style comment): separate - // with a blank instead of a tab - sep = ' ' - } - p.writeByte(sep, 1) - } - - } else { - // comment on a different line: - // separate with at least one line break - droppedLinebreak := false - j := 0 - for i, ch := range p.wsbuf { - switch ch { - case blank, vtab: - // ignore any horizontal whitespace before line breaks - p.wsbuf[i] = ignore - continue - case indent: - // apply pending indentation - continue - case unindent: - // if this is not the last unindent, apply it - // as it is (likely) belonging to the last - // construct (e.g., a multi-line expression list) - // and is not part of closing a block - if i+1 < len(p.wsbuf) && p.wsbuf[i+1] == unindent { - continue - } - // if the next token is not a closing }, apply the unindent - // if it appears that the comment is aligned with the - // token; otherwise assume the unindent is part of a - // closing block and stop (this scenario appears with - // comments before a case label where the comments - // apply to the next case instead of the current one) - if tok != token.RBRACE && pos.Column == next.Column { - continue - } - case newline, formfeed: - p.wsbuf[i] = ignore - droppedLinebreak = prev == nil // record only if first comment of a group - } - j = i - break - } - p.writeWhitespace(j) - - // determine number of linebreaks before the comment - n := 0 - if pos.IsValid() && p.last.IsValid() { - n = pos.Line - p.last.Line - if n < 0 { // should never happen - n = 0 - } - } - - // at the package scope level only (p.indent == 0), - // add an extra newline if we dropped one before: - // this preserves a blank line before documentation - // comments at the package scope level (issue 2570) - if p.indent == 0 && droppedLinebreak { - n++ - } - - // make sure there is at least one line break - // if the previous comment was a line comment - if n == 0 && prev != nil && prev.Text[1] == '/' { - n = 1 - } - - if n > 0 { - // use formfeeds to break columns before a comment; - // this is analogous to using formfeeds to separate - // individual lines of /*-style comments - p.writeByte('\f', nlimit(n)) - } - } -} - -// Split comment text into lines -// (using strings.Split(text, "\n") is significantly slower for -// this specific purpose, as measured with: go test -bench=Print) -// -func split(text string) []string { - // count lines (comment text never ends in a newline) - n := 1 - for i := 0; i < len(text); i++ { - if text[i] == '\n' { - n++ - } - } - - // split - lines := make([]string, n) - n = 0 - i := 0 - for j := 0; j < len(text); j++ { - if text[j] == '\n' { - lines[n] = text[i:j] // exclude newline - i = j + 1 // discard newline - n++ - } - } - lines[n] = text[i:] - - return lines -} - -// Returns true if s contains only white space -// (only tabs and blanks can appear in the printer's context). -// -func isBlank(s string) bool { - for i := 0; i < len(s); i++ { - if s[i] > ' ' { - return false - } - } - return true -} - -// commonPrefix returns the common prefix of a and b. -func commonPrefix(a, b string) string { - i := 0 - for i < len(a) && i < len(b) && a[i] == b[i] && (a[i] <= ' ' || a[i] == '*') { - i++ - } - return a[0:i] -} - -// trimRight returns s with trailing whitespace removed. -func trimRight(s string) string { - return strings.TrimRightFunc(s, unicode.IsSpace) -} - -// stripCommonPrefix removes a common prefix from /*-style comment lines (unless no -// comment line is indented, all but the first line have some form of space prefix). -// The prefix is computed using heuristics such that is likely that the comment -// contents are nicely laid out after re-printing each line using the printer's -// current indentation. -// -func stripCommonPrefix(lines []string) { - if len(lines) <= 1 { - return // at most one line - nothing to do - } - // len(lines) > 1 - - // The heuristic in this function tries to handle a few - // common patterns of /*-style comments: Comments where - // the opening /* and closing */ are aligned and the - // rest of the comment text is aligned and indented with - // blanks or tabs, cases with a vertical "line of stars" - // on the left, and cases where the closing */ is on the - // same line as the last comment text. - - // 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). - // In case of two-line comments, consider the last line for - // the prefix computation since otherwise the prefix would - // be empty. - // - // Note that the first and last line are never empty (they - // contain the opening /* and closing */ respectively) and - // thus they can be ignored by the blank line check. - var prefix string - if len(lines) > 2 { - first := true - for i, line := range lines[1 : len(lines)-1] { - switch { - case isBlank(line): - lines[1+i] = "" // range starts with lines[1] - case first: - prefix = commonPrefix(line, line) - first = false - default: - prefix = commonPrefix(prefix, line) - } - } - } else { // len(lines) == 2, lines cannot be blank (contain /* and */) - line := lines[1] - prefix = commonPrefix(line, line) - } - - /* - * Check for vertical "line of stars" and correct prefix accordingly. - */ - lineOfStars := false - if i := strings.Index(prefix, "*"); i >= 0 { - // Line of stars present. - if i > 0 && prefix[i-1] == ' ' { - i-- // remove trailing blank from prefix so stars remain aligned - } - prefix = prefix[0:i] - lineOfStars = true - } else { - // No line of stars present. - // Determine the white space on the first line after the /* - // and before the beginning of the comment text, assume two - // blanks instead of the /* unless the first character after - // 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] - 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) - 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] - } else { - // comment text on the first line - suffix := make([]byte, len(first)) - n := 2 // start after opening /* - for n < len(first) && first[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] - } - // Shorten the computed common prefix by the length of - // suffix, if it is found as suffix of the prefix. - if strings.HasSuffix(prefix, string(suffix)) { - prefix = prefix[0 : len(prefix)-len(suffix)] - } - } - } - - // 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 := "*/" - i := strings.Index(last, closing) // i >= 0 (closing is always present) - if isBlank(last[0:i]) { - // last line only contains closing */ - if lineOfStars { - closing = " */" // add blank to align final star - } - lines[len(lines)-1] = prefix + closing - } else { - // last line contains more comment text - assume - // it is aligned like the other lines and include - // in prefix computation - prefix = commonPrefix(prefix, last) - } - - // Remove the common prefix from all but the first and empty lines. - for i, line := range lines { - if i > 0 && line != "" { - lines[i] = line[len(prefix):] - } - } -} - -func (p *printer) writeComment(comment *ast.Comment) { - text := comment.Text - pos := p.posFor(comment.Pos()) - - const linePrefix = "//line " - if strings.HasPrefix(text, linePrefix) && (!pos.IsValid() || pos.Column == 1) { - // possibly a line directive - ldir := strings.TrimSpace(text[len(linePrefix):]) - if i := strings.LastIndex(ldir, ":"); i >= 0 { - if line, err := strconv.Atoi(ldir[i+1:]); err == nil && line > 0 { - // The line directive we are about to print changed - // the Filename and Line number used for subsequent - // tokens. We have to update our AST-space position - // accordingly and suspend indentation temporarily. - indent := p.indent - p.indent = 0 - defer func() { - p.pos.Filename = ldir[:i] - p.pos.Line = line - p.pos.Column = 1 - p.indent = indent - }() - } - } - } - - // shortcut common case of //-style comments - if text[1] == '/' { - p.writeString(pos, trimRight(text), true) - return - } - - // for /*-style comments, print line by line and let the - // write function take care of the proper indentation - lines := split(text) - - // The comment started in the first column but is going - // to be indented. For an idempotent result, add indentation - // to all lines such that they look like they were indented - // before - this will make sure the common prefix computation - // is the same independent of how many times formatting is - // applied (was issue 1835). - if pos.IsValid() && pos.Column == 1 && p.indent > 0 { - for i, line := range lines[1:] { - lines[1+i] = " " + line - } - } - - stripCommonPrefix(lines) - - // write comment lines, separated by formfeed, - // without a line break after the last line - for i, line := range lines { - if i > 0 { - p.writeByte('\f', 1) - pos = p.pos - } - if len(line) > 0 { - p.writeString(pos, trimRight(line), true) - } - } -} - -// writeCommentSuffix writes a line break after a comment if indicated -// and processes any leftover indentation information. If a line break -// is needed, the kind of break (newline vs formfeed) depends on the -// pending whitespace. The writeCommentSuffix result indicates if a -// newline was written or if a formfeed was dropped from the whitespace -// buffer. -// -func (p *printer) writeCommentSuffix(needsLinebreak bool) (wroteNewline, droppedFF bool) { - for i, ch := range p.wsbuf { - switch ch { - case blank, vtab: - // ignore trailing whitespace - p.wsbuf[i] = ignore - case indent, unindent: - // don't lose indentation information - case newline, formfeed: - // if we need a line break, keep exactly one - // but remember if we dropped any formfeeds - if needsLinebreak { - needsLinebreak = false - wroteNewline = true - } else { - if ch == formfeed { - droppedFF = true - } - p.wsbuf[i] = ignore - } - } - } - p.writeWhitespace(len(p.wsbuf)) - - // make sure we have a line break - if needsLinebreak { - p.writeByte('\n', 1) - wroteNewline = true - } - - return -} - -// intersperseComments consumes all comments that appear before the next token -// tok and prints it together with the buffered whitespace (i.e., the whitespace -// that needs to be written before the next token). A heuristic is used to mix -// the comments and whitespace. The intersperseComments result indicates if a -// newline was written or if a formfeed was dropped from the whitespace buffer. -// -func (p *printer) intersperseComments(next token.Position, tok token.Token) (wroteNewline, droppedFF bool) { - var last *ast.Comment - for p.commentBefore(next) { - for _, c := range p.comment.List { - p.writeCommentPrefix(p.posFor(c.Pos()), next, last, c, tok) - p.writeComment(c) - last = c - } - p.nextComment() - } - - if last != nil { - // if the last comment is a /*-style comment and the next item - // follows on the same line but is not a comma or a "closing" - // token, add an extra blank for separation - if last.Text[1] == '*' && p.lineFor(last.Pos()) == next.Line && tok != token.COMMA && - tok != token.RPAREN && tok != token.RBRACK && tok != token.RBRACE { - p.writeByte(' ', 1) - } - // ensure that there is a line break after a //-style comment, - // before a closing '}' unless explicitly disabled, or at eof - needsLinebreak := - last.Text[1] == '/' || - tok == token.RBRACE && p.mode&noExtraLinebreak == 0 || - tok == token.EOF - return p.writeCommentSuffix(needsLinebreak) - } - - // no comment was written - we should never reach here since - // intersperseComments should not be called in that case - p.internalError("intersperseComments called without pending comments") - return -} - -// whiteWhitespace writes the first n whitespace entries. -func (p *printer) writeWhitespace(n int) { - // write entries - for i := 0; i < n; i++ { - switch ch := p.wsbuf[i]; ch { - case ignore: - // ignore! - case indent: - p.indent++ - case unindent: - p.indent-- - if p.indent < 0 { - p.internalError("negative indentation:", p.indent) - p.indent = 0 - } - case newline, formfeed: - // A line break immediately followed by a "correcting" - // unindent is swapped with the unindent - this permits - // proper label positioning. If a comment is between - // the line break and the label, the unindent is not - // part of the comment whitespace prefix and the comment - // will be positioned correctly indented. - if i+1 < n && p.wsbuf[i+1] == unindent { - // Use a formfeed to terminate the current section. - // Otherwise, a long label name on the next line leading - // to a wide column may increase the indentation column - // of lines before the label; effectively leading to wrong - // indentation. - p.wsbuf[i], p.wsbuf[i+1] = unindent, formfeed - i-- // do it again - continue - } - fallthrough - default: - p.writeByte(byte(ch), 1) - } - } - - // shift remaining entries down - i := 0 - for ; n < len(p.wsbuf); n++ { - p.wsbuf[i] = p.wsbuf[n] - i++ - } - p.wsbuf = p.wsbuf[0:i] -} - -// ---------------------------------------------------------------------------- -// Printing interface - -// nlines limits n to maxNewlines. -func nlimit(n int) int { - if n > maxNewlines { - n = maxNewlines - } - return n -} - -func mayCombine(prev token.Token, next byte) (b bool) { - switch prev { - case token.INT: - b = next == '.' // 1. - case token.ADD: - b = next == '+' // ++ - case token.SUB: - b = next == '-' // -- - case token.QUO: - b = next == '*' // /* - case token.LSS: - b = next == '-' || next == '<' // <- or << - case token.AND: - b = next == '&' || next == '^' // && or &^ - } - return -} - -// print prints a list of "items" (roughly corresponding to syntactic -// tokens, but also including whitespace and formatting information). -// It is the only print function that should be called directly from -// any of the AST printing functions in nodes.go. -// -// Whitespace is accumulated until a non-whitespace token appears. Any -// comments that need to appear before that token are printed first, -// taking into account the amount and structure of any pending white- -// space for best comment placement. Then, any leftover whitespace is -// printed, followed by the actual token. -// -func (p *printer) print(args ...interface{}) { - for _, arg := range args { - // information about the current arg - var data string - var isLit bool - var impliedSemi bool // value for p.impliedSemi after this arg - - switch x := arg.(type) { - case pmode: - // toggle printer mode - p.mode ^= x - continue - - case whiteSpace: - if x == ignore { - // don't add ignore's to the buffer; they - // may screw up "correcting" unindents (see - // LabeledStmt) - continue - } - i := len(p.wsbuf) - if i == cap(p.wsbuf) { - // 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.wsbuf = p.wsbuf[0 : i+1] - p.wsbuf[i] = x - if x == newline || x == formfeed { - // newlines affect the current state (p.impliedSemi) - // and not the state after printing arg (impliedSemi) - // because comments can be interspersed before the arg - // in this case - p.impliedSemi = false - } - p.lastTok = token.ILLEGAL - continue - - case *ast.Ident: - data = x.Name - impliedSemi = true - p.lastTok = token.IDENT - - case *ast.BasicLit: - data = x.Value - isLit = true - impliedSemi = true - p.lastTok = x.Kind - - case token.Token: - s := x.String() - if mayCombine(p.lastTok, s[0]) { - // the previous and the current token must be - // separated by a blank otherwise they combine - // into a different incorrect token sequence - // (except for token.INT followed by a '.' this - // should never happen because it is taken care - // of via binary expression formatting) - if len(p.wsbuf) != 0 { - p.internalError("whitespace buffer not empty") - } - p.wsbuf = p.wsbuf[0:1] - p.wsbuf[0] = ' ' - } - data = s - // some keywords followed by a newline imply a semicolon - switch x { - case token.BREAK, token.CONTINUE, token.FALLTHROUGH, token.RETURN, - token.INC, token.DEC, token.RPAREN, token.RBRACK, token.RBRACE: - impliedSemi = true - } - p.lastTok = x - - case token.Pos: - if x.IsValid() { - p.pos = p.posFor(x) // accurate position of next item - } - continue - - case string: - // incorrect AST - print error message - data = x - isLit = true - impliedSemi = true - p.lastTok = token.STRING - - default: - fmt.Fprintf(os.Stderr, "print: unsupported argument %v (%T)\n", arg, arg) - panic("go/printer type") - } - // data != "" - - next := p.pos // estimated/accurate position of next item - wroteNewline, droppedFF := p.flush(next, p.lastTok) - - // intersperse extra newlines if present in the source and - // if they don't cause extra semicolons (don't do this in - // flush as it will cause extra newlines at the end of a file) - if !p.impliedSemi { - n := nlimit(next.Line - p.pos.Line) - // don't exceed maxNewlines if we already wrote one - if wroteNewline && n == maxNewlines { - n = maxNewlines - 1 - } - if n > 0 { - ch := byte('\n') - if droppedFF { - ch = '\f' // use formfeed since we dropped one before - } - p.writeByte(ch, n) - impliedSemi = false - } - } - - p.writeString(next, data, isLit) - p.impliedSemi = impliedSemi - } -} - -// commentBefore returns true iff the current comment group occurs -// before the next position in the source code and printing it does -// not introduce implicit semicolons. -// -func (p *printer) commentBefore(next token.Position) (result bool) { - return p.commentOffset < next.Offset && (!p.impliedSemi || !p.commentNewline) -} - -// flush prints any pending comments and whitespace occurring textually -// before the position of the next token tok. The flush result indicates -// if a newline was written or if a formfeed was dropped from the whitespace -// buffer. -// -func (p *printer) flush(next token.Position, tok token.Token) (wroteNewline, droppedFF bool) { - if p.commentBefore(next) { - // if there are comments before the next item, intersperse them - wroteNewline, droppedFF = p.intersperseComments(next, tok) - } else { - // otherwise, write any leftover whitespace - p.writeWhitespace(len(p.wsbuf)) - } - return -} - -// getNode returns the ast.CommentGroup associated with n, if any. -func getDoc(n ast.Node) *ast.CommentGroup { - switch n := n.(type) { - case *ast.Field: - return n.Doc - case *ast.ImportSpec: - return n.Doc - case *ast.ValueSpec: - return n.Doc - case *ast.TypeSpec: - return n.Doc - case *ast.GenDecl: - return n.Doc - case *ast.FuncDecl: - return n.Doc - case *ast.File: - return n.Doc - } - return nil -} - -func (p *printer) printNode(node interface{}) error { - // unpack *CommentedNode, if any - var comments []*ast.CommentGroup - if cnode, ok := node.(*CommentedNode); ok { - node = cnode.Node - comments = cnode.Comments - } - - if comments != nil { - // commented node - restrict comment list to relevant range - n, ok := node.(ast.Node) - if !ok { - goto unsupported - } - beg := n.Pos() - end := n.End() - // if the node has associated documentation, - // include that commentgroup in the range - // (the comment list is sorted in the order - // of the comment appearance in the source code) - if doc := getDoc(n); doc != nil { - beg = doc.Pos() - } - // token.Pos values are global offsets, we can - // compare them directly - i := 0 - for i < len(comments) && comments[i].End() < beg { - i++ - } - j := i - for j < len(comments) && comments[j].Pos() < end { - j++ - } - if i < j { - p.comments = comments[i:j] - } - } else if n, ok := node.(*ast.File); ok { - // use ast.File comments, if any - p.comments = n.Comments - } - - // if there are no comments, use node comments - p.useNodeComments = p.comments == nil - - // get comments ready for use - p.nextComment() - - // format node - switch n := node.(type) { - case ast.Expr: - p.expr(n) - case ast.Stmt: - // A labeled statement will un-indent to position the label. - // Set p.indent to 1 so we don't get indent "underflow". - if _, ok := n.(*ast.LabeledStmt); ok { - p.indent = 1 - } - p.stmt(n, false) - case ast.Decl: - p.decl(n) - case ast.Spec: - p.spec(n, 1, false) - case []ast.Stmt: - // A labeled statement will un-indent to position the label. - // Set p.indent to 1 so we don't get indent "underflow". - for _, s := range n { - if _, ok := s.(*ast.LabeledStmt); ok { - p.indent = 1 - } - } - p.stmtList(n, 0, false) - case []ast.Decl: - p.declList(n) - case *ast.File: - p.file(n) - default: - goto unsupported - } - - return nil - -unsupported: - return fmt.Errorf("go/printer: unsupported node type %T", node) -} - -// ---------------------------------------------------------------------------- -// Trimmer - -// A trimmer is an io.Writer filter for stripping tabwriter.Escape -// characters, trailing blanks and tabs, and for converting formfeed -// and vtab characters into newlines and htabs (in case no tabwriter -// is used). Text bracketed by tabwriter.Escape characters is passed -// through unchanged. -// -type trimmer struct { - output io.Writer - state int - space []byte -} - -// trimmer is implemented as a state machine. -// It can be in one of the following states: -const ( - inSpace = iota // inside space - inEscape // inside text bracketed by tabwriter.Escapes - inText // inside text -) - -func (p *trimmer) resetSpace() { - p.state = inSpace - p.space = p.space[0:0] -} - -// Design note: It is tempting to eliminate extra blanks occurring in -// whitespace in this function as it could simplify some -// of the blanks logic in the node printing functions. -// However, this would mess up any formatting done by -// the tabwriter. - -var aNewline = []byte("\n") - -func (p *trimmer) Write(data []byte) (n int, err error) { - // invariants: - // p.state == inSpace: - // p.space is unwritten - // p.state == inEscape, inText: - // data[m:n] is unwritten - m := 0 - var b byte - for n, b = range data { - if b == '\v' { - b = '\t' // convert to htab - } - switch p.state { - case inSpace: - switch b { - case '\t', ' ': - p.space = append(p.space, b) - case '\n', '\f': - p.resetSpace() // discard trailing space - _, err = p.output.Write(aNewline) - case tabwriter.Escape: - _, err = p.output.Write(p.space) - p.state = inEscape - m = n + 1 // +1: skip tabwriter.Escape - default: - _, err = p.output.Write(p.space) - p.state = inText - m = n - } - case inEscape: - if b == tabwriter.Escape { - _, err = p.output.Write(data[m:n]) - p.resetSpace() - } - case inText: - switch b { - case '\t', ' ': - _, err = p.output.Write(data[m:n]) - p.resetSpace() - p.space = append(p.space, b) - case '\n', '\f': - _, err = p.output.Write(data[m:n]) - p.resetSpace() - _, err = p.output.Write(aNewline) - case tabwriter.Escape: - _, err = p.output.Write(data[m:n]) - p.state = inEscape - m = n + 1 // +1: skip tabwriter.Escape - } - default: - panic("unreachable") - } - if err != nil { - return - } - } - n = len(data) - - switch p.state { - case inEscape, inText: - _, err = p.output.Write(data[m:n]) - p.resetSpace() - } - - return -} - -// ---------------------------------------------------------------------------- -// Public interface - -// A Mode value is a set of flags (or 0). They control printing. -type Mode uint - -const ( - RawFormat Mode = 1 << iota // 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 - SourcePos // emit //line comments to preserve original source positions -) - -// A Config node controls the output of Fprint. -type Config struct { - Mode Mode // default: 0 - Tabwidth int // default: 8 - Indent int // default: 0 (all code is indented at least by this much) -} - -// fprint implements Fprint and takes a nodesSizes map for setting up the printer state. -func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node interface{}, nodeSizes map[ast.Node]int) (err error) { - // print node - var p printer - p.init(cfg, fset, nodeSizes) - if err = p.printNode(node); err != nil { - return - } - // print outstanding comments - p.impliedSemi = false // EOF acts like a newline - p.flush(token.Position{Offset: infinity, Line: infinity}, token.EOF) - - // redirect output through a trimmer to eliminate trailing whitespace - // (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} - - // redirect output through a tabwriter if necessary - if cfg.Mode&RawFormat == 0 { - minwidth := cfg.Tabwidth - - padchar := byte('\t') - if cfg.Mode&UseSpaces != 0 { - padchar = ' ' - } - - twmode := tabwriter.DiscardEmptyColumns - if cfg.Mode&TabIndent != 0 { - minwidth = 0 - twmode |= tabwriter.TabIndent - } - - output = tabwriter.NewWriter(output, minwidth, cfg.Tabwidth, 1, padchar, twmode) - } - - // write printer result via tabwriter/trimmer to output - if _, err = output.Write(p.output); err != nil { - return - } - - // flush tabwriter, if any - if tw, _ := output.(*tabwriter.Writer); tw != nil { - err = tw.Flush() - } - - return -} - -// A CommentedNode bundles an AST node and corresponding comments. -// It may be provided as argument to any of the Fprint functions. -// -type CommentedNode struct { - Node interface{} // *ast.File, or ast.Expr, ast.Decl, ast.Spec, or ast.Stmt - Comments []*ast.CommentGroup -} - -// Fprint "pretty-prints" an AST node to output for a given configuration cfg. -// Position information is interpreted relative to the file set fset. -// The node type must be *ast.File, *CommentedNode, []ast.Decl, []ast.Stmt, -// or assignment-compatible to ast.Expr, ast.Decl, ast.Spec, or ast.Stmt. -// -func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node interface{}) error { - return cfg.fprint(output, fset, node, make(map[ast.Node]int)) -} - -// Fprint "pretty-prints" an AST node to output. -// It calls Config.Fprint with default settings. -// -func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error { - return (&Config{Tabwidth: 8}).Fprint(output, fset, node) -} diff --git a/gcc-4.8.1/libgo/go/go/printer/printer_test.go b/gcc-4.8.1/libgo/go/go/printer/printer_test.go deleted file mode 100644 index 8454ac12b..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/printer_test.go +++ /dev/null @@ -1,569 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package printer - -import ( - "bytes" - "errors" - "flag" - "fmt" - "go/ast" - "go/parser" - "go/token" - "io/ioutil" - "path/filepath" - "testing" - "time" -) - -const ( - dataDir = "testdata" - tabwidth = 8 -) - -var update = flag.Bool("update", false, "update golden files") - -var fset = token.NewFileSet() - -type checkMode uint - -const ( - export checkMode = 1 << iota - rawFormat - idempotent -) - -// format parses src, prints the corresponding AST, verifies the resulting -// src is syntactically correct, and returns the resulting src or an error -// if any. -func format(src []byte, mode checkMode) ([]byte, error) { - // parse src - f, err := parser.ParseFile(fset, "", src, parser.ParseComments) - if err != nil { - return nil, fmt.Errorf("parse: %s\n%s", err, src) - } - - // filter exports if necessary - if mode&export != 0 { - ast.FileExports(f) // ignore result - f.Comments = nil // don't print comments that are not in AST - } - - // determine printer configuration - cfg := Config{Tabwidth: tabwidth} - if mode&rawFormat != 0 { - cfg.Mode |= RawFormat - } - - // print AST - var buf bytes.Buffer - if err := cfg.Fprint(&buf, fset, f); err != nil { - return nil, fmt.Errorf("print: %s", err) - } - - // make sure formated output is syntactically correct - res := buf.Bytes() - if _, err := parser.ParseFile(fset, "", res, 0); err != nil { - return nil, fmt.Errorf("re-parse: %s\n%s", err, buf.Bytes()) - } - - return res, nil -} - -// lineAt returns the line in text starting at offset offs. -func lineAt(text []byte, offs int) []byte { - i := offs - for i < len(text) && text[i] != '\n' { - i++ - } - return text[offs:i] -} - -// diff compares a and b. -func diff(aname, bname string, a, b []byte) error { - var buf bytes.Buffer // holding long error message - - // compare lengths - if len(a) != len(b) { - fmt.Fprintf(&buf, "\nlength changed: len(%s) = %d, len(%s) = %d", aname, len(a), bname, len(b)) - } - - // compare contents - line := 1 - offs := 1 - for i := 0; i < len(a) && i < len(b); i++ { - ch := a[i] - if ch != b[i] { - fmt.Fprintf(&buf, "\n%s:%d:%d: %s", aname, line, i-offs+1, lineAt(a, offs)) - fmt.Fprintf(&buf, "\n%s:%d:%d: %s", bname, line, i-offs+1, lineAt(b, offs)) - fmt.Fprintf(&buf, "\n\n") - break - } - if ch == '\n' { - line++ - offs = i + 1 - } - } - - if buf.Len() > 0 { - return errors.New(buf.String()) - } - return nil -} - -func runcheck(t *testing.T, source, golden string, mode checkMode) { - src, err := ioutil.ReadFile(source) - if err != nil { - t.Error(err) - return - } - - res, err := format(src, mode) - if err != nil { - t.Error(err) - return - } - - // update golden files if necessary - if *update { - if err := ioutil.WriteFile(golden, res, 0644); err != nil { - t.Error(err) - } - return - } - - // get golden - gld, err := ioutil.ReadFile(golden) - if err != nil { - t.Error(err) - return - } - - // formatted source and golden must be the same - if err := diff(source, golden, res, gld); err != nil { - t.Error(err) - return - } - - if mode&idempotent != 0 { - // formatting golden must be idempotent - // (This is very difficult to achieve in general and for now - // it is only checked for files explicitly marked as such.) - res, err = format(gld, mode) - if err := diff(golden, fmt.Sprintf("format(%s)", golden), gld, res); err != nil { - t.Errorf("golden is not idempotent: %s", err) - } - } -} - -func check(t *testing.T, source, golden string, mode checkMode) { - // start a timer to produce a time-out signal - tc := make(chan int) - go func() { - time.Sleep(10 * time.Second) // plenty of a safety margin, even for very slow machines - tc <- 0 - }() - - // run the test - cc := make(chan int) - go func() { - runcheck(t, source, golden, mode) - cc <- 0 - }() - - // wait for the first finisher - select { - case <-tc: - // test running past time out - t.Errorf("%s: running too slowly", source) - case <-cc: - // test finished within alloted time margin - } -} - -type entry struct { - source, golden string - mode checkMode -} - -// Use go test -update to create/update the respective golden files. -var data = []entry{ - {"empty.input", "empty.golden", idempotent}, - {"comments.input", "comments.golden", 0}, - {"comments.input", "comments.x", export}, - {"comments2.input", "comments2.golden", idempotent}, - {"linebreaks.input", "linebreaks.golden", idempotent}, - {"expressions.input", "expressions.golden", idempotent}, - {"expressions.input", "expressions.raw", rawFormat | idempotent}, - {"declarations.input", "declarations.golden", 0}, - {"statements.input", "statements.golden", 0}, - {"slow.input", "slow.golden", idempotent}, -} - -func TestFiles(t *testing.T) { - for _, e := range data { - source := filepath.Join(dataDir, e.source) - golden := filepath.Join(dataDir, e.golden) - check(t, source, golden, e.mode) - // TODO(gri) check that golden is idempotent - //check(t, golden, golden, e.mode) - } -} - -// TestLineComments, using a simple test case, checks that consequtive line -// comments are properly terminated with a newline even if the AST position -// information is incorrect. -// -func TestLineComments(t *testing.T) { - const src = `// comment 1 - // comment 2 - // comment 3 - package main - ` - - fset := token.NewFileSet() - f, err := parser.ParseFile(fset, "", src, parser.ParseComments) - if err != nil { - panic(err) // error in test - } - - var buf bytes.Buffer - fset = token.NewFileSet() // use the wrong file set - Fprint(&buf, fset, f) - - nlines := 0 - for _, ch := range buf.Bytes() { - if ch == '\n' { - nlines++ - } - } - - const expected = 3 - if nlines < expected { - t.Errorf("got %d, expected %d\n", nlines, expected) - t.Errorf("result:\n%s", buf.Bytes()) - } -} - -// Verify that the printer can be invoked during initialization. -func init() { - const name = "foobar" - var buf bytes.Buffer - if err := Fprint(&buf, fset, &ast.Ident{Name: name}); err != nil { - panic(err) // error in test - } - // in debug mode, the result contains additional information; - // ignore it - if s := buf.String(); !debug && s != name { - panic("got " + s + ", want " + name) - } -} - -// Verify that the printer doesn't crash if the AST contains BadXXX nodes. -func TestBadNodes(t *testing.T) { - const src = "package p\n(" - const res = "package p\nBadDecl\n" - f, err := parser.ParseFile(fset, "", src, parser.ParseComments) - if err == nil { - t.Error("expected illegal program") // error in test - } - var buf bytes.Buffer - Fprint(&buf, fset, f) - if buf.String() != res { - t.Errorf("got %q, expected %q", buf.String(), res) - } -} - -// testComment verifies that f can be parsed again after printing it -// with its first comment set to comment at any possible source offset. -func testComment(t *testing.T, f *ast.File, srclen int, comment *ast.Comment) { - f.Comments[0].List[0] = comment - var buf bytes.Buffer - for offs := 0; offs <= srclen; offs++ { - buf.Reset() - // Printing f should result in a correct program no - // matter what the (incorrect) comment position is. - if err := Fprint(&buf, fset, f); err != nil { - t.Error(err) - } - if _, err := parser.ParseFile(fset, "", buf.Bytes(), 0); err != nil { - t.Fatalf("incorrect program for pos = %d:\n%s", comment.Slash, buf.String()) - } - // Position information is just an offset. - // Move comment one byte down in the source. - comment.Slash++ - } -} - -// Verify that the printer produces a correct program -// even if the position information of comments introducing newlines -// is incorrect. -func TestBadComments(t *testing.T) { - const src = ` -// first comment - text and position changed by test -package p -import "fmt" -const pi = 3.14 // rough circle -var ( - x, y, z int = 1, 2, 3 - u, v float64 -) -func fibo(n int) { - if n < 2 { - return n /* seed values */ - } - return fibo(n-1) + fibo(n-2) -} -` - - f, err := parser.ParseFile(fset, "", src, parser.ParseComments) - if err != nil { - t.Error(err) // error in test - } - - comment := f.Comments[0].List[0] - pos := comment.Pos() - if fset.Position(pos).Offset != 1 { - t.Error("expected offset 1") // error in test - } - - testComment(t, f, len(src), &ast.Comment{Slash: pos, Text: "//-style comment"}) - testComment(t, f, len(src), &ast.Comment{Slash: pos, Text: "/*-style comment */"}) - testComment(t, f, len(src), &ast.Comment{Slash: pos, Text: "/*-style \n comment */"}) - testComment(t, f, len(src), &ast.Comment{Slash: pos, Text: "/*-style comment \n\n\n */"}) -} - -type visitor chan *ast.Ident - -func (v visitor) Visit(n ast.Node) (w ast.Visitor) { - if ident, ok := n.(*ast.Ident); ok { - v <- ident - } - return v -} - -// idents is an iterator that returns all idents in f via the result channel. -func idents(f *ast.File) <-chan *ast.Ident { - v := make(visitor) - go func() { - ast.Walk(v, f) - close(v) - }() - return v -} - -// identCount returns the number of identifiers found in f. -func identCount(f *ast.File) int { - n := 0 - for _ = range idents(f) { - n++ - } - return n -} - -// Verify that the SourcePos mode emits correct //line comments -// by testing that position information for matching identifiers -// is maintained. -func TestSourcePos(t *testing.T) { - const src = ` -package p -import ( "go/printer"; "math" ) -const pi = 3.14; var x = 0 -type t struct{ x, y, z int; u, v, w float32 } -func (t *t) foo(a, b, c int) int { - return a*t.x + b*t.y + - // two extra lines here - // ... - c*t.z -} -` - - // parse original - f1, err := parser.ParseFile(fset, "src", src, parser.ParseComments) - if err != nil { - t.Fatal(err) - } - - // pretty-print original - var buf bytes.Buffer - err = (&Config{Mode: UseSpaces | SourcePos, Tabwidth: 8}).Fprint(&buf, fset, f1) - if err != nil { - t.Fatal(err) - } - - // parse pretty printed original - // (//line comments must be interpreted even w/o parser.ParseComments set) - f2, err := parser.ParseFile(fset, "", buf.Bytes(), 0) - if err != nil { - t.Fatalf("%s\n%s", err, buf.Bytes()) - } - - // At this point the position information of identifiers in f2 should - // match the position information of corresponding identifiers in f1. - - // number of identifiers must be > 0 (test should run) and must match - n1 := identCount(f1) - n2 := identCount(f2) - if n1 == 0 { - t.Fatal("got no idents") - } - if n2 != n1 { - t.Errorf("got %d idents; want %d", n2, n1) - } - - // verify that all identifiers have correct line information - i2range := idents(f2) - for i1 := range idents(f1) { - i2 := <-i2range - - if i2.Name != i1.Name { - t.Errorf("got ident %s; want %s", i2.Name, i1.Name) - } - - l1 := fset.Position(i1.Pos()).Line - l2 := fset.Position(i2.Pos()).Line - if l2 != l1 { - t.Errorf("got line %d; want %d for %s", l2, l1, i1.Name) - } - } - - if t.Failed() { - t.Logf("\n%s", buf.Bytes()) - } -} - -var decls = []string{ - `import "fmt"`, - "const pi = 3.1415\nconst e = 2.71828\n\nvar x = pi", - "func sum(x, y int) int\t{ return x + y }", -} - -func TestDeclLists(t *testing.T) { - for _, src := range decls { - file, err := parser.ParseFile(fset, "", "package p;"+src, parser.ParseComments) - if err != nil { - panic(err) // error in test - } - - var buf bytes.Buffer - err = Fprint(&buf, fset, file.Decls) // only print declarations - if err != nil { - panic(err) // error in test - } - - out := buf.String() - if out != src { - t.Errorf("\ngot : %q\nwant: %q\n", out, src) - } - } -} - -var stmts = []string{ - "i := 0", - "select {}\nvar a, b = 1, 2\nreturn a + b", - "go f()\ndefer func() {}()", -} - -func TestStmtLists(t *testing.T) { - for _, src := range stmts { - file, err := parser.ParseFile(fset, "", "package p; func _() {"+src+"}", parser.ParseComments) - if err != nil { - panic(err) // error in test - } - - var buf bytes.Buffer - err = Fprint(&buf, fset, file.Decls[0].(*ast.FuncDecl).Body.List) // only print statements - if err != nil { - panic(err) // error in test - } - - out := buf.String() - if out != src { - t.Errorf("\ngot : %q\nwant: %q\n", out, src) - } - } -} - -func TestBaseIndent(t *testing.T) { - // The testfile must not contain multi-line raw strings since those - // are not indented (because their values must not change) and make - // this test fail. - const filename = "printer.go" - src, err := ioutil.ReadFile(filename) - if err != nil { - panic(err) // error in test - } - - file, err := parser.ParseFile(fset, filename, src, 0) - if err != nil { - panic(err) // error in test - } - - var buf bytes.Buffer - for indent := 0; indent < 4; indent++ { - buf.Reset() - (&Config{Tabwidth: tabwidth, Indent: indent}).Fprint(&buf, fset, file) - // all code must be indented by at least 'indent' tabs - lines := bytes.Split(buf.Bytes(), []byte{'\n'}) - for i, line := range lines { - if len(line) == 0 { - continue // empty lines don't have indentation - } - n := 0 - for j, b := range line { - if b != '\t' { - // end of indentation - n = j - break - } - } - if n < indent { - t.Errorf("line %d: got only %d tabs; want at least %d: %q", i, n, indent, line) - } - } - } -} - -// TestFuncType tests that an ast.FuncType with a nil Params field -// can be printed (per go/ast specification). Test case for issue 3870. -func TestFuncType(t *testing.T) { - src := &ast.File{ - Name: &ast.Ident{Name: "p"}, - Decls: []ast.Decl{ - &ast.FuncDecl{ - Name: &ast.Ident{Name: "f"}, - Type: &ast.FuncType{}, - }, - }, - } - - var buf bytes.Buffer - if err := Fprint(&buf, fset, src); err != nil { - t.Fatal(err) - } - got := buf.String() - - const want = `package p - -func f() -` - - if got != want { - t.Fatalf("got:\n%s\nwant:\n%s\n", got, want) - } -} - -// TextX is a skeleton test that can be filled in for debugging one-off cases. -// Do not remove. -func TestX(t *testing.T) { - const src = ` -package p -func _() {} -` - _, err := format([]byte(src), 0) - if err != nil { - t.Error(err) - } -} diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/comments.golden b/gcc-4.8.1/libgo/go/go/printer/testdata/comments.golden deleted file mode 100644 index 610a42a68..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/comments.golden +++ /dev/null @@ -1,638 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This is a package for testing comment placement by go/printer. -// -package main - -import "fmt" // fmt - -const c0 = 0 // zero -const ( - c1 = iota // c1 - c2 // c2 -) - -// Alignment of comments in declarations> -const ( - _ T = iota // comment - _ // comment - _ // comment - _ = iota + 10 - _ // comments - - _ = 10 // comment - _ T = 20 // comment -) - -const ( - _____ = iota // foo - _ // bar - _ = 0 // bal - _ // bat -) - -const ( - _ T = iota // comment - _ // comment - _ // comment - _ = iota + 10 - _ // comment - _ = 10 - _ = 20 // comment - _ T = 0 // comment -) - -// The SZ struct; it is empty. -type SZ struct{} - -// The S0 struct; no field is exported. -type S0 struct { - int - x, y, z int // 3 unexported fields -} - -// The S1 struct; some fields are not exported. -type S1 struct { - S0 - A, B, C float // 3 exported fields - D, b, c int // 2 unexported fields -} - -// The S2 struct; all fields are exported. -type S2 struct { - S1 - A, B, C float // 3 exported fields -} - -// The IZ interface; it is empty. -type SZ interface{} - -// The I0 interface; no method is exported. -type I0 interface { - f(x int) int // unexported method -} - -// The I1 interface; some methods are not exported. -type I1 interface { - I0 - F(x float) float // exported methods - g(x int) int // unexported method -} - -// The I2 interface; all methods are exported. -type I2 interface { - I0 - F(x float) float // exported method - G(x float) float // exported method -} - -// The S3 struct; all comments except for the last one must appear in the export. -type S3 struct { - // lead comment for F1 - F1 int // line comment for F1 - // lead comment for F2 - F2 int // line comment for F2 - f3 int // f3 is not exported -} - -// This comment group should be separated -// with a newline from the next comment -// group. - -// This comment should NOT be associated with the next declaration. - -var x int // x -var () - -// This comment SHOULD be associated with f0. -func f0() { - const pi = 3.14 // pi - var s1 struct{} /* an empty struct */ /* foo */ - // a struct constructor - // -------------------- - var s2 struct{} = struct{}{} - x := pi -} - -// -// This comment should be associated with f1, with one blank line before the comment. -// -func f1() { - f0() - /* 1 */ - // 2 - /* 3 */ - /* 4 */ - f0() -} - -func _() { - // this comment should be properly indented -} - -func _(x int) int { - if x < 0 { // the tab printed before this comment's // must not affect the remaining lines - return -x // this statement should be properly indented - } - if x < 0 { /* the tab printed before this comment's /* must not affect the remaining lines */ - return -x // this statement should be properly indented - } - return x -} - -func typeswitch(x interface{}) { - switch v := x.(type) { - case bool, int, float: - case string: - default: - } - - switch x.(type) { - } - - switch v0, ok := x.(int); v := x.(type) { - } - - switch v0, ok := x.(int); x.(type) { - case byte: // this comment should be on the same line as the keyword - // this comment should be normally indented - _ = 0 - case bool, int, float: - // this comment should be indented - case string: - default: - // this comment should be indented - } - // this comment should not be indented -} - -// -// Indentation of comments after possibly indented multi-line constructs -// (test cases for issue 3147). -// - -func _() { - s := 1 + - 2 - // should be indented like s -} - -func _() { - s := 1 + - 2 // comment - // should be indented like s -} - -func _() { - s := 1 + - 2 // comment - // should be indented like s - _ = 0 -} - -func _() { - s := 1 + - 2 - // should be indented like s - _ = 0 -} - -func _() { - s := 1 + - 2 - - // should be indented like s -} - -func _() { - s := 1 + - 2 // comment - - // should be indented like s -} - -func _() { - s := 1 + - 2 // comment - - // should be indented like s - _ = 0 -} - -func _() { - s := 1 + - 2 - - // should be indented like s - _ = 0 -} - -// Test case from issue 3147. -func f() { - templateText := "a" + // A - "b" + // B - "c" // C - - // should be aligned with f() - f() -} - -// Modified test case from issue 3147. -func f() { - templateText := "a" + // A - "b" + // B - "c" // C - - // may not be aligned with f() (source is not aligned) - f() -} - -// -// Test cases for alignment of lines in general comments. -// - -func _() { - /* freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - aligned line */ -} - -func _() { - /* freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - aligned line */ -} - -func _() { - /* - freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - aligned line */ -} - -func _() { - /* - freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - aligned line */ -} - -func _() { - /* freestanding comment - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line */ -} - -func _() { - /* freestanding comment - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line */ -} - -func _() { - /* - freestanding comment - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line */ -} - -func _() { - /* - freestanding comment - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line */ -} - -/* - * line - * of - * stars - */ - -/* another line - * of - * stars */ - -/* and another line - * of - * stars */ - -/* a line of - * stars */ - -/* and another line of - * stars */ - -/* a line of stars - */ - -/* and another line of - */ - -/* a line of stars - */ - -/* and another line of - */ - -/* -aligned in middle -here - not here -*/ - -/* -blank line in middle: - -with no leading spaces on blank line. -*/ - -/* - aligned in middle - here - not here -*/ - -/* - blank line in middle: - - with no leading spaces on blank line. -*/ - -func _() { - /* - * line - * of - * stars - */ - - /* - aligned in middle - here - not here - */ - - /* - blank line in middle: - - with no leading spaces on blank line. - */ -} - -// Some interesting interspersed comments. -// See below for more common cases. -func _( /* this */ x /* is */ /* an */ int) { -} - -func _( /* no params */) {} - -func _() { - f( /* no args */) -} - -func ( /* comment1 */ T /* comment2 */) _() {} - -func _() { /* one-line functions with comments are formatted as multi-line functions */ -} - -func _() { - _ = 0 - /* closing curly brace should be on new line */ -} - -func _() { - _ = []int{0, 1 /* don't introduce a newline after this comment - was issue 1365 */} -} - -// Test cases from issue 1542: -// Comments must not be placed before commas and cause invalid programs. -func _() { - var a = []int{1, 2 /*jasldf*/} - _ = a -} - -func _() { - var a = []int{1, 2}/*jasldf - */ - - _ = a -} - -func _() { - var a = []int{1, 2}// jasldf - - _ = a -} - -// Comments immediately adjacent to punctuation followed by a newline -// remain after the punctuation (looks better and permits alignment of -// comments). -func _() { - _ = T{ - 1, // comment after comma - 2, /* comment after comma */ - 3, // comment after comma - } - _ = T{ - 1, // comment after comma - 2, /* comment after comma */ - 3, // comment after comma - } - _ = T{ - /* comment before literal */ 1, - 2, /* comment before comma - ok to move after comma */ - 3, /* comment before comma - ok to move after comma */ - } - - for i = 0; // comment after semicolon - i < 9; /* comment after semicolon */ - i++ { // comment after opening curly brace - } - - // TODO(gri) the last comment in this example should be aligned */ - for i = 0; // comment after semicolon - i < 9; /* comment before semicolon - ok to move after semicolon */ - i++ /* comment before opening curly brace */ { - } -} - -// If there is no newline following punctuation, commas move before the punctuation. -// This way, commas interspersed in lists stay with the respective expression. -func f(x /* comment */, y int, z int /* comment */, u, v, w int /* comment */) { - f(x /* comment */, y) - f(x, /* comment */ - y) - f( - x, /* comment */ - ) -} - -func g( - x int, /* comment */ -) { -} - -type _ struct { - a, b /* comment */, c int -} - -type _ struct { - a, b /* comment */, c int -} - -func _() { - for a /* comment */, b := range x { - } -} - -// Print line directives correctly. - -// The following is a legal line directive. -//line foo:1 -func _() { - _ = 0 - // The following is a legal line directive. It must not be indented: -//line foo:2 - _ = 1 - - // The following is not a legal line directive (it doesn't start in column 1): - //line foo:2 - _ = 2 - - // The following is not a legal line directive (negative line number): - //line foo:-3 - _ = 3 -} - -// Line comments with tabs -func _() { - var finput *bufio.Reader // input file - var stderr *bufio.Writer - var ftable *bufio.Writer // y.go file - var foutput *bufio.Writer // y.output file - - var oflag string // -o [y.go] - y.go file - var vflag string // -v [y.output] - y.output file - var lflag bool // -l - disable line directives -} - -// Trailing white space in comments should be trimmed -func _() { - // This comment has 4 blanks following that should be trimmed: - /* Each line of this comment has blanks or tabs following that should be trimmed: - line 2: - line 3: - */ -} - -/* This comment is the last entry in this file. It must be printed and should be followed by a newline */ diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/comments.input b/gcc-4.8.1/libgo/go/go/printer/testdata/comments.input deleted file mode 100644 index d121dd4be..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/comments.input +++ /dev/null @@ -1,642 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This is a package for testing comment placement by go/printer. -// -package main - -import "fmt" // fmt - -const c0 = 0 // zero -const ( - c1 = iota // c1 - c2 // c2 -) - -// Alignment of comments in declarations> -const ( - _ T = iota // comment - _ // comment - _ // comment - _ = iota+10 - _ // comments - - _ = 10 // comment - _ T = 20 // comment -) - -const ( - _____ = iota // foo - _ // bar - _ = 0 // bal - _ // bat -) - -const ( - _ T = iota // comment - _ // comment - _ // comment - _ = iota + 10 - _ // comment - _ = 10 - _ = 20 // comment - _ T = 0 // comment -) - -// The SZ struct; it is empty. -type SZ struct {} - -// The S0 struct; no field is exported. -type S0 struct { - int - x, y, z int // 3 unexported fields -} - -// The S1 struct; some fields are not exported. -type S1 struct { - S0 - A, B, C float // 3 exported fields - D, b, c int // 2 unexported fields -} - -// The S2 struct; all fields are exported. -type S2 struct { - S1 - A, B, C float // 3 exported fields -} - -// The IZ interface; it is empty. -type SZ interface {} - -// The I0 interface; no method is exported. -type I0 interface { - f(x int) int // unexported method -} - -// The I1 interface; some methods are not exported. -type I1 interface { - I0 - F(x float) float // exported methods - g(x int) int // unexported method -} - -// The I2 interface; all methods are exported. -type I2 interface { - I0 - F(x float) float // exported method - G(x float) float // exported method -} - -// The S3 struct; all comments except for the last one must appear in the export. -type S3 struct { - // lead comment for F1 - F1 int // line comment for F1 - // lead comment for F2 - F2 int // line comment for F2 - f3 int // f3 is not exported -} - -// This comment group should be separated -// with a newline from the next comment -// group. - -// This comment should NOT be associated with the next declaration. - -var x int // x -var () - - -// This comment SHOULD be associated with f0. -func f0() { - const pi = 3.14 // pi - var s1 struct {} /* an empty struct */ /* foo */ - // a struct constructor - // -------------------- - var s2 struct {} = struct {}{} - x := pi -} -// -// This comment should be associated with f1, with one blank line before the comment. -// -func f1() { - f0() - /* 1 */ - // 2 - /* 3 */ - /* 4 */ - f0() -} - - -func _() { -// this comment should be properly indented -} - - -func _(x int) int { - if x < 0 { // the tab printed before this comment's // must not affect the remaining lines - return -x // this statement should be properly indented - } - if x < 0 { /* the tab printed before this comment's /* must not affect the remaining lines */ - return -x // this statement should be properly indented - } - return x -} - - -func typeswitch(x interface{}) { - switch v := x.(type) { - case bool, int, float: - case string: - default: - } - - switch x.(type) { - } - - switch v0, ok := x.(int); v := x.(type) { - } - - switch v0, ok := x.(int); x.(type) { - case byte: // this comment should be on the same line as the keyword - // this comment should be normally indented - _ = 0 - case bool, int, float: - // this comment should be indented - case string: - default: - // this comment should be indented - } - // this comment should not be indented -} - -// -// Indentation of comments after possibly indented multi-line constructs -// (test cases for issue 3147). -// - -func _() { - s := 1 + - 2 -// should be indented like s -} - -func _() { - s := 1 + - 2 // comment - // should be indented like s -} - -func _() { - s := 1 + - 2 // comment - // should be indented like s - _ = 0 -} - -func _() { - s := 1 + - 2 - // should be indented like s - _ = 0 -} - -func _() { - s := 1 + - 2 - -// should be indented like s -} - -func _() { - s := 1 + - 2 // comment - - // should be indented like s -} - -func _() { - s := 1 + - 2 // comment - - // should be indented like s - _ = 0 -} - -func _() { - s := 1 + - 2 - - // should be indented like s - _ = 0 -} - -// Test case from issue 3147. -func f() { - templateText := "a" + // A - "b" + // B - "c" // C - - // should be aligned with f() - f() -} - -// Modified test case from issue 3147. -func f() { - templateText := "a" + // A - "b" + // B - "c" // C - - // may not be aligned with f() (source is not aligned) - f() -} - -// -// Test cases for alignment of lines in general comments. -// - -func _() { - /* freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - aligned line */ -} - -func _() { - /* freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - aligned line */ -} - - -func _() { - /* - freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - aligned line */ -} - -func _() { - /* - freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - aligned line */ -} - -func _() { - /* freestanding comment - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line */ -} - -func _() { - /* freestanding comment - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line - */ -} - -func _() { - /* freestanding comment - aligned line */ -} - - -func _() { - /* - freestanding comment - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line */ -} - -func _() { - /* - freestanding comment - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line - */ -} - -func _() { - /* - freestanding comment - aligned line */ -} - -/* - * line - * of - * stars - */ - -/* another line - * of - * stars */ - -/* and another line - * of - * stars */ - -/* a line of - * stars */ - -/* and another line of - * stars */ - -/* a line of stars -*/ - -/* and another line of -*/ - -/* a line of stars - */ - -/* and another line of - */ - -/* -aligned in middle -here - not here -*/ - -/* -blank line in middle: - -with no leading spaces on blank line. -*/ - -/* - aligned in middle - here - not here -*/ - -/* - blank line in middle: - - with no leading spaces on blank line. -*/ - -func _() { - /* - * line - * of - * stars - */ - - /* - aligned in middle - here - not here - */ - - /* - blank line in middle: - - with no leading spaces on blank line. -*/ -} - - -// Some interesting interspersed comments. -// See below for more common cases. -func _(/* this */x/* is *//* an */ int) { -} - -func _(/* no params */) {} - -func _() { - f(/* no args */) -} - -func (/* comment1 */ T /* comment2 */) _() {} - -func _() { /* one-line functions with comments are formatted as multi-line functions */ } - -func _() { - _ = 0 - /* closing curly brace should be on new line */ } - -func _() { - _ = []int{0, 1 /* don't introduce a newline after this comment - was issue 1365 */} -} - -// Test cases from issue 1542: -// Comments must not be placed before commas and cause invalid programs. -func _() { - var a = []int{1, 2, /*jasldf*/ - } - _ = a -} - -func _() { - var a = []int{1, 2, /*jasldf - */ - } - _ = a -} - -func _() { - var a = []int{1, 2, // jasldf - } - _ = a -} - -// Comments immediately adjacent to punctuation followed by a newline -// remain after the punctuation (looks better and permits alignment of -// comments). -func _() { - _ = T{ - 1, // comment after comma - 2, /* comment after comma */ - 3 , // comment after comma - } - _ = T{ - 1 ,// comment after comma - 2 ,/* comment after comma */ - 3,// comment after comma - } - _ = T{ - /* comment before literal */1, - 2/* comment before comma - ok to move after comma */, - 3 /* comment before comma - ok to move after comma */ , - } - - for - i=0;// comment after semicolon - i<9;/* comment after semicolon */ - i++{// comment after opening curly brace - } - - // TODO(gri) the last comment in this example should be aligned */ - for - i=0;// comment after semicolon - i<9/* comment before semicolon - ok to move after semicolon */; - i++ /* comment before opening curly brace */ { - } -} - -// If there is no newline following punctuation, commas move before the punctuation. -// This way, commas interspersed in lists stay with the respective expression. -func f(x/* comment */, y int, z int /* comment */, u, v, w int /* comment */) { - f(x /* comment */, y) - f(x /* comment */, - y) - f( - x /* comment */, - ) -} - -func g( - x int /* comment */, -) {} - -type _ struct { - a, b /* comment */, c int -} - -type _ struct { a, b /* comment */, c int } - -func _() { - for a /* comment */, b := range x { - } -} - -// Print line directives correctly. - -// The following is a legal line directive. -//line foo:1 -func _() { - _ = 0 -// The following is a legal line directive. It must not be indented: -//line foo:2 - _ = 1 - -// The following is not a legal line directive (it doesn't start in column 1): - //line foo:2 - _ = 2 - -// The following is not a legal line directive (negative line number): -//line foo:-3 - _ = 3 -} - -// Line comments with tabs -func _() { -var finput *bufio.Reader // input file -var stderr *bufio.Writer -var ftable *bufio.Writer // y.go file -var foutput *bufio.Writer // y.output file - -var oflag string // -o [y.go] - y.go file -var vflag string // -v [y.output] - y.output file -var lflag bool // -l - disable line directives -} - -// Trailing white space in comments should be trimmed -func _() { -// This comment has 4 blanks following that should be trimmed: -/* Each line of this comment has blanks or tabs following that should be trimmed: - line 2: - line 3: -*/ -} - -/* This comment is the last entry in this file. It must be printed and should be followed by a newline */ diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/comments.x b/gcc-4.8.1/libgo/go/go/printer/testdata/comments.x deleted file mode 100644 index ae7729286..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/comments.x +++ /dev/null @@ -1,56 +0,0 @@ -// This is a package for testing comment placement by go/printer. -// -package main - -// The SZ struct; it is empty. -type SZ struct{} - -// The S0 struct; no field is exported. -type S0 struct { - // contains filtered or unexported fields -} - -// The S1 struct; some fields are not exported. -type S1 struct { - S0 - A, B, C float // 3 exported fields - D int // 2 unexported fields - // contains filtered or unexported fields -} - -// The S2 struct; all fields are exported. -type S2 struct { - S1 - A, B, C float // 3 exported fields -} - -// The IZ interface; it is empty. -type SZ interface{} - -// The I0 interface; no method is exported. -type I0 interface { - // contains filtered or unexported methods -} - -// The I1 interface; some methods are not exported. -type I1 interface { - I0 - F(x float) float // exported methods - // contains filtered or unexported methods -} - -// The I2 interface; all methods are exported. -type I2 interface { - I0 - F(x float) float // exported method - G(x float) float // exported method -} - -// The S3 struct; all comments except for the last one must appear in the export. -type S3 struct { - // lead comment for F1 - F1 int // line comment for F1 - // lead comment for F2 - F2 int // line comment for F2 - // contains filtered or unexported fields -} diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/comments2.golden b/gcc-4.8.1/libgo/go/go/printer/testdata/comments2.golden deleted file mode 100644 index d3b50bf3e..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/comments2.golden +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This is a package for testing comment placement by go/printer. -// -package main - -// Test cases for idempotent comment formatting (was issue 1835). -/* -c1a -*/ -/* - c1b -*/ -/* foo -c1c -*/ -/* foo - c1d -*/ -/* -c1e -foo */ -/* - c1f - foo */ - -func f() { - /* - c2a - */ - /* - c2b - */ - /* foo - c2c - */ - /* foo - c2d - */ - /* - c2e - foo */ - /* - c2f - foo */ -} - -func g() { - /* - c3a - */ - /* - c3b - */ - /* foo - c3c - */ - /* foo - c3d - */ - /* - c3e - foo */ - /* - c3f - foo */ -} - -// Test case taken literally from issue 1835. -func main() { - /* - prints test 5 times - */ - for i := 0; i < 5; i++ { - println("test") - } -} diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/comments2.input b/gcc-4.8.1/libgo/go/go/printer/testdata/comments2.input deleted file mode 100644 index 6f8c85c94..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/comments2.input +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This is a package for testing comment placement by go/printer. -// -package main - -// Test cases for idempotent comment formatting (was issue 1835). -/* -c1a -*/ -/* - c1b -*/ -/* foo -c1c -*/ -/* foo - c1d -*/ -/* -c1e -foo */ -/* - c1f - foo */ - -func f() { -/* -c2a -*/ -/* - c2b -*/ -/* foo -c2c -*/ -/* foo - c2d -*/ -/* -c2e -foo */ -/* - c2f - foo */ -} - -func g() { -/* -c3a -*/ -/* - c3b -*/ -/* foo -c3c -*/ -/* foo - c3d -*/ -/* -c3e -foo */ -/* - c3f - foo */ -} - -// Test case taken literally from issue 1835. -func main() { -/* -prints test 5 times -*/ - for i := 0; i < 5; i++ { - println("test") - } -}
\ No newline at end of file diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/declarations.golden b/gcc-4.8.1/libgo/go/go/printer/testdata/declarations.golden deleted file mode 100644 index 0ad72d349..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/declarations.golden +++ /dev/null @@ -1,914 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imports - -import "io" - -import ( - _ "io" -) - -import _ "io" - -import ( - "io" - "io" - "io" -) - -import ( - "io" - aLongRename "io" - - b "io" -) - -import ( - "unrenamed" - renamed "renameMe" - . "io" - _ "io" - "io" - . "os" -) - -// no newlines between consecutive single imports, but -// respect extra line breaks in the source (at most one empty line) -import _ "io" -import _ "io" -import _ "io" - -import _ "os" -import _ "os" -import _ "os" - -import _ "fmt" -import _ "fmt" -import _ "fmt" - -import "foo" // a comment -import "bar" // a comment - -import ( - _ "foo" - // a comment - "bar" - "foo" // a comment - "bar" // a comment -) - -// comments + renames -import ( - "unrenamed" // a comment - renamed "renameMe" - . "io" /* a comment */ - _ "io/ioutil" // a comment - "io" // testing alignment - . "os" - // a comment -) - -// a case that caused problems in the past (comment placement) -import ( - . "fmt" - "io" - "malloc" // for the malloc count test only - "math" - "strings" - "testing" -) - -// more import examples -import ( - "xxx" - "much_longer_name" // comment - "short_name" // comment -) - -import ( - _ "xxx" - "much_longer_name" // comment -) - -import ( - mymath "math" - "/foo/bar/long_package_path" // a comment -) - -import ( - "package_a" // comment - "package_b" - my_better_c "package_c" // comment - "package_d" // comment - my_e "package_e" // comment - - "package_a" // comment - "package_bb" - "package_ccc" // comment - "package_dddd" // comment -) - -// at least one empty line between declarations of different kind -import _ "io" - -var _ int - -// at least one empty line between declarations of the same kind -// if there is associated documentation (was issue 2570) -type T1 struct{} - -// T2 comment -type T2 struct { -} // should be a two-line struct - -// T3 comment -type T2 struct { -} // should be a two-line struct - -// printing of constant literals -const ( - _ = "foobar" - _ = "a۰۱۸" - _ = "foo६४" - _ = "bar9876" - _ = 0 - _ = 1 - _ = 123456789012345678890 - _ = 01234567 - _ = 0xcafebabe - _ = 0. - _ = .0 - _ = 3.14159265 - _ = 1e0 - _ = 1e+100 - _ = 1e-100 - _ = 2.71828e-1000 - _ = 0i - _ = 1i - _ = 012345678901234567889i - _ = 123456789012345678890i - _ = 0.i - _ = .0i - _ = 3.14159265i - _ = 1e0i - _ = 1e+100i - _ = 1e-100i - _ = 2.71828e-1000i - _ = 'a' - _ = '\000' - _ = '\xFF' - _ = '\uff16' - _ = '\U0000ff16' - _ = `foobar` - _ = `foo ---- ---- -bar` -) - -func _() { - type _ int - type _ *int - type _ []int - type _ map[string]int - type _ chan int - type _ func() int - - var _ int - var _ *int - var _ []int - var _ map[string]int - var _ chan int - var _ func() int - - type _ struct{} - type _ *struct{} - type _ []struct{} - type _ map[string]struct{} - type _ chan struct{} - type _ func() struct{} - - type _ interface{} - type _ *interface{} - type _ []interface{} - type _ map[string]interface{} - type _ chan interface{} - type _ func() interface{} - - var _ struct{} - var _ *struct{} - var _ []struct{} - var _ map[string]struct{} - var _ chan struct{} - var _ func() struct{} - - var _ interface{} - var _ *interface{} - var _ []interface{} - var _ map[string]interface{} - var _ chan interface{} - var _ func() interface{} -} - -// don't lose blank lines in grouped declarations -const ( - _ int = 0 - _ float = 1 - - _ string = "foo" - - _ = iota - _ - - // a comment - _ - - _ -) - -type ( - _ int - _ struct{} - - _ interface{} - - // a comment - _ map[string]int -) - -var ( - _ int = 0 - _ float = 1 - - _ string = "foo" - - _ bool - - // a comment - _ bool -) - -// don't lose blank lines in this struct -type _ struct { - String struct { - Str, Len int - } - Slice struct { - Array, Len, Cap int - } - Eface struct { - Typ, Ptr int - } - - UncommonType struct { - Name, PkgPath int - } - CommonType struct { - Size, Hash, Alg, Align, FieldAlign, String, UncommonType int - } - Type struct { - Typ, Ptr int - } - StructField struct { - Name, PkgPath, Typ, Tag, Offset int - } - StructType struct { - Fields int - } - PtrType struct { - Elem int - } - SliceType struct { - Elem int - } - ArrayType struct { - Elem, Len int - } - - Stktop struct { - Stackguard, Stackbase, Gobuf int - } - Gobuf struct { - Sp, Pc, G int - } - G struct { - Stackbase, Sched, Status, Alllink int - } -} - -// no blank lines in empty structs and interfaces, but leave 1- or 2-line layout alone -type _ struct{} -type _ struct { -} - -type _ interface{} -type _ interface { -} - -// no tabs for single or ungrouped decls -func _() { - const xxxxxx = 0 - type x int - var xxx int - var yyyy float = 3.14 - var zzzzz = "bar" - - const ( - xxxxxx = 0 - ) - type ( - x int - ) - var ( - xxx int - ) - var ( - yyyy float = 3.14 - ) - var ( - zzzzz = "bar" - ) -} - -// tabs for multiple or grouped decls -func _() { - // no entry has a type - const ( - zzzzzz = 1 - z = 2 - zzz = 3 - ) - // some entries have a type - const ( - xxxxxx = 1 - x = 2 - xxx = 3 - yyyyyyyy float = iota - yyyy = "bar" - yyy - yy = 2 - ) -} - -func _() { - // no entry has a type - var ( - zzzzzz = 1 - z = 2 - zzz = 3 - ) - // no entry has a value - var ( - _ int - _ float - _ string - - _ int // comment - _ float // comment - _ string // comment - ) - // some entries have a type - var ( - xxxxxx int - x float - xxx string - yyyyyyyy int = 1234 - y float = 3.14 - yyyy = "bar" - yyy string = "foo" - ) - // mixed entries - all comments should be aligned - var ( - a, b, c int - x = 10 - d int // comment - y = 20 // comment - f, ff, fff, ffff int = 0, 1, 2, 3 // comment - ) - // respect original line breaks - var _ = []T{ - T{0x20, "Telugu"}, - } - var _ = []T{ - // respect original line breaks - T{0x20, "Telugu"}, - } -} - -func _() { - type ( - xxxxxx int - x float - xxx string - xxxxx []x - xx struct{} - xxxxxxx struct { - _, _ int - _ float - } - xxxx chan<- string - ) -} - -// alignment of "=" in consecutive lines (extended example from issue 1414) -const ( - umax uint = ^uint(0) // maximum value for a uint - bpu = 1 << (5 + umax>>63) // bits per uint - foo - bar = -1 -) - -// typical enum -const ( - a MyType = iota - abcd - b - c - def -) - -// excerpt from godoc.go -var ( - goroot = flag.String("goroot", runtime.GOROOT(), "Go root directory") - testDir = flag.String("testdir", "", "Go root subdirectory - for testing only (faster startups)") - pkgPath = flag.String("path", "", "additional package directories (colon-separated)") - filter = flag.String("filter", "", "filter file containing permitted package directory paths") - filterMin = flag.Int("filter_minutes", 0, "filter file update interval in minutes; disabled if <= 0") - filterDelay delayTime // actual filter update interval in minutes; usually filterDelay == filterMin, but filterDelay may back off exponentially -) - -// formatting of structs -type _ struct{} - -type _ struct { /* this comment should be visible */ -} - -type _ struct { - // this comment should be visible and properly indented -} - -type _ struct { // this comment must not change indentation - f int - f, ff, fff, ffff int -} - -type _ struct { - string -} - -type _ struct { - string // comment -} - -type _ struct { - string "tag" -} - -type _ struct { - string "tag" // comment -} - -type _ struct { - f int -} - -type _ struct { - f int // comment -} - -type _ struct { - f int "tag" -} - -type _ struct { - f int "tag" // comment -} - -type _ struct { - bool - a, b, c int - int "tag" - ES // comment - float "tag" // comment - f int // comment - f, ff, fff, ffff int // comment - g float "tag" - h float "tag" // comment -} - -type _ struct { - a, b, - c, d int // this line should be indented - u, v, w, x float // this line should be indented - p, q, - r, s float // this line should be indented -} - -// difficult cases -type _ struct { - bool // comment - text []byte // comment -} - -// formatting of interfaces -type EI interface{} - -type _ interface { - EI -} - -type _ interface { - f() - fffff() -} - -type _ interface { - EI - f() - fffffg() -} - -type _ interface { // this comment must not change indentation - EI // here's a comment - f() // no blank between identifier and () - fffff() // no blank between identifier and () - gggggggggggg(x, y, z int) // hurray -} - -// formatting of variable declarations -func _() { - type day struct { - n int - short, long string - } - var ( - Sunday = day{0, "SUN", "Sunday"} - Monday = day{1, "MON", "Monday"} - Tuesday = day{2, "TUE", "Tuesday"} - Wednesday = day{3, "WED", "Wednesday"} - Thursday = day{4, "THU", "Thursday"} - Friday = day{5, "FRI", "Friday"} - Saturday = day{6, "SAT", "Saturday"} - ) -} - -// formatting of multi-line variable declarations -var a1, b1, c1 int // all on one line - -var a2, b2, - c2 int // this line should be indented - -var ( - a3, b3, - c3, d3 int // this line should be indented - a4, b4, c4 int // this line should be indented -) - -// Test case from issue 3304: multi-line declarations must end -// a formatting section and not influence indentation of the -// next line. -var ( - minRefreshTimeSec = flag.Int64("min_refresh_time_sec", 604800, - "minimum time window between two refreshes for a given user.") - x = flag.Int64("refresh_user_rollout_percent", 100, - "temporary flag to ramp up the refresh user rpc") - aVeryLongVariableName = stats.GetVarInt("refresh-user-count") -) - -func _() { - var privateKey2 = &Block{Type: "RSA PRIVATE KEY", - Headers: map[string]string{}, - Bytes: []uint8{0x30, 0x82, 0x1, 0x3a, 0x2, 0x1, 0x0, 0x2, - 0x41, 0x0, 0xb2, 0x99, 0xf, 0x49, 0xc4, 0x7d, 0xfa, 0x8c, - 0xd4, 0x0, 0xae, 0x6a, 0x4d, 0x1b, 0x8a, 0x3b, 0x6a, 0x13, - 0x64, 0x2b, 0x23, 0xf2, 0x8b, 0x0, 0x3b, 0xfb, 0x97, 0x79, - }, - } -} - -func _() { - var Universe = Scope{ - Names: map[string]*Ident{ - // basic types - "bool": nil, - "byte": nil, - "int8": nil, - "int16": nil, - "int32": nil, - "int64": nil, - "uint8": nil, - "uint16": nil, - "uint32": nil, - "uint64": nil, - "float32": nil, - "float64": nil, - "string": nil, - - // convenience types - "int": nil, - "uint": nil, - "uintptr": nil, - "float": nil, - - // constants - "false": nil, - "true": nil, - "iota": nil, - "nil": nil, - - // functions - "cap": nil, - "len": nil, - "new": nil, - "make": nil, - "panic": nil, - "panicln": nil, - "print": nil, - "println": nil, - }, - } -} - -// alignment of map composite entries -var _ = map[int]int{ - // small key sizes: always align even if size ratios are large - a: a, - abcdefghabcdefgh: a, - ab: a, - abc: a, - abcdefgabcdefg: a, - abcd: a, - abcde: a, - abcdef: a, - - // mixed key sizes: align when key sizes change within accepted ratio - abcdefgh: a, - abcdefghabcdefg: a, - abcdefghij: a, - abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij: a, // outlier - do not align with previous line - abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij: a, // align with previous line - - ab: a, // do not align with previous line - abcde: a, // align with previous line -} - -// alignment of map composite entries: test cases from issue 3965 -// aligned -var _ = T1{ - a: x, - b: y, - cccccccccccccccccccc: z, -} - -// not aligned -var _ = T2{ - a: x, - b: y, - ccccccccccccccccccccc: z, -} - -// aligned -var _ = T3{ - aaaaaaaaaaaaaaaaaaaa: x, - b: y, - c: z, -} - -// not aligned -var _ = T4{ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: x, - b: y, - c: z, -} - -func _() { - var _ = T{ - a, // must introduce trailing comma - } -} - -// formatting of function results -func _() func() {} -func _() func(int) { return nil } -func _() func(int) int { return nil } -func _() func(int) func(int) func() { return nil } - -// formatting of consecutive single-line functions -func _() {} -func _() {} -func _() {} - -func _() {} // an empty line before this function -func _() {} -func _() {} - -func _() { f(1, 2, 3) } -func _(x int) int { y := x; return y + 1 } -func _() int { type T struct{}; var x T; return x } - -// these must remain multi-line since they are multi-line in the source -func _() { - f(1, 2, 3) -} -func _(x int) int { - y := x - return y + 1 -} -func _() int { - type T struct{} - var x T - return x -} - -// making function declarations safe for new semicolon rules -func _() { /* multi-line func because of comment */ -} - -func _() { - /* multi-line func because block is on multiple lines */ -} - -// ellipsis parameters -func _(...int) -func _(...*int) -func _(...[]int) -func _(...struct{}) -func _(bool, ...interface{}) -func _(bool, ...func()) -func _(bool, ...func(...int)) -func _(bool, ...map[string]int) -func _(bool, ...chan int) - -func _(b bool, x ...int) -func _(b bool, x ...*int) -func _(b bool, x ...[]int) -func _(b bool, x ...struct{}) -func _(x ...interface{}) -func _(x ...func()) -func _(x ...func(...int)) -func _(x ...map[string]int) -func _(x ...chan int) - -// these parameter lists must remain multi-line since they are multi-line in the source -func _(bool, - int) { -} -func _(x bool, - y int) { -} -func _(x, - y bool) { -} -func _(bool, // comment - int) { -} -func _(x bool, // comment - y int) { -} -func _(x, // comment - y bool) { -} -func _(bool, // comment - // comment - int) { -} -func _(x bool, // comment - // comment - y int) { -} -func _(x, // comment - // comment - y bool) { -} -func _(bool, - // comment - int) { -} -func _(x bool, - // comment - y int) { -} -func _(x, - // comment - y bool) { -} -func _(x, // comment - y, // comment - z bool) { -} -func _(x, // comment - y, // comment - z bool) { -} -func _(x int, // comment - y float, // comment - z bool) { -} - -// properly indent multi-line signatures -func ManageStatus(in <-chan *Status, req <-chan Request, - stat chan<- *TargetInfo, - TargetHistorySize int) { -} - -func MultiLineSignature0( - a, b, c int, -) { -} - -func MultiLineSignature1( - a, b, c int, - u, v, w float, -) { -} - -func MultiLineSignature2( - a, b, - c int, -) { -} - -func MultiLineSignature3( - a, b, - c int, u, v, - w float, - x ...int) { -} - -func MultiLineSignature4( - a, b, c int, - u, v, - w float, - x ...int) { -} - -func MultiLineSignature5( - a, b, c int, - u, v, w float, - p, q, - r string, - x ...int) { -} - -// make sure it also works for methods in interfaces -type _ interface { - MultiLineSignature0( - a, b, c int, - ) - - MultiLineSignature1( - a, b, c int, - u, v, w float, - ) - - MultiLineSignature2( - a, b, - c int, - ) - - MultiLineSignature3( - a, b, - c int, u, v, - w float, - x ...int) - - MultiLineSignature4( - a, b, c int, - u, v, - w float, - x ...int) - - MultiLineSignature5( - a, b, c int, - u, v, w float, - p, q, - r string, - x ...int) -} - -// omit superfluous parentheses in parameter lists -func _(int) -func _(int) -func _(x int) -func _(x int) -func _(x, y int) -func _(x, y int) - -func _() int -func _() int -func _() int - -func _() (x int) -func _() (x int) -func _() (x int) - -// special cases: some channel types require parentheses -func _(x chan (<-chan int)) -func _(x chan (<-chan int)) -func _(x chan (<-chan int)) - -func _(x chan<- (chan int)) -func _(x chan<- (chan int)) -func _(x chan<- (chan int)) diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/declarations.input b/gcc-4.8.1/libgo/go/go/printer/testdata/declarations.input deleted file mode 100644 index 455c0c6c1..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/declarations.input +++ /dev/null @@ -1,923 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imports - -import "io" - -import ( - _ "io" -) - -import _ "io" - -import ( - "io" - "io" - "io" -) - -import ( - "io" - aLongRename "io" - - b "io" -) - -import ( - "unrenamed" - renamed "renameMe" - . "io" - _ "io" - "io" - . "os" -) - -// no newlines between consecutive single imports, but -// respect extra line breaks in the source (at most one empty line) -import _ "io" -import _ "io" -import _ "io" - -import _ "os" -import _ "os" -import _ "os" - - -import _ "fmt" -import _ "fmt" -import _ "fmt" - -import "foo" // a comment -import "bar" // a comment - -import ( - _ "foo" - // a comment - "bar" - "foo" // a comment - "bar" // a comment -) - -// comments + renames -import ( - "unrenamed" // a comment - renamed "renameMe" - . "io" /* a comment */ - _ "io/ioutil" // a comment - "io" // testing alignment - . "os" - // a comment -) - -// a case that caused problems in the past (comment placement) -import ( - . "fmt" - "io" - "malloc" // for the malloc count test only - "math" - "strings" - "testing" -) - -// more import examples -import ( - "xxx" - "much_longer_name" // comment - "short_name" // comment -) - -import ( - _ "xxx" - "much_longer_name" // comment -) - -import ( - mymath "math" - "/foo/bar/long_package_path" // a comment -) - -import ( - "package_a" // comment - "package_b" - my_better_c "package_c" // comment - "package_d" // comment - my_e "package_e" // comment - - "package_a" // comment - "package_bb" - "package_ccc" // comment - "package_dddd" // comment -) - -// at least one empty line between declarations of different kind -import _ "io" -var _ int - -// at least one empty line between declarations of the same kind -// if there is associated documentation (was issue 2570) -type T1 struct{} -// T2 comment -type T2 struct { -} // should be a two-line struct - - -// T3 comment -type T2 struct { - - -} // should be a two-line struct - - -// printing of constant literals -const ( - _ = "foobar" - _ = "a۰۱۸" - _ = "foo६४" - _ = "bar9876" - _ = 0 - _ = 1 - _ = 123456789012345678890 - _ = 01234567 - _ = 0xcafebabe - _ = 0. - _ = .0 - _ = 3.14159265 - _ = 1e0 - _ = 1e+100 - _ = 1e-100 - _ = 2.71828e-1000 - _ = 0i - _ = 1i - _ = 012345678901234567889i - _ = 123456789012345678890i - _ = 0.i - _ = .0i - _ = 3.14159265i - _ = 1e0i - _ = 1e+100i - _ = 1e-100i - _ = 2.71828e-1000i - _ = 'a' - _ = '\000' - _ = '\xFF' - _ = '\uff16' - _ = '\U0000ff16' - _ = `foobar` - _ = `foo ---- ---- -bar` -) - - -func _() { - type _ int - type _ *int - type _ []int - type _ map[string]int - type _ chan int - type _ func() int - - var _ int - var _ *int - var _ []int - var _ map[string]int - var _ chan int - var _ func() int - - type _ struct{} - type _ *struct{} - type _ []struct{} - type _ map[string]struct{} - type _ chan struct{} - type _ func() struct{} - - type _ interface{} - type _ *interface{} - type _ []interface{} - type _ map[string]interface{} - type _ chan interface{} - type _ func() interface{} - - var _ struct{} - var _ *struct{} - var _ []struct{} - var _ map[string]struct{} - var _ chan struct{} - var _ func() struct{} - - var _ interface{} - var _ *interface{} - var _ []interface{} - var _ map[string]interface{} - var _ chan interface{} - var _ func() interface{} -} - - -// don't lose blank lines in grouped declarations -const ( - _ int = 0 - _ float = 1 - - _ string = "foo" - - _ = iota - _ - - // a comment - _ - - _ -) - - -type ( - _ int - _ struct {} - - _ interface{} - - // a comment - _ map[string]int -) - - -var ( - _ int = 0 - _ float = 1 - - _ string = "foo" - - _ bool - - // a comment - _ bool -) - - -// don't lose blank lines in this struct -type _ struct { - String struct { - Str, Len int - } - Slice struct { - Array, Len, Cap int - } - Eface struct { - Typ, Ptr int - } - - UncommonType struct { - Name, PkgPath int - } - CommonType struct { - Size, Hash, Alg, Align, FieldAlign, String, UncommonType int - } - Type struct { - Typ, Ptr int - } - StructField struct { - Name, PkgPath, Typ, Tag, Offset int - } - StructType struct { - Fields int - } - PtrType struct { - Elem int - } - SliceType struct { - Elem int - } - ArrayType struct { - Elem, Len int - } - - Stktop struct { - Stackguard, Stackbase, Gobuf int - } - Gobuf struct { - Sp, Pc, G int - } - G struct { - Stackbase, Sched, Status, Alllink int - } -} - - -// no blank lines in empty structs and interfaces, but leave 1- or 2-line layout alone -type _ struct{ } -type _ struct { - -} - -type _ interface{ } -type _ interface { - -} - - -// no tabs for single or ungrouped decls -func _() { - const xxxxxx = 0 - type x int - var xxx int - var yyyy float = 3.14 - var zzzzz = "bar" - - const ( - xxxxxx = 0 - ) - type ( - x int - ) - var ( - xxx int - ) - var ( - yyyy float = 3.14 - ) - var ( - zzzzz = "bar" - ) -} - -// tabs for multiple or grouped decls -func _() { - // no entry has a type - const ( - zzzzzz = 1 - z = 2 - zzz = 3 - ) - // some entries have a type - const ( - xxxxxx = 1 - x = 2 - xxx = 3 - yyyyyyyy float = iota - yyyy = "bar" - yyy - yy = 2 - ) -} - -func _() { - // no entry has a type - var ( - zzzzzz = 1 - z = 2 - zzz = 3 - ) - // no entry has a value - var ( - _ int - _ float - _ string - - _ int // comment - _ float // comment - _ string // comment - ) - // some entries have a type - var ( - xxxxxx int - x float - xxx string - yyyyyyyy int = 1234 - y float = 3.14 - yyyy = "bar" - yyy string = "foo" - ) - // mixed entries - all comments should be aligned - var ( - a, b, c int - x = 10 - d int // comment - y = 20 // comment - f, ff, fff, ffff int = 0, 1, 2, 3 // comment - ) - // respect original line breaks - var _ = []T { - T{0x20, "Telugu"}, - } - var _ = []T { - // respect original line breaks - T{0x20, "Telugu"}, - } -} - -func _() { - type ( - xxxxxx int - x float - xxx string - xxxxx []x - xx struct{} - xxxxxxx struct { - _, _ int - _ float - } - xxxx chan<- string - ) -} - -// alignment of "=" in consecutive lines (extended example from issue 1414) -const ( - umax uint = ^uint(0) // maximum value for a uint - bpu = 1 << (5 + umax>>63) // bits per uint - foo - bar = -1 -) - -// typical enum -const ( - a MyType = iota - abcd - b - c - def -) - -// excerpt from godoc.go -var ( - goroot = flag.String("goroot", runtime.GOROOT(), "Go root directory") - testDir = flag.String("testdir", "", "Go root subdirectory - for testing only (faster startups)") - pkgPath = flag.String("path", "", "additional package directories (colon-separated)") - filter = flag.String("filter", "", "filter file containing permitted package directory paths") - filterMin = flag.Int("filter_minutes", 0, "filter file update interval in minutes; disabled if <= 0") - filterDelay delayTime // actual filter update interval in minutes; usually filterDelay == filterMin, but filterDelay may back off exponentially -) - - -// formatting of structs -type _ struct{} - -type _ struct{ /* this comment should be visible */ } - -type _ struct{ - // this comment should be visible and properly indented -} - -type _ struct { // this comment must not change indentation - f int - f, ff, fff, ffff int -} - -type _ struct { - string -} - -type _ struct { - string // comment -} - -type _ struct { - string "tag" -} - -type _ struct { - string "tag" // comment -} - -type _ struct { - f int -} - -type _ struct { - f int // comment -} - -type _ struct { - f int "tag" -} - -type _ struct { - f int "tag" // comment -} - -type _ struct { - bool - a, b, c int - int "tag" - ES // comment - float "tag" // comment - f int // comment - f, ff, fff, ffff int // comment - g float "tag" - h float "tag" // comment -} - -type _ struct { a, b, -c, d int // this line should be indented -u, v, w, x float // this line should be indented -p, q, -r, s float // this line should be indented -} - - -// difficult cases -type _ struct { - bool // comment - text []byte // comment -} - - -// formatting of interfaces -type EI interface{} - -type _ interface { - EI -} - -type _ interface { - f() - fffff() -} - -type _ interface { - EI - f() - fffffg() -} - -type _ interface { // this comment must not change indentation - EI // here's a comment - f() // no blank between identifier and () - fffff() // no blank between identifier and () - gggggggggggg(x, y, z int) () // hurray -} - - -// formatting of variable declarations -func _() { - type day struct { n int; short, long string } - var ( - Sunday = day{ 0, "SUN", "Sunday" } - Monday = day{ 1, "MON", "Monday" } - Tuesday = day{ 2, "TUE", "Tuesday" } - Wednesday = day{ 3, "WED", "Wednesday" } - Thursday = day{ 4, "THU", "Thursday" } - Friday = day{ 5, "FRI", "Friday" } - Saturday = day{ 6, "SAT", "Saturday" } - ) -} - - -// formatting of multi-line variable declarations -var a1, b1, c1 int // all on one line - -var a2, b2, -c2 int // this line should be indented - -var (a3, b3, -c3, d3 int // this line should be indented -a4, b4, c4 int // this line should be indented -) - -// Test case from issue 3304: multi-line declarations must end -// a formatting section and not influence indentation of the -// next line. -var ( - minRefreshTimeSec = flag.Int64("min_refresh_time_sec", 604800, - "minimum time window between two refreshes for a given user.") - x = flag.Int64("refresh_user_rollout_percent", 100, - "temporary flag to ramp up the refresh user rpc") - aVeryLongVariableName = stats.GetVarInt("refresh-user-count") -) - -func _() { - var privateKey2 = &Block{Type: "RSA PRIVATE KEY", - Headers: map[string]string{}, - Bytes: []uint8{0x30, 0x82, 0x1, 0x3a, 0x2, 0x1, 0x0, 0x2, - 0x41, 0x0, 0xb2, 0x99, 0xf, 0x49, 0xc4, 0x7d, 0xfa, 0x8c, - 0xd4, 0x0, 0xae, 0x6a, 0x4d, 0x1b, 0x8a, 0x3b, 0x6a, 0x13, - 0x64, 0x2b, 0x23, 0xf2, 0x8b, 0x0, 0x3b, 0xfb, 0x97, 0x79, - }, - } -} - - -func _() { - var Universe = Scope { - Names: map[string]*Ident { - // basic types - "bool": nil, - "byte": nil, - "int8": nil, - "int16": nil, - "int32": nil, - "int64": nil, - "uint8": nil, - "uint16": nil, - "uint32": nil, - "uint64": nil, - "float32": nil, - "float64": nil, - "string": nil, - - // convenience types - "int": nil, - "uint": nil, - "uintptr": nil, - "float": nil, - - // constants - "false": nil, - "true": nil, - "iota": nil, - "nil": nil, - - // functions - "cap": nil, - "len": nil, - "new": nil, - "make": nil, - "panic": nil, - "panicln": nil, - "print": nil, - "println": nil, - }, - } -} - - -// alignment of map composite entries -var _ = map[int]int{ - // small key sizes: always align even if size ratios are large - a: a, - abcdefghabcdefgh: a, - ab: a, - abc: a, - abcdefgabcdefg: a, - abcd: a, - abcde: a, - abcdef: a, - - // mixed key sizes: align when key sizes change within accepted ratio - abcdefgh: a, - abcdefghabcdefg: a, - abcdefghij: a, - abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij: a, // outlier - do not align with previous line - abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij: a, // align with previous line - - ab: a, // do not align with previous line - abcde: a, // align with previous line -} - -// alignment of map composite entries: test cases from issue 3965 -// aligned -var _ = T1{ - a: x, - b: y, - cccccccccccccccccccc: z, -} - -// not aligned -var _ = T2{ - a: x, - b: y, - ccccccccccccccccccccc: z, -} - -// aligned -var _ = T3{ - aaaaaaaaaaaaaaaaaaaa: x, - b: y, - c: z, -} - -// not aligned -var _ = T4{ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: x, - b: y, - c: z, -} - - -func _() { - var _ = T{ - a, // must introduce trailing comma - } -} - - -// formatting of function results -func _() func() {} -func _() func(int) { return nil } -func _() func(int) int { return nil } -func _() func(int) func(int) func() { return nil } - - -// formatting of consecutive single-line functions -func _() {} -func _() {} -func _() {} - -func _() {} // an empty line before this function -func _() {} -func _() {} - -func _() { f(1, 2, 3) } -func _(x int) int { y := x; return y+1 } -func _() int { type T struct{}; var x T; return x } - -// these must remain multi-line since they are multi-line in the source -func _() { - f(1, 2, 3) -} -func _(x int) int { - y := x; return y+1 -} -func _() int { - type T struct{}; var x T; return x -} - - -// making function declarations safe for new semicolon rules -func _() { /* multi-line func because of comment */ } - -func _() { -/* multi-line func because block is on multiple lines */ } - - -// ellipsis parameters -func _(...int) -func _(...*int) -func _(...[]int) -func _(...struct{}) -func _(bool, ...interface{}) -func _(bool, ...func()) -func _(bool, ...func(...int)) -func _(bool, ...map[string]int) -func _(bool, ...chan int) - -func _(b bool, x ...int) -func _(b bool, x ...*int) -func _(b bool, x ...[]int) -func _(b bool, x ...struct{}) -func _(x ...interface{}) -func _(x ...func()) -func _(x ...func(...int)) -func _(x ...map[string]int) -func _(x ...chan int) - - -// these parameter lists must remain multi-line since they are multi-line in the source -func _(bool, -int) { -} -func _(x bool, -y int) { -} -func _(x, -y bool) { -} -func _(bool, // comment -int) { -} -func _(x bool, // comment -y int) { -} -func _(x, // comment -y bool) { -} -func _(bool, // comment -// comment -int) { -} -func _(x bool, // comment -// comment -y int) { -} -func _(x, // comment -// comment -y bool) { -} -func _(bool, -// comment -int) { -} -func _(x bool, -// comment -y int) { -} -func _(x, -// comment -y bool) { -} -func _(x, // comment -y,// comment -z bool) { -} -func _(x, // comment - y,// comment - z bool) { -} -func _(x int, // comment - y float, // comment - z bool) { -} - - -// properly indent multi-line signatures -func ManageStatus(in <-chan *Status, req <-chan Request, -stat chan<- *TargetInfo, -TargetHistorySize int) { -} - -func MultiLineSignature0( -a, b, c int, -) {} - -func MultiLineSignature1( -a, b, c int, -u, v, w float, -) {} - -func MultiLineSignature2( -a, b, -c int, -) {} - -func MultiLineSignature3( -a, b, -c int, u, v, -w float, - x ...int) {} - -func MultiLineSignature4( -a, b, c int, -u, v, -w float, - x ...int) {} - -func MultiLineSignature5( -a, b, c int, -u, v, w float, -p, q, -r string, - x ...int) {} - -// make sure it also works for methods in interfaces -type _ interface { -MultiLineSignature0( -a, b, c int, -) - -MultiLineSignature1( -a, b, c int, -u, v, w float, -) - -MultiLineSignature2( -a, b, -c int, -) - -MultiLineSignature3( -a, b, -c int, u, v, -w float, - x ...int) - -MultiLineSignature4( -a, b, c int, -u, v, -w float, - x ...int) - -MultiLineSignature5( -a, b, c int, -u, v, w float, -p, q, -r string, - x ...int) -} - -// omit superfluous parentheses in parameter lists -func _((int)) -func _((((((int)))))) -func _(x (int)) -func _(x (((((int)))))) -func _(x, y (int)) -func _(x, y (((((int)))))) - -func _() (int) -func _() ((int)) -func _() ((((((int)))))) - -func _() (x int) -func _() (x (int)) -func _() (x (((((int)))))) - -// special cases: some channel types require parentheses -func _(x chan(<-chan int)) -func _(x (chan(<-chan int))) -func _(x ((((chan(<-chan int)))))) - -func _(x chan<-(chan int)) -func _(x (chan<-(chan int))) -func _(x ((((chan<-(chan int)))))) diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/empty.golden b/gcc-4.8.1/libgo/go/go/printer/testdata/empty.golden deleted file mode 100644 index a055f4758..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/empty.golden +++ /dev/null @@ -1,5 +0,0 @@ -// a comment at the beginning of the file - -package empty - -// a comment at the end of the file diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/empty.input b/gcc-4.8.1/libgo/go/go/printer/testdata/empty.input deleted file mode 100644 index a055f4758..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/empty.input +++ /dev/null @@ -1,5 +0,0 @@ -// a comment at the beginning of the file - -package empty - -// a comment at the end of the file diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/expressions.golden b/gcc-4.8.1/libgo/go/go/printer/testdata/expressions.golden deleted file mode 100644 index 4291c557c..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/expressions.golden +++ /dev/null @@ -1,664 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package expressions - -type T struct { - x, y, z int -} - -var ( - a, b, c, d, e int - under_bar int - longIdentifier1, longIdentifier2, longIdentifier3 int - t0, t1, t2 T - s string - p *int -) - -func _() { - // no spaces around simple or parenthesized expressions - _ = (a + 0) - _ = a + b - _ = a + b + c - _ = a + b - c - _ = a - b - c - _ = a + (b * c) - _ = a + (b / c) - _ = a - (b % c) - _ = 1 + a - _ = a + 1 - _ = a + b + 1 - _ = s[a] - _ = s[a:] - _ = s[:b] - _ = s[1:2] - _ = s[a:b] - _ = s[0:len(s)] - _ = s[0] << 1 - _ = (s[0] << 1) & 0xf - _ = s[0]<<2 | s[1]>>4 - _ = "foo" + s - _ = s + "foo" - _ = 'a' + 'b' - _ = len(s) / 2 - _ = len(t0.x) / a - - // spaces around expressions of different precedence or expressions containing spaces - _ = a + -b - _ = a - ^b - _ = a / *p - _ = a + b*c - _ = 1 + b*c - _ = a + 2*c - _ = a + c*2 - _ = 1 + 2*3 - _ = s[1 : 2*3] - _ = s[a : b-c] - _ = s[0:] - _ = s[a+b] - _ = s[:b-c] - _ = s[a+b:] - _ = a[a<<b+1] - _ = a[a<<b+1:] - _ = s[a+b : len(s)] - _ = s[len(s):-a] - _ = s[a : len(s)+1] - _ = s[a:len(s)+1] + s - - // spaces around operators with equal or lower precedence than comparisons - _ = a == b - _ = a != b - _ = a > b - _ = a >= b - _ = a < b - _ = a <= b - _ = a < b && c > d - _ = a < b || c > d - - // spaces around "long" operands - _ = a + longIdentifier1 - _ = longIdentifier1 + a - _ = longIdentifier1 + longIdentifier2*longIdentifier3 - _ = s + "a longer string" - - // some selected cases - _ = a + t0.x - _ = a + t0.x + t1.x*t2.x - _ = a + b + c + d + e + 2*3 - _ = a + b + c + 2*3 + d + e - _ = (a + b + c) * 2 - _ = a - b + c - d + (a + b + c) + d&e - _ = under_bar - 1 - _ = Open(dpath+"/file", O_WRONLY|O_CREAT, 0666) - _ = int(c0&_Mask4)<<18 | int(c1&_Maskx)<<12 | int(c2&_Maskx)<<6 | int(c3&_Maskx) - - // the parser does not restrict expressions that may appear as statements - true - 42 - "foo" - x - (x) - a + b - a + b + c - a + (b * c) - a + (b / c) - 1 + a - a + 1 - s[a] - x << 1 - (s[0] << 1) & 0xf - "foo" + s - x == y - x < y || z > 42 -} - -func _() { - _ = a + b - _ = a + b + c - _ = a + b*c - _ = a + (b * c) - _ = (a + b) * c - _ = a + (b * c * d) - _ = a + (b*c + d) - - _ = 1 << x - _ = -1 << x - _ = 1<<x - 1 - _ = -1<<x - 1 - - _ = f(a + b) - _ = f(a + b + c) - _ = f(a + b*c) - _ = f(a + (b * c)) - _ = f(1<<x-1, 1<<x-2) - - _ = 1<<d.logWindowSize - 1 - - buf = make(x, 2*cap(b.buf)+n) - - dst[i*3+2] = dbuf[0] << 2 - dst[i*3+2] = dbuf[0]<<2 | dbuf[1]>>4 - - b.buf = b.buf[0 : b.off+m+n] - b.buf = b.buf[0 : b.off+m*n] - f(b.buf[0 : b.off+m+n]) - - signed += ' ' * 8 - tw.octal(header[148:155], chksum) - - _ = x > 0 && i >= 0 - - x1, x0 := x>>w2, x&m2 - z0 = t1<<w2 + t0 - z1 = (t1 + t0>>w2) >> w2 - q1, r1 := x1/d1, x1%d1 - r1 = r1*b2 | x0>>w2 - x1 = (x1 << z) | (x0 >> (uint(w) - z)) - x1 = x1<<z | x0>>(uint(w)-z) - - _ = buf[0 : len(buf)+1] - _ = buf[0 : n+1] - - a, b = b, a - a = b + c - a = b*c + d - _ = a*b + c - _ = a - b - c - _ = a - (b - c) - _ = a - b*c - _ = a - (b * c) - _ = a * b / c - _ = a / *b - _ = x[a|^b] - _ = x[a / *b] - _ = a & ^b - _ = a + +b - _ = a - -b - _ = x[a*-b] - _ = x[a + +b] - _ = x ^ y ^ z - _ = b[a>>24] ^ b[(a>>16)&0xFF] ^ b[(a>>8)&0xFF] ^ b[a&0xFF] - _ = len(longVariableName) * 2 - - _ = token(matchType + xlength<<lengthShift + xoffset) -} - -func f(x int, args ...int) { - f(0, args...) - f(1, args) - f(2, args[0]) - - // make sure syntactically legal code remains syntactically legal - f(3, 42 ...) // a blank must remain between 42 and ... - f(4, 42....) - f(5, 42....) - f(6, 42.0...) - f(7, 42.0...) - f(8, .42...) - f(9, .42...) - f(10, 42e0...) - f(11, 42e0...) - - _ = 42 .x // a blank must remain between 42 and .x - _ = 42..x - _ = 42..x - _ = 42.0.x - _ = 42.0.x - _ = .42.x - _ = .42.x - _ = 42e0.x - _ = 42e0.x - - // a blank must remain between the binary operator and the 2nd operand - _ = x / *y - _ = x < -1 - _ = x < <-1 - _ = x + +1 - _ = x - -1 - _ = x & &x - _ = x & ^x - - _ = f(x / *y, x < -1, x < <-1, x + +1, x - -1, x & &x, x & ^x) -} - -func _() { - _ = T{} - _ = struct{}{} - _ = [10]T{} - _ = [...]T{} - _ = []T{} - _ = map[int]T{} -} - -// one-line structs/interfaces in composite literals (up to a threshold) -func _() { - _ = struct{}{} - _ = struct{ x int }{0} - _ = struct{ x, y, z int }{0, 1, 2} - _ = struct{ int }{0} - _ = struct{ s struct{ int } }{struct{ int }{0}} -} - -func _() { - // do not modify literals - _ = "tab1 tab2 tab3 end" // string contains 3 tabs - _ = "tab1 tab2 tab3 end" // same string with 3 blanks - may be unaligned because editors see tabs in strings - _ = "" // this comment should be aligned with the one on the previous line - _ = `` - _ = ` -` - _ = `foo - bar` - _ = `three spaces before the end of the line starting here: -they must not be removed` -} - -func _() { - // smart handling of indentation for multi-line raw strings - var _ = `` - var _ = `foo` - var _ = `foo -bar` - - var _ = `` - var _ = `foo` - var _ = - // the next line should remain indented - `foo -bar` - - var _ = // comment - `` - var _ = // comment - `foo` - var _ = // comment - // the next line should remain indented - `foo -bar` - - var _ = /* comment */ `` - var _ = /* comment */ `foo` - var _ = /* comment */ `foo -bar` - - var _ = /* comment */ - `` - var _ = /* comment */ - `foo` - var _ = /* comment */ - // the next line should remain indented - `foo -bar` - - var board = []int( - `........... -........... -....●●●.... -....●●●.... -..●●●●●●●.. -..●●●○●●●.. -..●●●●●●●.. -....●●●.... -....●●●.... -........... -........... -`) - - var state = S{ - "foo", - // the next line should remain indented - `........... -........... -....●●●.... -....●●●.... -..●●●●●●●.. -..●●●○●●●.. -..●●●●●●●.. -....●●●.... -....●●●.... -........... -........... -`, - "bar", - } -} - -func _() { - // one-line function literals (body is on a single line) - _ = func() {} - _ = func() int { return 0 } - _ = func(x, y int) bool { m := (x + y) / 2; return m < 0 } - - // multi-line function literals (body is not on one line) - _ = func() { - } - _ = func() int { - return 0 - } - _ = func(x, y int) bool { - m := (x + y) / 2 - return x < y - } - - f(func() { - }) - f(func() int { - return 0 - }) - f(func(x, y int) bool { - m := (x + y) / 2 - return x < y - }) -} - -func _() { - _ = [][]int{ - []int{1}, - []int{1, 2}, - []int{1, 2, 3}, - } - _ = [][]int{ - {1}, - []int{1, 2}, - []int{1, 2, 3}, - } - _ = [][]int{ - {1}, - {1, 2}, - {1, 2, 3}, - } - _ = [][]int{{1}, {1, 2}, {1, 2, 3}} -} - -// various multi-line expressions -func _() { - // do not add extra indentation to multi-line string lists - _ = "foo" + "bar" - _ = "foo" + - "bar" + - "bah" - _ = []string{ - "abc" + - "def", - "foo" + - "bar", - } -} - -const _ = F1 + - `string = "%s";` + - `ptr = *;` + - `datafmt.T2 = s ["-" p "-"];` - -const _ = `datafmt "datafmt";` + - `default = "%v";` + - `array = *;` + - `datafmt.T3 = s {" " a a / ","};` - -const _ = `datafmt "datafmt";` + - `default = "%v";` + - `array = *;` + - `datafmt.T3 = s {" " a a / ","};` - -func _() { - _ = F1 + - `string = "%s";` + - `ptr = *;` + - `datafmt.T2 = s ["-" p "-"];` - - _ = - `datafmt "datafmt";` + - `default = "%v";` + - `array = *;` + - `datafmt.T3 = s {" " a a / ","};` - - _ = `datafmt "datafmt";` + - `default = "%v";` + - `array = *;` + - `datafmt.T3 = s {" " a a / ","};` -} - -func _() { - // respect source lines in multi-line expressions - _ = a + - b + - c - _ = a < b || - b < a - _ = "933262154439441526816992388562667004907159682643816214685929" + - "638952175999932299156089414639761565182862536979208272237582" + - "51185210916864000000000000000000000000" // 100! - _ = "170141183460469231731687303715884105727" // prime -} - -// Alignment after overlong lines -const ( - _ = "991" - _ = "2432902008176640000" // 20! - _ = "933262154439441526816992388562667004907159682643816214685929" + - "638952175999932299156089414639761565182862536979208272237582" + - "51185210916864000000000000000000000000" // 100! - _ = "170141183460469231731687303715884105727" // prime -) - -// Correct placement of operators and comments in multi-line expressions -func _() { - _ = a + // comment - b + // comment - c - _ = "a" + - "b" + // comment - "c" - _ = "ba0408" + "7265717569726564" // field 71, encoding 2, string "required" -} - -// Correct placement of terminating comma/closing parentheses in multi-line calls. -func _() { - f(1, - 2, - 3) - f(1, - 2, - 3, - ) - f(1, - 2, - 3) // comment - f(1, - 2, - 3, // comment - ) - f(1, - 2, - 3) // comment - f(1, - 2, - 3, // comment - ) -} - -// Align comments in multi-line lists of single-line expressions. -var txpix = [NCOL]draw.Color{ - draw.Yellow, // yellow - draw.Cyan, // cyan - draw.Green, // lime green - draw.GreyBlue, // slate - draw.Red, /* red */ - draw.GreyGreen, /* olive green */ - draw.Blue, /* blue */ - draw.Color(0xFF55AAFF), /* pink */ - draw.Color(0xFFAAFFFF), /* lavender */ - draw.Color(0xBB005DFF), /* maroon */ -} - -func same(t, u *Time) bool { - // respect source lines in multi-line expressions - return t.Year == u.Year && - t.Month == u.Month && - t.Day == u.Day && - t.Hour == u.Hour && - t.Minute == u.Minute && - t.Second == u.Second && - t.Weekday == u.Weekday && - t.ZoneOffset == u.ZoneOffset && - t.Zone == u.Zone -} - -func (p *parser) charClass() { - // respect source lines in multi-line expressions - if cc.negate && len(cc.ranges) == 2 && - cc.ranges[0] == '\n' && cc.ranges[1] == '\n' { - nl := new(_NotNl) - p.re.add(nl) - } -} - -func addState(s []state, inst instr, match []int) { - // handle comments correctly in multi-line expressions - for i := 0; i < l; i++ { - if s[i].inst.index() == index && // same instruction - s[i].match[0] < pos { // earlier match already going; leftmost wins - return s - } - } -} - -func (self *T) foo(x int) *T { return self } - -func _() { module.Func1().Func2() } - -func _() { - _ = new(T). - foo(1). - foo(2). - foo(3) - - _ = new(T). - foo(1). - foo(2). // inline comments - foo(3) - - _ = new(T).foo(1).foo(2).foo(3) - - // handle multiline argument list correctly - _ = new(T). - foo( - 1). - foo(2) - - _ = new(T).foo( - 1).foo(2) - - _ = Array[3+ - 4] - - _ = Method(1, 2, - 3) - - _ = new(T). - foo(). - bar().(*Type) - - _ = new(T). - foo(). - bar().(*Type). - baz() - - _ = new(T). - foo(). - bar()["idx"] - - _ = new(T). - foo(). - bar()["idx"]. - baz() - - _ = new(T). - foo(). - bar()[1:2] - - _ = new(T). - foo(). - bar()[1:2]. - baz() - - _ = new(T). - Field. - Array[3+ - 4]. - Table["foo"]. - Blob.(*Type). - Slices[1:4]. - Method(1, 2, - 3). - Thingy - - _ = a.b.c - _ = a. - b. - c - _ = a.b().c - _ = a. - b(). - c - _ = a.b[0].c - _ = a. - b[0]. - c - _ = a.b[0:].c - _ = a. - b[0:]. - c - _ = a.b.(T).c - _ = a. - b.(T). - c -} - -// Don't introduce extra newlines in strangely formatted expression lists. -func f() { - // os.Open parameters should remain on two lines - if writer, err = os.Open(outfile, s.O_WRONLY|os.O_CREATE| - os.O_TRUNC, 0666); err != nil { - log.Fatal(err) - } -} - -// Handle multi-line argument lists ending in ... correctly. -// Was issue 3130. -func _() { - _ = append(s, a...) - _ = append( - s, a...) - _ = append(s, - a...) - _ = append( - s, - a...) - _ = append(s, a..., - ) - _ = append(s, - a..., - ) - _ = append( - s, - a..., - ) -} - -// Literal function types in conversions must be parenthesized; -// for now go/parser accepts the unparenthesized form where it -// is non-ambiguous. -func _() { - // these conversions should be rewritten to look - // the same as the parenthesized conversions below - _ = (func())(nil) - _ = (func(x int) float)(nil) - _ = (func() func() func())(nil) - - _ = (func())(nil) - _ = (func(x int) float)(nil) - _ = (func() func() func())(nil) -} diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/expressions.input b/gcc-4.8.1/libgo/go/go/printer/testdata/expressions.input deleted file mode 100644 index 1ec12a050..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/expressions.input +++ /dev/null @@ -1,693 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package expressions - -type T struct { - x, y, z int -} - -var ( - a, b, c, d, e int - under_bar int - longIdentifier1, longIdentifier2, longIdentifier3 int - t0, t1, t2 T - s string - p *int -) - - -func _() { - // no spaces around simple or parenthesized expressions - _ = (a+0) - _ = a+b - _ = a+b+c - _ = a+b-c - _ = a-b-c - _ = a+(b*c) - _ = a+(b/c) - _ = a-(b%c) - _ = 1+a - _ = a+1 - _ = a+b+1 - _ = s[a] - _ = s[a:] - _ = s[:b] - _ = s[1:2] - _ = s[a:b] - _ = s[0:len(s)] - _ = s[0]<<1 - _ = (s[0]<<1)&0xf - _ = s[0] << 2 | s[1] >> 4 - _ = "foo"+s - _ = s+"foo" - _ = 'a'+'b' - _ = len(s)/2 - _ = len(t0.x)/a - - // spaces around expressions of different precedence or expressions containing spaces - _ = a + -b - _ = a - ^b - _ = a / *p - _ = a + b*c - _ = 1 + b*c - _ = a + 2*c - _ = a + c*2 - _ = 1 + 2*3 - _ = s[1 : 2*3] - _ = s[a : b-c] - _ = s[0:] - _ = s[a+b] - _ = s[: b-c] - _ = s[a+b :] - _ = a[a<<b+1] - _ = a[a<<b+1 :] - _ = s[a+b : len(s)] - _ = s[len(s) : -a] - _ = s[a : len(s)+1] - _ = s[a : len(s)+1]+s - - // spaces around operators with equal or lower precedence than comparisons - _ = a == b - _ = a != b - _ = a > b - _ = a >= b - _ = a < b - _ = a <= b - _ = a < b && c > d - _ = a < b || c > d - - // spaces around "long" operands - _ = a + longIdentifier1 - _ = longIdentifier1 + a - _ = longIdentifier1 + longIdentifier2 * longIdentifier3 - _ = s + "a longer string" - - // some selected cases - _ = a + t0.x - _ = a + t0.x + t1.x * t2.x - _ = a + b + c + d + e + 2*3 - _ = a + b + c + 2*3 + d + e - _ = (a+b+c)*2 - _ = a - b + c - d + (a+b+c) + d&e - _ = under_bar-1 - _ = Open(dpath + "/file", O_WRONLY | O_CREAT, 0666) - _ = int(c0&_Mask4)<<18 | int(c1&_Maskx)<<12 | int(c2&_Maskx)<<6 | int(c3&_Maskx) - - // the parser does not restrict expressions that may appear as statements - true - 42 - "foo" - x - (x) - a+b - a+b+c - a+(b*c) - a+(b/c) - 1+a - a+1 - s[a] - x<<1 - (s[0]<<1)&0xf - "foo"+s - x == y - x < y || z > 42 -} - - -func _() { - _ = a+b - _ = a+b+c - _ = a+b*c - _ = a+(b*c) - _ = (a+b)*c - _ = a+(b*c*d) - _ = a+(b*c+d) - - _ = 1<<x - _ = -1<<x - _ = 1<<x-1 - _ = -1<<x-1 - - _ = f(a+b) - _ = f(a+b+c) - _ = f(a+b*c) - _ = f(a+(b*c)) - _ = f(1<<x-1, 1<<x-2) - - _ = 1<<d.logWindowSize-1 - - buf = make(x, 2*cap(b.buf) + n) - - dst[i*3+2] = dbuf[0]<<2 - dst[i*3+2] = dbuf[0]<<2 | dbuf[1]>>4 - - b.buf = b.buf[0:b.off+m+n] - b.buf = b.buf[0:b.off+m*n] - f(b.buf[0:b.off+m+n]) - - signed += ' '*8 - tw.octal(header[148:155], chksum) - - _ = x > 0 && i >= 0 - - x1, x0 := x>>w2, x&m2 - z0 = t1<<w2+t0 - z1 = (t1+t0>>w2)>>w2 - q1, r1 := x1/d1, x1%d1 - r1 = r1*b2 | x0>>w2 - x1 = (x1<<z)|(x0>>(uint(w)-z)) - x1 = x1<<z | x0>>(uint(w)-z) - - _ = buf[0:len(buf)+1] - _ = buf[0:n+1] - - a,b = b,a - a = b+c - a = b*c+d - _ = a*b+c - _ = a-b-c - _ = a-(b-c) - _ = a-b*c - _ = a-(b*c) - _ = a*b/c - _ = a/ *b - _ = x[a|^b] - _ = x[a/ *b] - _ = a& ^b - _ = a+ +b - _ = a- -b - _ = x[a*-b] - _ = x[a+ +b] - _ = x^y^z - _ = b[a>>24] ^ b[(a>>16)&0xFF] ^ b[(a>>8)&0xFF] ^ b[a&0xFF] - _ = len(longVariableName)*2 - - _ = token(matchType + xlength<<lengthShift + xoffset) -} - - -func f(x int, args ...int) { - f(0, args...) - f(1, args) - f(2, args[0]) - - // make sure syntactically legal code remains syntactically legal - f(3, 42 ...) // a blank must remain between 42 and ... - f(4, 42. ...) - f(5, 42....) - f(6, 42.0 ...) - f(7, 42.0...) - f(8, .42 ...) - f(9, .42...) - f(10, 42e0 ...) - f(11, 42e0...) - - _ = 42 .x // a blank must remain between 42 and .x - _ = 42. .x - _ = 42..x - _ = 42.0 .x - _ = 42.0.x - _ = .42 .x - _ = .42.x - _ = 42e0 .x - _ = 42e0.x - - // a blank must remain between the binary operator and the 2nd operand - _ = x/ *y - _ = x< -1 - _ = x< <-1 - _ = x+ +1 - _ = x- -1 - _ = x& &x - _ = x& ^x - - _ = f(x/ *y, x< -1, x< <-1, x+ +1, x- -1, x& &x, x& ^x) -} - - -func _() { - _ = T{} - _ = struct{}{} - _ = [10]T{} - _ = [...]T{} - _ = []T{} - _ = map[int]T{} -} - - -// one-line structs/interfaces in composite literals (up to a threshold) -func _() { - _ = struct{}{} - _ = struct{ x int }{0} - _ = struct{ x, y, z int }{0, 1, 2} - _ = struct{ int }{0} - _ = struct{ s struct { int } }{struct{ int}{0} } -} - - -func _() { - // do not modify literals - _ = "tab1 tab2 tab3 end" // string contains 3 tabs - _ = "tab1 tab2 tab3 end" // same string with 3 blanks - may be unaligned because editors see tabs in strings - _ = "" // this comment should be aligned with the one on the previous line - _ = `` - _ = ` -` -_ = `foo - bar` - _ = `three spaces before the end of the line starting here: -they must not be removed` -} - - -func _() { - // smart handling of indentation for multi-line raw strings - var _ = `` - var _ = `foo` - var _ = `foo -bar` - - -var _ = - `` -var _ = - `foo` -var _ = - // the next line should remain indented - `foo -bar` - - - var _ = // comment - `` - var _ = // comment - `foo` - var _ = // comment - // the next line should remain indented - `foo -bar` - - -var _ = /* comment */ `` -var _ = /* comment */ `foo` -var _ = /* comment */ `foo -bar` - - - var _ = /* comment */ - `` - var _ = /* comment */ - `foo` - var _ = /* comment */ - // the next line should remain indented - `foo -bar` - - -var board = []int( - `........... -........... -....●●●.... -....●●●.... -..●●●●●●●.. -..●●●○●●●.. -..●●●●●●●.. -....●●●.... -....●●●.... -........... -........... -`) - - - var state = S{ - "foo", - // the next line should remain indented - `........... -........... -....●●●.... -....●●●.... -..●●●●●●●.. -..●●●○●●●.. -..●●●●●●●.. -....●●●.... -....●●●.... -........... -........... -`, - "bar", - } -} - - -func _() { - // one-line function literals (body is on a single line) - _ = func() {} - _ = func() int { return 0 } - _ = func(x, y int) bool { m := (x+y)/2; return m < 0 } - - // multi-line function literals (body is not on one line) - _ = func() { - } - _ = func() int { - return 0 - } - _ = func(x, y int) bool { - m := (x+y)/2; return x < y } - - f(func() { - }) - f(func() int { - return 0 - }) - f(func(x, y int) bool { - m := (x+y)/2; return x < y }) -} - - -func _() { - _ = [][]int { - []int{1}, - []int{1, 2}, - []int{1, 2, 3}, - } - _ = [][]int { - {1}, - []int{1, 2}, - []int{1, 2, 3}, - } - _ = [][]int { - {1}, - {1, 2}, - {1, 2, 3}, - } - _ = [][]int {{1}, {1, 2}, {1, 2, 3}} -} - - -// various multi-line expressions -func _() { - // do not add extra indentation to multi-line string lists - _ = "foo" + "bar" - _ = "foo" + - "bar" + - "bah" - _ = []string { - "abc" + - "def", - "foo" + - "bar", - } -} - - -const _ = F1 + - `string = "%s";` + - `ptr = *;` + - `datafmt.T2 = s ["-" p "-"];` - - -const _ = - `datafmt "datafmt";` + - `default = "%v";` + - `array = *;` + - `datafmt.T3 = s {" " a a / ","};` - - -const _ = `datafmt "datafmt";` + -`default = "%v";` + -`array = *;` + -`datafmt.T3 = s {" " a a / ","};` - - -func _() { - _ = F1 + - `string = "%s";` + - `ptr = *;` + - `datafmt.T2 = s ["-" p "-"];` - - _ = - `datafmt "datafmt";` + - `default = "%v";` + - `array = *;` + - `datafmt.T3 = s {" " a a / ","};` - - _ = `datafmt "datafmt";` + - `default = "%v";` + - `array = *;` + - `datafmt.T3 = s {" " a a / ","};` -} - - -func _() { - // respect source lines in multi-line expressions - _ = a+ - b+ - c - _ = a < b || - b < a - _ = "933262154439441526816992388562667004907159682643816214685929" + - "638952175999932299156089414639761565182862536979208272237582" + - "51185210916864000000000000000000000000" // 100! - _ = "170141183460469231731687303715884105727" // prime -} - - -// Alignment after overlong lines -const ( - _ = "991" - _ = "2432902008176640000" // 20! - _ = "933262154439441526816992388562667004907159682643816214685929" + - "638952175999932299156089414639761565182862536979208272237582" + - "51185210916864000000000000000000000000" // 100! - _ = "170141183460469231731687303715884105727" // prime -) - - -// Correct placement of operators and comments in multi-line expressions -func _() { - _ = a + // comment - b + // comment - c - _ = "a" + - "b" + // comment - "c" - _ = "ba0408" + "7265717569726564" // field 71, encoding 2, string "required" -} - - -// Correct placement of terminating comma/closing parentheses in multi-line calls. -func _() { - f(1, - 2, - 3) - f(1, - 2, - 3, - ) - f(1, - 2, - 3) // comment - f(1, - 2, - 3, // comment - ) - f(1, - 2, - 3)// comment - f(1, - 2, - 3,// comment - ) -} - - -// Align comments in multi-line lists of single-line expressions. -var txpix = [NCOL]draw.Color{ - draw.Yellow, // yellow - draw.Cyan, // cyan - draw.Green, // lime green - draw.GreyBlue, // slate - draw.Red, /* red */ - draw.GreyGreen, /* olive green */ - draw.Blue, /* blue */ - draw.Color(0xFF55AAFF), /* pink */ - draw.Color(0xFFAAFFFF), /* lavender */ - draw.Color(0xBB005DFF), /* maroon */ -} - - -func same(t, u *Time) bool { - // respect source lines in multi-line expressions - return t.Year == u.Year && - t.Month == u.Month && - t.Day == u.Day && - t.Hour == u.Hour && - t.Minute == u.Minute && - t.Second == u.Second && - t.Weekday == u.Weekday && - t.ZoneOffset == u.ZoneOffset && - t.Zone == u.Zone -} - - -func (p *parser) charClass() { - // respect source lines in multi-line expressions - if cc.negate && len(cc.ranges) == 2 && - cc.ranges[0] == '\n' && cc.ranges[1] == '\n' { - nl := new(_NotNl) - p.re.add(nl) - } -} - - -func addState(s []state, inst instr, match []int) { - // handle comments correctly in multi-line expressions - for i := 0; i < l; i++ { - if s[i].inst.index() == index && // same instruction - s[i].match[0] < pos { // earlier match already going; leftmost wins - return s - } - } -} - -func (self *T) foo(x int) *T { return self } - -func _() { module.Func1().Func2() } - -func _() { - _ = new(T). - foo(1). - foo(2). - foo(3) - - _ = new(T). - foo(1). - foo(2). // inline comments - foo(3) - - _ = new(T).foo(1).foo(2).foo(3) - - // handle multiline argument list correctly - _ = new(T). - foo( - 1). - foo(2) - - _ = new(T).foo( - 1).foo(2) - - _ = Array[3 + -4] - - _ = Method(1, 2, - 3) - - _ = new(T). - foo(). - bar() . (*Type) - - _ = new(T). -foo(). -bar().(*Type). -baz() - - _ = new(T). - foo(). - bar()["idx"] - - _ = new(T). - foo(). - bar()["idx"] . - baz() - - _ = new(T). - foo(). - bar()[1:2] - - _ = new(T). - foo(). - bar()[1:2]. - baz() - - _ = new(T). - Field. - Array[3+ - 4]. - Table ["foo"]. - Blob. (*Type). - Slices[1:4]. - Method(1, 2, - 3). - Thingy - - _ = a.b.c - _ = a. - b. - c - _ = a.b().c - _ = a. - b(). - c - _ = a.b[0].c - _ = a. - b[0]. - c - _ = a.b[0:].c - _ = a. - b[0:]. - c - _ = a.b.(T).c - _ = a. - b. - (T). - c -} - - -// Don't introduce extra newlines in strangely formatted expression lists. -func f() { - // os.Open parameters should remain on two lines - if writer, err = os.Open(outfile, s.O_WRONLY|os.O_CREATE| - os.O_TRUNC, 0666); err != nil { - log.Fatal(err) - } -} - -// Handle multi-line argument lists ending in ... correctly. -// Was issue 3130. -func _() { - _ = append(s, a...) - _ = append( - s, a...) - _ = append(s, - a...) - _ = append( - s, - a...) - _ = append(s, a..., - ) - _ = append(s, - a..., - ) - _ = append( - s, - a..., - ) -} - -// Literal function types in conversions must be parenthesized; -// for now go/parser accepts the unparenthesized form where it -// is non-ambiguous. -func _() { - // these conversions should be rewritten to look - // the same as the parenthesized conversions below - _ = func()()(nil) - _ = func(x int)(float)(nil) - _ = func() func() func()()(nil) - - _ = (func()())(nil) - _ = (func(x int)(float))(nil) - _ = (func() func() func()())(nil) -} diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/expressions.raw b/gcc-4.8.1/libgo/go/go/printer/testdata/expressions.raw deleted file mode 100644 index 062900e07..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/expressions.raw +++ /dev/null @@ -1,664 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package expressions - -type T struct { - x, y, z int -} - -var ( - a, b, c, d, e int - under_bar int - longIdentifier1, longIdentifier2, longIdentifier3 int - t0, t1, t2 T - s string - p *int -) - -func _() { - // no spaces around simple or parenthesized expressions - _ = (a + 0) - _ = a + b - _ = a + b + c - _ = a + b - c - _ = a - b - c - _ = a + (b * c) - _ = a + (b / c) - _ = a - (b % c) - _ = 1 + a - _ = a + 1 - _ = a + b + 1 - _ = s[a] - _ = s[a:] - _ = s[:b] - _ = s[1:2] - _ = s[a:b] - _ = s[0:len(s)] - _ = s[0] << 1 - _ = (s[0] << 1) & 0xf - _ = s[0]<<2 | s[1]>>4 - _ = "foo" + s - _ = s + "foo" - _ = 'a' + 'b' - _ = len(s) / 2 - _ = len(t0.x) / a - - // spaces around expressions of different precedence or expressions containing spaces - _ = a + -b - _ = a - ^b - _ = a / *p - _ = a + b*c - _ = 1 + b*c - _ = a + 2*c - _ = a + c*2 - _ = 1 + 2*3 - _ = s[1 : 2*3] - _ = s[a : b-c] - _ = s[0:] - _ = s[a+b] - _ = s[:b-c] - _ = s[a+b:] - _ = a[a<<b+1] - _ = a[a<<b+1:] - _ = s[a+b : len(s)] - _ = s[len(s):-a] - _ = s[a : len(s)+1] - _ = s[a:len(s)+1] + s - - // spaces around operators with equal or lower precedence than comparisons - _ = a == b - _ = a != b - _ = a > b - _ = a >= b - _ = a < b - _ = a <= b - _ = a < b && c > d - _ = a < b || c > d - - // spaces around "long" operands - _ = a + longIdentifier1 - _ = longIdentifier1 + a - _ = longIdentifier1 + longIdentifier2*longIdentifier3 - _ = s + "a longer string" - - // some selected cases - _ = a + t0.x - _ = a + t0.x + t1.x*t2.x - _ = a + b + c + d + e + 2*3 - _ = a + b + c + 2*3 + d + e - _ = (a + b + c) * 2 - _ = a - b + c - d + (a + b + c) + d&e - _ = under_bar - 1 - _ = Open(dpath+"/file", O_WRONLY|O_CREAT, 0666) - _ = int(c0&_Mask4)<<18 | int(c1&_Maskx)<<12 | int(c2&_Maskx)<<6 | int(c3&_Maskx) - - // the parser does not restrict expressions that may appear as statements - true - 42 - "foo" - x - (x) - a + b - a + b + c - a + (b * c) - a + (b / c) - 1 + a - a + 1 - s[a] - x << 1 - (s[0] << 1) & 0xf - "foo" + s - x == y - x < y || z > 42 -} - -func _() { - _ = a + b - _ = a + b + c - _ = a + b*c - _ = a + (b * c) - _ = (a + b) * c - _ = a + (b * c * d) - _ = a + (b*c + d) - - _ = 1 << x - _ = -1 << x - _ = 1<<x - 1 - _ = -1<<x - 1 - - _ = f(a + b) - _ = f(a + b + c) - _ = f(a + b*c) - _ = f(a + (b * c)) - _ = f(1<<x-1, 1<<x-2) - - _ = 1<<d.logWindowSize - 1 - - buf = make(x, 2*cap(b.buf)+n) - - dst[i*3+2] = dbuf[0] << 2 - dst[i*3+2] = dbuf[0]<<2 | dbuf[1]>>4 - - b.buf = b.buf[0 : b.off+m+n] - b.buf = b.buf[0 : b.off+m*n] - f(b.buf[0 : b.off+m+n]) - - signed += ' ' * 8 - tw.octal(header[148:155], chksum) - - _ = x > 0 && i >= 0 - - x1, x0 := x>>w2, x&m2 - z0 = t1<<w2 + t0 - z1 = (t1 + t0>>w2) >> w2 - q1, r1 := x1/d1, x1%d1 - r1 = r1*b2 | x0>>w2 - x1 = (x1 << z) | (x0 >> (uint(w) - z)) - x1 = x1<<z | x0>>(uint(w)-z) - - _ = buf[0 : len(buf)+1] - _ = buf[0 : n+1] - - a, b = b, a - a = b + c - a = b*c + d - _ = a*b + c - _ = a - b - c - _ = a - (b - c) - _ = a - b*c - _ = a - (b * c) - _ = a * b / c - _ = a / *b - _ = x[a|^b] - _ = x[a / *b] - _ = a & ^b - _ = a + +b - _ = a - -b - _ = x[a*-b] - _ = x[a + +b] - _ = x ^ y ^ z - _ = b[a>>24] ^ b[(a>>16)&0xFF] ^ b[(a>>8)&0xFF] ^ b[a&0xFF] - _ = len(longVariableName) * 2 - - _ = token(matchType + xlength<<lengthShift + xoffset) -} - -func f(x int, args ...int) { - f(0, args...) - f(1, args) - f(2, args[0]) - - // make sure syntactically legal code remains syntactically legal - f(3, 42 ...) // a blank must remain between 42 and ... - f(4, 42....) - f(5, 42....) - f(6, 42.0...) - f(7, 42.0...) - f(8, .42...) - f(9, .42...) - f(10, 42e0...) - f(11, 42e0...) - - _ = 42 .x // a blank must remain between 42 and .x - _ = 42..x - _ = 42..x - _ = 42.0.x - _ = 42.0.x - _ = .42.x - _ = .42.x - _ = 42e0.x - _ = 42e0.x - - // a blank must remain between the binary operator and the 2nd operand - _ = x / *y - _ = x < -1 - _ = x < <-1 - _ = x + +1 - _ = x - -1 - _ = x & &x - _ = x & ^x - - _ = f(x / *y, x < -1, x < <-1, x + +1, x - -1, x & &x, x & ^x) -} - -func _() { - _ = T{} - _ = struct{}{} - _ = [10]T{} - _ = [...]T{} - _ = []T{} - _ = map[int]T{} -} - -// one-line structs/interfaces in composite literals (up to a threshold) -func _() { - _ = struct{}{} - _ = struct{ x int }{0} - _ = struct{ x, y, z int }{0, 1, 2} - _ = struct{ int }{0} - _ = struct{ s struct{ int } }{struct{ int }{0}} -} - -func _() { - // do not modify literals - _ = "tab1 tab2 tab3 end" // string contains 3 tabs - _ = "tab1 tab2 tab3 end" // same string with 3 blanks - may be unaligned because editors see tabs in strings - _ = "" // this comment should be aligned with the one on the previous line - _ = `` - _ = ` -` - _ = `foo - bar` - _ = `three spaces before the end of the line starting here: -they must not be removed` -} - -func _() { - // smart handling of indentation for multi-line raw strings - var _ = `` - var _ = `foo` - var _ = `foo -bar` - - var _ = `` - var _ = `foo` - var _ = - // the next line should remain indented - `foo -bar` - - var _ = // comment - `` - var _ = // comment - `foo` - var _ = // comment - // the next line should remain indented - `foo -bar` - - var _ = /* comment */ `` - var _ = /* comment */ `foo` - var _ = /* comment */ `foo -bar` - - var _ = /* comment */ - `` - var _ = /* comment */ - `foo` - var _ = /* comment */ - // the next line should remain indented - `foo -bar` - - var board = []int( - `........... -........... -....●●●.... -....●●●.... -..●●●●●●●.. -..●●●○●●●.. -..●●●●●●●.. -....●●●.... -....●●●.... -........... -........... -`) - - var state = S{ - "foo", - // the next line should remain indented - `........... -........... -....●●●.... -....●●●.... -..●●●●●●●.. -..●●●○●●●.. -..●●●●●●●.. -....●●●.... -....●●●.... -........... -........... -`, - "bar", - } -} - -func _() { - // one-line function literals (body is on a single line) - _ = func() {} - _ = func() int { return 0 } - _ = func(x, y int) bool { m := (x + y) / 2; return m < 0 } - - // multi-line function literals (body is not on one line) - _ = func() { - } - _ = func() int { - return 0 - } - _ = func(x, y int) bool { - m := (x + y) / 2 - return x < y - } - - f(func() { - }) - f(func() int { - return 0 - }) - f(func(x, y int) bool { - m := (x + y) / 2 - return x < y - }) -} - -func _() { - _ = [][]int{ - []int{1}, - []int{1, 2}, - []int{1, 2, 3}, - } - _ = [][]int{ - {1}, - []int{1, 2}, - []int{1, 2, 3}, - } - _ = [][]int{ - {1}, - {1, 2}, - {1, 2, 3}, - } - _ = [][]int{{1}, {1, 2}, {1, 2, 3}} -} - -// various multi-line expressions -func _() { - // do not add extra indentation to multi-line string lists - _ = "foo" + "bar" - _ = "foo" + - "bar" + - "bah" - _ = []string{ - "abc" + - "def", - "foo" + - "bar", - } -} - -const _ = F1 + - `string = "%s";` + - `ptr = *;` + - `datafmt.T2 = s ["-" p "-"];` - -const _ = `datafmt "datafmt";` + - `default = "%v";` + - `array = *;` + - `datafmt.T3 = s {" " a a / ","};` - -const _ = `datafmt "datafmt";` + - `default = "%v";` + - `array = *;` + - `datafmt.T3 = s {" " a a / ","};` - -func _() { - _ = F1 + - `string = "%s";` + - `ptr = *;` + - `datafmt.T2 = s ["-" p "-"];` - - _ = - `datafmt "datafmt";` + - `default = "%v";` + - `array = *;` + - `datafmt.T3 = s {" " a a / ","};` - - _ = `datafmt "datafmt";` + - `default = "%v";` + - `array = *;` + - `datafmt.T3 = s {" " a a / ","};` -} - -func _() { - // respect source lines in multi-line expressions - _ = a + - b + - c - _ = a < b || - b < a - _ = "933262154439441526816992388562667004907159682643816214685929" + - "638952175999932299156089414639761565182862536979208272237582" + - "51185210916864000000000000000000000000" // 100! - _ = "170141183460469231731687303715884105727" // prime -} - -// Alignment after overlong lines -const ( - _ = "991" - _ = "2432902008176640000" // 20! - _ = "933262154439441526816992388562667004907159682643816214685929" + - "638952175999932299156089414639761565182862536979208272237582" + - "51185210916864000000000000000000000000" // 100! - _ = "170141183460469231731687303715884105727" // prime -) - -// Correct placement of operators and comments in multi-line expressions -func _() { - _ = a + // comment - b + // comment - c - _ = "a" + - "b" + // comment - "c" - _ = "ba0408" + "7265717569726564" // field 71, encoding 2, string "required" -} - -// Correct placement of terminating comma/closing parentheses in multi-line calls. -func _() { - f(1, - 2, - 3) - f(1, - 2, - 3, - ) - f(1, - 2, - 3) // comment - f(1, - 2, - 3, // comment - ) - f(1, - 2, - 3) // comment - f(1, - 2, - 3, // comment - ) -} - -// Align comments in multi-line lists of single-line expressions. -var txpix = [NCOL]draw.Color{ - draw.Yellow, // yellow - draw.Cyan, // cyan - draw.Green, // lime green - draw.GreyBlue, // slate - draw.Red, /* red */ - draw.GreyGreen, /* olive green */ - draw.Blue, /* blue */ - draw.Color(0xFF55AAFF), /* pink */ - draw.Color(0xFFAAFFFF), /* lavender */ - draw.Color(0xBB005DFF), /* maroon */ -} - -func same(t, u *Time) bool { - // respect source lines in multi-line expressions - return t.Year == u.Year && - t.Month == u.Month && - t.Day == u.Day && - t.Hour == u.Hour && - t.Minute == u.Minute && - t.Second == u.Second && - t.Weekday == u.Weekday && - t.ZoneOffset == u.ZoneOffset && - t.Zone == u.Zone -} - -func (p *parser) charClass() { - // respect source lines in multi-line expressions - if cc.negate && len(cc.ranges) == 2 && - cc.ranges[0] == '\n' && cc.ranges[1] == '\n' { - nl := new(_NotNl) - p.re.add(nl) - } -} - -func addState(s []state, inst instr, match []int) { - // handle comments correctly in multi-line expressions - for i := 0; i < l; i++ { - if s[i].inst.index() == index && // same instruction - s[i].match[0] < pos { // earlier match already going; leftmost wins - return s - } - } -} - -func (self *T) foo(x int) *T { return self } - -func _() { module.Func1().Func2() } - -func _() { - _ = new(T). - foo(1). - foo(2). - foo(3) - - _ = new(T). - foo(1). - foo(2). // inline comments - foo(3) - - _ = new(T).foo(1).foo(2).foo(3) - - // handle multiline argument list correctly - _ = new(T). - foo( - 1). - foo(2) - - _ = new(T).foo( - 1).foo(2) - - _ = Array[3+ - 4] - - _ = Method(1, 2, - 3) - - _ = new(T). - foo(). - bar().(*Type) - - _ = new(T). - foo(). - bar().(*Type). - baz() - - _ = new(T). - foo(). - bar()["idx"] - - _ = new(T). - foo(). - bar()["idx"]. - baz() - - _ = new(T). - foo(). - bar()[1:2] - - _ = new(T). - foo(). - bar()[1:2]. - baz() - - _ = new(T). - Field. - Array[3+ - 4]. - Table["foo"]. - Blob.(*Type). - Slices[1:4]. - Method(1, 2, - 3). - Thingy - - _ = a.b.c - _ = a. - b. - c - _ = a.b().c - _ = a. - b(). - c - _ = a.b[0].c - _ = a. - b[0]. - c - _ = a.b[0:].c - _ = a. - b[0:]. - c - _ = a.b.(T).c - _ = a. - b.(T). - c -} - -// Don't introduce extra newlines in strangely formatted expression lists. -func f() { - // os.Open parameters should remain on two lines - if writer, err = os.Open(outfile, s.O_WRONLY|os.O_CREATE| - os.O_TRUNC, 0666); err != nil { - log.Fatal(err) - } -} - -// Handle multi-line argument lists ending in ... correctly. -// Was issue 3130. -func _() { - _ = append(s, a...) - _ = append( - s, a...) - _ = append(s, - a...) - _ = append( - s, - a...) - _ = append(s, a..., - ) - _ = append(s, - a..., - ) - _ = append( - s, - a..., - ) -} - -// Literal function types in conversions must be parenthesized; -// for now go/parser accepts the unparenthesized form where it -// is non-ambiguous. -func _() { - // these conversions should be rewritten to look - // the same as the parenthesized conversions below - _ = (func())(nil) - _ = (func(x int) float)(nil) - _ = (func() func() func())(nil) - - _ = (func())(nil) - _ = (func(x int) float)(nil) - _ = (func() func() func())(nil) -} diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/linebreaks.golden b/gcc-4.8.1/libgo/go/go/printer/testdata/linebreaks.golden deleted file mode 100644 index 006cf1718..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/linebreaks.golden +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package linebreaks - -import ( - "bytes" - "fmt" - "io" - "os" - "reflect" - "strings" - "testing" -) - -type writerTestEntry struct { - header *Header - contents string -} - -type writerTest struct { - file string // filename of expected output - entries []*writerTestEntry -} - -var writerTests = []*writerTest{ - &writerTest{ - file: "testdata/writer.tar", - entries: []*writerTestEntry{ - &writerTestEntry{ - header: &Header{ - Name: "small.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 5, - Mtime: 1246508266, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - contents: "Kilts", - }, - &writerTestEntry{ - header: &Header{ - Name: "small2.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 11, - Mtime: 1245217492, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - contents: "Google.com\n", - }, - }, - }, - // The truncated test file was produced using these commands: - // dd if=/dev/zero bs=1048576 count=16384 > /tmp/16gig.txt - // tar -b 1 -c -f- /tmp/16gig.txt | dd bs=512 count=8 > writer-big.tar - &writerTest{ - file: "testdata/writer-big.tar", - entries: []*writerTestEntry{ - &writerTestEntry{ - header: &Header{ - Name: "tmp/16gig.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 16 << 30, - Mtime: 1254699560, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - // no contents - }, - }, - }, -} - -type untarTest struct { - file string - headers []*Header -} - -var untarTests = []*untarTest{ - &untarTest{ - file: "testdata/gnu.tar", - headers: []*Header{ - &Header{ - Name: "small.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 5, - Mtime: 1244428340, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - &Header{ - Name: "small2.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 11, - Mtime: 1244436044, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - }, - }, - &untarTest{ - file: "testdata/star.tar", - headers: []*Header{ - &Header{ - Name: "small.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 5, - Mtime: 1244592783, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - Atime: 1244592783, - Ctime: 1244592783, - }, - &Header{ - Name: "small2.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 11, - Mtime: 1244592783, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - Atime: 1244592783, - Ctime: 1244592783, - }, - }, - }, - &untarTest{ - file: "testdata/v7.tar", - headers: []*Header{ - &Header{ - Name: "small.txt", - Mode: 0444, - Uid: 73025, - Gid: 5000, - Size: 5, - Mtime: 1244593104, - Typeflag: '\x00', - }, - &Header{ - Name: "small2.txt", - Mode: 0444, - Uid: 73025, - Gid: 5000, - Size: 11, - Mtime: 1244593104, - Typeflag: '\x00', - }, - }, - }, -} - -var facts = map[int]string{ - 0: "1", - 1: "1", - 2: "2", - 10: "3628800", - 20: "2432902008176640000", - 100: "933262154439441526816992388562667004907159682643816214685929" + - "638952175999932299156089414639761565182862536979208272237582" + - "51185210916864000000000000000000000000", -} - -func usage() { - fmt.Fprintf(os.Stderr, - // TODO(gri): the 2nd string of this string list should not be indented - "usage: godoc package [name ...]\n"+ - " godoc -http=:6060\n") - flag.PrintDefaults() - os.Exit(2) -} - -func TestReader(t *testing.T) { -testLoop: - for i, test := range untarTests { - f, err := os.Open(test.file, os.O_RDONLY, 0444) - if err != nil { - t.Errorf("test %d: Unexpected error: %v", i, err) - continue - } - tr := NewReader(f) - for j, header := range test.headers { - hdr, err := tr.Next() - if err != nil || hdr == nil { - t.Errorf("test %d, entry %d: Didn't get entry: %v", i, j, err) - f.Close() - continue testLoop - } - if !reflect.DeepEqual(hdr, header) { - t.Errorf("test %d, entry %d: Incorrect header:\nhave %+v\nwant %+v", - i, j, *hdr, *header) - } - } - hdr, err := tr.Next() - if hdr != nil || err != nil { - t.Errorf("test %d: Unexpected entry or error: hdr=%v err=%v", i, err) - } - f.Close() - } -} - -// Respect line breaks in function calls. -func _() { - f(x) - f(x, - x) - f(x, - x, - ) - f( - x, - x) - f( - x, - x, - ) -} - -// Respect line breaks in function declarations. -func _(x T) {} -func _(x T, - y T) { -} -func _(x T, - y T, -) { -} -func _( - x T, - y T) { -} -func _( - x T, - y T, -) { -} - -// Example from issue 2597. -func ManageStatus0( - in <-chan *Status, - req <-chan Request, - stat chan<- *TargetInfo, - TargetHistorySize int) { -} - -func ManageStatus1( - in <-chan *Status, - req <-chan Request, - stat chan<- *TargetInfo, - TargetHistorySize int, -) { -} - -// There should be exactly one linebreak after this comment. diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/linebreaks.input b/gcc-4.8.1/libgo/go/go/printer/testdata/linebreaks.input deleted file mode 100644 index e782bb044..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/linebreaks.input +++ /dev/null @@ -1,271 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package linebreaks - -import ( - "bytes" - "fmt" - "io" - "os" - "reflect" - "strings" - "testing" -) - -type writerTestEntry struct { - header *Header - contents string -} - -type writerTest struct { - file string // filename of expected output - entries []*writerTestEntry -} - -var writerTests = []*writerTest{ - &writerTest{ - file: "testdata/writer.tar", - entries: []*writerTestEntry{ - &writerTestEntry{ - header: &Header{ - Name: "small.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 5, - Mtime: 1246508266, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - contents: "Kilts", - }, - &writerTestEntry{ - header: &Header{ - Name: "small2.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 11, - Mtime: 1245217492, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - contents: "Google.com\n", - }, - }, - }, - // The truncated test file was produced using these commands: - // dd if=/dev/zero bs=1048576 count=16384 > /tmp/16gig.txt - // tar -b 1 -c -f- /tmp/16gig.txt | dd bs=512 count=8 > writer-big.tar - &writerTest{ - file: "testdata/writer-big.tar", - entries: []*writerTestEntry{ - &writerTestEntry{ - header: &Header{ - Name: "tmp/16gig.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 16 << 30, - Mtime: 1254699560, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - // no contents - }, - }, - }, -} - -type untarTest struct { - file string - headers []*Header -} - -var untarTests = []*untarTest{ - &untarTest{ - file: "testdata/gnu.tar", - headers: []*Header{ - &Header{ - Name: "small.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 5, - Mtime: 1244428340, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - &Header{ - Name: "small2.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 11, - Mtime: 1244436044, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - }, - }, - &untarTest{ - file: "testdata/star.tar", - headers: []*Header{ - &Header{ - Name: "small.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 5, - Mtime: 1244592783, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - Atime: 1244592783, - Ctime: 1244592783, - }, - &Header{ - Name: "small2.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 11, - Mtime: 1244592783, - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - Atime: 1244592783, - Ctime: 1244592783, - }, - }, - }, - &untarTest{ - file: "testdata/v7.tar", - headers: []*Header{ - &Header{ - Name: "small.txt", - Mode: 0444, - Uid: 73025, - Gid: 5000, - Size: 5, - Mtime: 1244593104, - Typeflag: '\x00', - }, - &Header{ - Name: "small2.txt", - Mode: 0444, - Uid: 73025, - Gid: 5000, - Size: 11, - Mtime: 1244593104, - Typeflag: '\x00', - }, - }, - }, -} - -var facts = map[int] string { - 0: "1", - 1: "1", - 2: "2", - 10: "3628800", - 20: "2432902008176640000", - 100: "933262154439441526816992388562667004907159682643816214685929" + - "638952175999932299156089414639761565182862536979208272237582" + - "51185210916864000000000000000000000000", -} - -func usage() { - fmt.Fprintf(os.Stderr, - // TODO(gri): the 2nd string of this string list should not be indented - "usage: godoc package [name ...]\n" + - " godoc -http=:6060\n") - flag.PrintDefaults() - os.Exit(2) -} - -func TestReader(t *testing.T) { -testLoop: - for i, test := range untarTests { - f, err := os.Open(test.file, os.O_RDONLY, 0444) - if err != nil { - t.Errorf("test %d: Unexpected error: %v", i, err) - continue - } - tr := NewReader(f) - for j, header := range test.headers { - hdr, err := tr.Next() - if err != nil || hdr == nil { - t.Errorf("test %d, entry %d: Didn't get entry: %v", i, j, err) - f.Close() - continue testLoop - } - if !reflect.DeepEqual(hdr, header) { - t.Errorf("test %d, entry %d: Incorrect header:\nhave %+v\nwant %+v", - i, j, *hdr, *header) - } - } - hdr, err := tr.Next() - if hdr != nil || err != nil { - t.Errorf("test %d: Unexpected entry or error: hdr=%v err=%v", i, err) - } - f.Close() - } -} - -// Respect line breaks in function calls. -func _() { - f(x) - f(x, - x) - f(x, - x, - ) - f( - x, - x) - f( - x, - x, - ) -} - -// Respect line breaks in function declarations. -func _(x T) {} -func _(x T, - y T) {} -func _(x T, - y T, -) {} -func _( - x T, - y T) {} -func _( - x T, - y T, -) {} - -// Example from issue 2597. -func ManageStatus0( - in <-chan *Status, - req <-chan Request, - stat chan<- *TargetInfo, - TargetHistorySize int) { -} - -func ManageStatus1( - in <-chan *Status, - req <-chan Request, - stat chan<- *TargetInfo, - TargetHistorySize int, -) { -} - -// There should be exactly one linebreak after this comment. diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/parser.go b/gcc-4.8.1/libgo/go/go/printer/testdata/parser.go deleted file mode 100644 index dba8bbd43..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/parser.go +++ /dev/null @@ -1,2153 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package parser implements a parser for Go source files. Input may be -// provided in a variety of forms (see the various Parse* functions); the -// output is an abstract syntax tree (AST) representing the Go source. The -// parser is invoked through one of the Parse* functions. - -package parser - -import ( - "fmt" - "go/ast" - "go/scanner" - "go/token" -) - -// The mode parameter to the Parse* functions is a set of flags (or 0). -// They control the amount of source code parsed and other optional -// parser functionality. -// -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 - DeclarationErrors // report declaration errors -) - -// The parser structure holds the parser's internal state. -type parser struct { - file *token.File - scanner.ErrorVector - scanner scanner.Scanner - - // Tracing/debugging - mode uint // parsing mode - trace bool // == (mode & Trace != 0) - indent uint // indentation used for tracing output - - // Comments - comments []*ast.CommentGroup - leadComment *ast.CommentGroup // last lead comment - lineComment *ast.CommentGroup // last line comment - - // Next token - pos token.Pos // token position - tok token.Token // one token look-ahead - lit string // token literal - - // Non-syntactic parser control - exprLev int // < 0: in control clause, >= 0: in expression - - // Ordinary identifier scopes - pkgScope *ast.Scope // pkgScope.Outer == nil - topScope *ast.Scope // top-most scope; may be pkgScope - unresolved []*ast.Ident // unresolved identifiers - imports []*ast.ImportSpec // list of imports - - // Label scope - // (maintained by open/close LabelScope) - labelScope *ast.Scope // label scope for current function - targetStack [][]*ast.Ident // stack of unresolved labels -} - -// scannerMode returns the scanner mode bits given the parser's mode bits. -func scannerMode(mode uint) uint { - var m uint = scanner.InsertSemis - if mode&ParseComments != 0 { - m |= scanner.ScanComments - } - return m -} - -func (p *parser) init(fset *token.FileSet, filename string, src []byte, mode uint) { - p.file = fset.AddFile(filename, fset.Base(), len(src)) - p.scanner.Init(p.file, src, p, scannerMode(mode)) - - p.mode = mode - p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently) - - p.next() - - // set up the pkgScope here (as opposed to in parseFile) because - // there are other parser entry points (ParseExpr, etc.) - p.openScope() - p.pkgScope = p.topScope - - // for the same reason, set up a label scope - p.openLabelScope() -} - -// ---------------------------------------------------------------------------- -// Scoping support - -func (p *parser) openScope() { - p.topScope = ast.NewScope(p.topScope) -} - -func (p *parser) closeScope() { - p.topScope = p.topScope.Outer -} - -func (p *parser) openLabelScope() { - p.labelScope = ast.NewScope(p.labelScope) - p.targetStack = append(p.targetStack, nil) -} - -func (p *parser) closeLabelScope() { - // resolve labels - n := len(p.targetStack) - 1 - scope := p.labelScope - for _, ident := range p.targetStack[n] { - ident.Obj = scope.Lookup(ident.Name) - if ident.Obj == nil && p.mode&DeclarationErrors != 0 { - p.error(ident.Pos(), fmt.Sprintf("label %s undefined", ident.Name)) - } - } - // pop label scope - p.targetStack = p.targetStack[0:n] - p.labelScope = p.labelScope.Outer -} - -func (p *parser) declare(decl interface{}, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) { - for _, ident := range idents { - assert(ident.Obj == nil, "identifier already declared or resolved") - if ident.Name != "_" { - obj := ast.NewObj(kind, ident.Name) - // remember the corresponding declaration for redeclaration - // errors and global variable resolution/typechecking phase - obj.Decl = decl - if alt := scope.Insert(obj); alt != nil && p.mode&DeclarationErrors != 0 { - prevDecl := "" - if pos := alt.Pos(); pos.IsValid() { - prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", p.file.Position(pos)) - } - p.error(ident.Pos(), fmt.Sprintf("%s redeclared in this block%s", ident.Name, prevDecl)) - } - ident.Obj = obj - } - } -} - -func (p *parser) shortVarDecl(idents []*ast.Ident) { - // Go spec: A short variable declaration may redeclare variables - // provided they were originally declared in the same block with - // the same type, and at least one of the non-blank variables is new. - n := 0 // number of new variables - for _, ident := range idents { - assert(ident.Obj == nil, "identifier already declared or resolved") - if ident.Name != "_" { - obj := ast.NewObj(ast.Var, ident.Name) - // short var declarations cannot have redeclaration errors - // and are not global => no need to remember the respective - // declaration - alt := p.topScope.Insert(obj) - if alt == nil { - n++ // new declaration - alt = obj - } - ident.Obj = alt - } - } - if n == 0 && p.mode&DeclarationErrors != 0 { - p.error(idents[0].Pos(), "no new variables on left side of :=") - } -} - -// The unresolved object is a sentinel to mark identifiers that have been added -// to the list of unresolved identifiers. The sentinel is only used for verifying -// internal consistency. -var unresolved = new(ast.Object) - -func (p *parser) resolve(x ast.Expr) { - // nothing to do if x is not an identifier or the blank identifier - ident, _ := x.(*ast.Ident) - if ident == nil { - return - } - assert(ident.Obj == nil, "identifier already declared or resolved") - if ident.Name == "_" { - return - } - // try to resolve the identifier - for s := p.topScope; s != nil; s = s.Outer { - if obj := s.Lookup(ident.Name); obj != nil { - ident.Obj = obj - return - } - } - // all local scopes are known, so any unresolved identifier - // must be found either in the file scope, package scope - // (perhaps in another file), or universe scope --- collect - // them so that they can be resolved later - ident.Obj = unresolved - p.unresolved = append(p.unresolved, ident) -} - -// ---------------------------------------------------------------------------- -// Parsing support - -func (p *parser) printTrace(a ...interface{}) { - const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " + - ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " - const n = uint(len(dots)) - pos := p.file.Position(p.pos) - fmt.Printf("%5d:%3d: ", pos.Line, pos.Column) - i := 2 * p.indent - for ; i > n; i -= n { - fmt.Print(dots) - } - fmt.Print(dots[0:i]) - fmt.Println(a...) -} - -func trace(p *parser, msg string) *parser { - p.printTrace(msg, "(") - p.indent++ - return p -} - -// Usage pattern: defer un(trace(p, "...")); -func un(p *parser) { - p.indent-- - p.printTrace(")") -} - -// Advance to the next token. -func (p *parser) next0() { - // Because of one-token look-ahead, print the previous token - // when tracing as it provides a more readable output. The - // very first token (!p.pos.IsValid()) is not initialized - // (it is token.ILLEGAL), so don't print it . - if p.trace && p.pos.IsValid() { - s := p.tok.String() - switch { - case p.tok.IsLiteral(): - p.printTrace(s, p.lit) - case p.tok.IsOperator(), p.tok.IsKeyword(): - p.printTrace("\"" + s + "\"") - default: - p.printTrace(s) - } - } - - 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.file.Line(p.pos) - if p.lit[1] == '*' { - // don't use range here - no need to decode Unicode code points - for i := 0; i < len(p.lit); i++ { - if p.lit[i] == '\n' { - endline++ - } - } - } - - comment = &ast.Comment{p.pos, p.lit} - p.next0() - - return -} - -// Consume a group of adjacent comments, add it to the parser's -// comments list, and return it together with the line at which -// the last comment in the group ends. An empty line or non-comment -// token terminates a comment group. -// -func (p *parser) consumeCommentGroup() (comments *ast.CommentGroup, endline int) { - var list []*ast.Comment - endline = p.file.Line(p.pos) - for p.tok == token.COMMENT && endline+1 >= p.file.Line(p.pos) { - var comment *ast.Comment - comment, endline = p.consumeComment() - list = append(list, comment) - } - - // add comment group to the comments list - comments = &ast.CommentGroup{list} - p.comments = append(p.comments, comments) - - return -} - -// Advance to the next non-comment token. In the process, collect -// any comment groups encountered, and remember the last lead and -// and line comments. -// -// A lead comment is a comment group that starts and ends in a -// line without any other tokens and that is followed by a non-comment -// token on the line immediately after the comment group. -// -// A line comment is a comment group that follows a non-comment -// token on the same line, and that has no tokens after it on the line -// where it ends. -// -// Lead and line comments may be considered documentation that is -// stored in the AST. -// -func (p *parser) next() { - p.leadComment = nil - p.lineComment = nil - line := p.file.Line(p.pos) // current line - p.next0() - - if p.tok == token.COMMENT { - var comment *ast.CommentGroup - var endline int - - if p.file.Line(p.pos) == line { - // The comment is on same line as the previous token; it - // cannot be a lead comment but may be a line comment. - comment, endline = p.consumeCommentGroup() - if p.file.Line(p.pos) != endline { - // The next token is on a different line, thus - // the last comment group is a line comment. - p.lineComment = comment - } - } - - // consume successor comments, if any - endline = -1 - for p.tok == token.COMMENT { - comment, endline = p.consumeCommentGroup() - } - - if endline+1 == p.file.Line(p.pos) { - // The next token is following on the line immediately after the - // comment group, thus the last comment group is a lead comment. - p.leadComment = comment - } - } -} - -func (p *parser) error(pos token.Pos, msg string) { - p.Error(p.file.Position(pos), msg) -} - -func (p *parser) errorExpected(pos token.Pos, msg string) { - msg = "expected " + msg - if pos == p.pos { - // the error happened at the current position; - // make the error message more specific - if p.tok == token.SEMICOLON && p.lit[0] == '\n' { - msg += ", found newline" - } else { - msg += ", found '" + p.tok.String() + "'" - if p.tok.IsLiteral() { - msg += " " + p.lit - } - } - } - p.error(pos, msg) -} - -func (p *parser) expect(tok token.Token) token.Pos { - pos := p.pos - if p.tok != tok { - p.errorExpected(pos, "'"+tok.String()+"'") - } - p.next() // make progress - return pos -} - -func (p *parser) expectSemi() { - if p.tok != token.RPAREN && p.tok != token.RBRACE { - p.expect(token.SEMICOLON) - } -} - -func assert(cond bool, msg string) { - if !cond { - panic("go/parser internal error: " + msg) - } -} - -// ---------------------------------------------------------------------------- -// Identifiers - -func (p *parser) parseIdent() *ast.Ident { - pos := p.pos - name := "_" - if p.tok == token.IDENT { - name = p.lit - p.next() - } else { - p.expect(token.IDENT) // use expect() error handling - } - return &ast.Ident{pos, name, nil} -} - -func (p *parser) parseIdentList() (list []*ast.Ident) { - if p.trace { - defer un(trace(p, "IdentList")) - } - - list = append(list, p.parseIdent()) - for p.tok == token.COMMA { - p.next() - list = append(list, p.parseIdent()) - } - - return -} - -// ---------------------------------------------------------------------------- -// Common productions - -// If lhs is set, result list elements which are identifiers are not resolved. -func (p *parser) parseExprList(lhs bool) (list []ast.Expr) { - if p.trace { - defer un(trace(p, "ExpressionList")) - } - - list = append(list, p.parseExpr(lhs)) - for p.tok == token.COMMA { - p.next() - list = append(list, p.parseExpr(lhs)) - } - - return -} - -func (p *parser) parseLhsList() []ast.Expr { - list := p.parseExprList(true) - switch p.tok { - case token.DEFINE: - // lhs of a short variable declaration - p.shortVarDecl(p.makeIdentList(list)) - case token.COLON: - // lhs of a label declaration or a communication clause of a select - // statement (parseLhsList is not called when parsing the case clause - // of a switch statement): - // - labels are declared by the caller of parseLhsList - // - for communication clauses, if there is a stand-alone identifier - // followed by a colon, we have a syntax error; there is no need - // to resolve the identifier in that case - default: - // identifiers must be declared elsewhere - for _, x := range list { - p.resolve(x) - } - } - return list -} - -func (p *parser) parseRhsList() []ast.Expr { - return p.parseExprList(false) -} - -// ---------------------------------------------------------------------------- -// Types - -func (p *parser) parseType() ast.Expr { - if p.trace { - defer un(trace(p, "Type")) - } - - typ := p.tryType() - - if typ == nil { - pos := p.pos - p.errorExpected(pos, "type") - p.next() // make progress - return &ast.BadExpr{pos, p.pos} - } - - return typ -} - -// If the result is an identifier, it is not resolved. -func (p *parser) parseTypeName() ast.Expr { - if p.trace { - defer un(trace(p, "TypeName")) - } - - ident := p.parseIdent() - // don't resolve ident yet - it may be a parameter or field name - - if p.tok == token.PERIOD { - // ident is a package name - p.next() - p.resolve(ident) - sel := p.parseIdent() - return &ast.SelectorExpr{ident, sel} - } - - return ident -} - -func (p *parser) parseArrayType(ellipsisOk bool) ast.Expr { - if p.trace { - defer un(trace(p, "ArrayType")) - } - - lbrack := p.expect(token.LBRACK) - var len ast.Expr - if ellipsisOk && p.tok == token.ELLIPSIS { - len = &ast.Ellipsis{p.pos, nil} - p.next() - } else if p.tok != token.RBRACK { - len = p.parseRhs() - } - p.expect(token.RBRACK) - elt := p.parseType() - - return &ast.ArrayType{lbrack, len, elt} -} - -func (p *parser) makeIdentList(list []ast.Expr) []*ast.Ident { - idents := make([]*ast.Ident, len(list)) - for i, x := range list { - ident, isIdent := x.(*ast.Ident) - if !isIdent { - pos := x.(ast.Expr).Pos() - p.errorExpected(pos, "identifier") - ident = &ast.Ident{pos, "_", nil} - } - idents[i] = ident - } - return idents -} - -func (p *parser) parseFieldDecl(scope *ast.Scope) *ast.Field { - if p.trace { - defer un(trace(p, "FieldDecl")) - } - - doc := p.leadComment - - // fields - list, typ := p.parseVarList(false) - - // optional tag - var tag *ast.BasicLit - if p.tok == token.STRING { - tag = &ast.BasicLit{p.pos, p.tok, p.lit} - p.next() - } - - // analyze case - var idents []*ast.Ident - if typ != nil { - // IdentifierList Type - idents = p.makeIdentList(list) - } else { - // ["*"] TypeName (AnonymousField) - typ = list[0] // we always have at least one element - p.resolve(typ) - if n := len(list); n > 1 || !isTypeName(deref(typ)) { - pos := typ.Pos() - p.errorExpected(pos, "anonymous field") - typ = &ast.BadExpr{pos, list[n-1].End()} - } - } - - p.expectSemi() // call before accessing p.linecomment - - field := &ast.Field{doc, idents, typ, tag, p.lineComment} - p.declare(field, scope, ast.Var, idents...) - - return field -} - -func (p *parser) parseStructType() *ast.StructType { - if p.trace { - defer un(trace(p, "StructType")) - } - - pos := p.expect(token.STRUCT) - lbrace := p.expect(token.LBRACE) - scope := ast.NewScope(nil) // struct scope - var list []*ast.Field - for p.tok == token.IDENT || p.tok == token.MUL || p.tok == token.LPAREN { - // a field declaration cannot start with a '(' but we accept - // it here for more robust parsing and better error messages - // (parseFieldDecl will check and complain if necessary) - list = append(list, p.parseFieldDecl(scope)) - } - rbrace := p.expect(token.RBRACE) - - // TODO(gri): store struct scope in AST - return &ast.StructType{pos, &ast.FieldList{lbrace, list, rbrace}, false} -} - -func (p *parser) parsePointerType() *ast.StarExpr { - if p.trace { - defer un(trace(p, "PointerType")) - } - - star := p.expect(token.MUL) - base := p.parseType() - - return &ast.StarExpr{star, base} -} - -func (p *parser) tryVarType(isParam bool) ast.Expr { - if isParam && p.tok == token.ELLIPSIS { - pos := p.pos - p.next() - typ := p.tryIdentOrType(isParam) // don't use parseType so we can provide better error message - if typ == nil { - p.error(pos, "'...' parameter is missing type") - typ = &ast.BadExpr{pos, p.pos} - } - if p.tok != token.RPAREN { - p.error(pos, "can use '...' with last parameter type only") - } - return &ast.Ellipsis{pos, typ} - } - return p.tryIdentOrType(false) -} - -func (p *parser) parseVarType(isParam bool) ast.Expr { - typ := p.tryVarType(isParam) - if typ == nil { - pos := p.pos - p.errorExpected(pos, "type") - p.next() // make progress - typ = &ast.BadExpr{pos, p.pos} - } - return typ -} - -func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) { - if p.trace { - defer un(trace(p, "VarList")) - } - - // a list of identifiers looks like a list of type names - for { - // parseVarType accepts any type (including parenthesized ones) - // even though the syntax does not permit them here: we - // accept them all for more robust parsing and complain - // afterwards - list = append(list, p.parseVarType(isParam)) - if p.tok != token.COMMA { - break - } - p.next() - } - - // if we had a list of identifiers, it must be followed by a type - typ = p.tryVarType(isParam) - if typ != nil { - p.resolve(typ) - } - - return -} - -func (p *parser) parseParameterList(scope *ast.Scope, ellipsisOk bool) (params []*ast.Field) { - if p.trace { - defer un(trace(p, "ParameterList")) - } - - list, typ := p.parseVarList(ellipsisOk) - if typ != nil { - // IdentifierList Type - idents := p.makeIdentList(list) - field := &ast.Field{nil, idents, typ, nil, nil} - params = append(params, field) - // Go spec: The scope of an identifier denoting a function - // parameter or result variable is the function body. - p.declare(field, scope, ast.Var, idents...) - if p.tok == token.COMMA { - p.next() - } - - for p.tok != token.RPAREN && p.tok != token.EOF { - idents := p.parseIdentList() - typ := p.parseVarType(ellipsisOk) - field := &ast.Field{nil, idents, typ, nil, nil} - params = append(params, field) - // Go spec: The scope of an identifier denoting a function - // parameter or result variable is the function body. - p.declare(field, scope, ast.Var, idents...) - if p.tok != token.COMMA { - break - } - p.next() - } - - } else { - // Type { "," Type } (anonymous parameters) - params = make([]*ast.Field, len(list)) - for i, x := range list { - p.resolve(x) - params[i] = &ast.Field{Type: x} - } - } - - return -} - -func (p *parser) parseParameters(scope *ast.Scope, ellipsisOk bool) *ast.FieldList { - if p.trace { - defer un(trace(p, "Parameters")) - } - - var params []*ast.Field - lparen := p.expect(token.LPAREN) - if p.tok != token.RPAREN { - params = p.parseParameterList(scope, ellipsisOk) - } - rparen := p.expect(token.RPAREN) - - return &ast.FieldList{lparen, params, rparen} -} - -func (p *parser) parseResult(scope *ast.Scope) *ast.FieldList { - if p.trace { - defer un(trace(p, "Result")) - } - - if p.tok == token.LPAREN { - return p.parseParameters(scope, false) - } - - typ := p.tryType() - if typ != nil { - list := make([]*ast.Field, 1) - list[0] = &ast.Field{Type: typ} - return &ast.FieldList{List: list} - } - - return nil -} - -func (p *parser) parseSignature(scope *ast.Scope) (params, results *ast.FieldList) { - if p.trace { - defer un(trace(p, "Signature")) - } - - params = p.parseParameters(scope, true) - results = p.parseResult(scope) - - return -} - -func (p *parser) parseFuncType() (*ast.FuncType, *ast.Scope) { - if p.trace { - defer un(trace(p, "FuncType")) - } - - pos := p.expect(token.FUNC) - scope := ast.NewScope(p.topScope) // function scope - params, results := p.parseSignature(scope) - - return &ast.FuncType{pos, params, results}, scope -} - -func (p *parser) parseMethodSpec(scope *ast.Scope) *ast.Field { - if p.trace { - defer un(trace(p, "MethodSpec")) - } - - doc := p.leadComment - var idents []*ast.Ident - var typ ast.Expr - x := p.parseTypeName() - if ident, isIdent := x.(*ast.Ident); isIdent && p.tok == token.LPAREN { - // method - idents = []*ast.Ident{ident} - scope := ast.NewScope(nil) // method scope - params, results := p.parseSignature(scope) - typ = &ast.FuncType{token.NoPos, params, results} - } else { - // embedded interface - typ = x - } - p.expectSemi() // call before accessing p.linecomment - - spec := &ast.Field{doc, idents, typ, nil, p.lineComment} - p.declare(spec, scope, ast.Fun, idents...) - - return spec -} - -func (p *parser) parseInterfaceType() *ast.InterfaceType { - if p.trace { - defer un(trace(p, "InterfaceType")) - } - - pos := p.expect(token.INTERFACE) - lbrace := p.expect(token.LBRACE) - scope := ast.NewScope(nil) // interface scope - var list []*ast.Field - for p.tok == token.IDENT { - list = append(list, p.parseMethodSpec(scope)) - } - rbrace := p.expect(token.RBRACE) - - // TODO(gri): store interface scope in AST - return &ast.InterfaceType{pos, &ast.FieldList{lbrace, list, rbrace}, false} -} - -func (p *parser) parseMapType() *ast.MapType { - if p.trace { - defer un(trace(p, "MapType")) - } - - 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} -} - -func (p *parser) parseChanType() *ast.ChanType { - if p.trace { - defer un(trace(p, "ChanType")) - } - - pos := p.pos - dir := ast.SEND | ast.RECV - if p.tok == token.CHAN { - p.next() - if p.tok == token.ARROW { - p.next() - dir = ast.SEND - } - } else { - p.expect(token.ARROW) - p.expect(token.CHAN) - dir = ast.RECV - } - value := p.parseType() - - return &ast.ChanType{pos, dir, value} -} - -// If the result is an identifier, it is not resolved. -func (p *parser) tryIdentOrType(ellipsisOk bool) ast.Expr { - switch p.tok { - case token.IDENT: - return p.parseTypeName() - case token.LBRACK: - return p.parseArrayType(ellipsisOk) - case token.STRUCT: - return p.parseStructType() - case token.MUL: - return p.parsePointerType() - case token.FUNC: - typ, _ := p.parseFuncType() - return typ - case token.INTERFACE: - return p.parseInterfaceType() - case token.MAP: - return p.parseMapType() - 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} - } - - // no type found - return nil -} - -func (p *parser) tryType() ast.Expr { - typ := p.tryIdentOrType(false) - if typ != nil { - p.resolve(typ) - } - return typ -} - -// ---------------------------------------------------------------------------- -// Blocks - -func (p *parser) parseStmtList() (list []ast.Stmt) { - if p.trace { - defer un(trace(p, "StatementList")) - } - - for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF { - list = append(list, p.parseStmt()) - } - - return -} - -func (p *parser) parseBody(scope *ast.Scope) *ast.BlockStmt { - if p.trace { - defer un(trace(p, "Body")) - } - - lbrace := p.expect(token.LBRACE) - p.topScope = scope // open function scope - p.openLabelScope() - list := p.parseStmtList() - p.closeLabelScope() - p.closeScope() - rbrace := p.expect(token.RBRACE) - - return &ast.BlockStmt{lbrace, list, rbrace} -} - -func (p *parser) parseBlockStmt() *ast.BlockStmt { - if p.trace { - defer un(trace(p, "BlockStmt")) - } - - lbrace := p.expect(token.LBRACE) - p.openScope() - list := p.parseStmtList() - p.closeScope() - rbrace := p.expect(token.RBRACE) - - return &ast.BlockStmt{lbrace, list, rbrace} -} - -// ---------------------------------------------------------------------------- -// Expressions - -func (p *parser) parseFuncTypeOrLit() ast.Expr { - if p.trace { - defer un(trace(p, "FuncTypeOrLit")) - } - - typ, scope := p.parseFuncType() - if p.tok != token.LBRACE { - // function type only - return typ - } - - p.exprLev++ - body := p.parseBody(scope) - p.exprLev-- - - return &ast.FuncLit{typ, body} -} - -// parseOperand may return an expression or a raw type (incl. array -// types of the form [...]T. Callers must verify the result. -// If lhs is set and the result is an identifier, it is not resolved. -// -func (p *parser) parseOperand(lhs bool) ast.Expr { - if p.trace { - defer un(trace(p, "Operand")) - } - - switch p.tok { - case token.IDENT: - x := p.parseIdent() - if !lhs { - p.resolve(x) - } - return x - - case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING: - 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.parseRhs() - p.exprLev-- - rparen := p.expect(token.RPAREN) - return &ast.ParenExpr{lparen, x, rparen} - - case token.FUNC: - return p.parseFuncTypeOrLit() - - default: - if typ := p.tryIdentOrType(true); typ != nil { - // could be type for composite literal or conversion - _, isIdent := typ.(*ast.Ident) - assert(!isIdent, "type cannot be identifier") - return typ - } - } - - pos := p.pos - p.errorExpected(pos, "operand") - p.next() // make progress - return &ast.BadExpr{pos, p.pos} -} - -func (p *parser) parseSelector(x ast.Expr) ast.Expr { - if p.trace { - defer un(trace(p, "Selector")) - } - - sel := p.parseIdent() - - return &ast.SelectorExpr{x, sel} -} - -func (p *parser) parseTypeAssertion(x ast.Expr) ast.Expr { - if p.trace { - defer un(trace(p, "TypeAssertion")) - } - - 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) - - return &ast.TypeAssertExpr{x, typ} -} - -func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr { - if p.trace { - defer un(trace(p, "IndexOrSlice")) - } - - lbrack := p.expect(token.LBRACK) - p.exprLev++ - var low, high ast.Expr - isSlice := false - if p.tok != token.COLON { - low = p.parseRhs() - } - if p.tok == token.COLON { - isSlice = true - p.next() - if p.tok != token.RBRACK { - high = p.parseRhs() - } - } - p.exprLev-- - rbrack := p.expect(token.RBRACK) - - if isSlice { - return &ast.SliceExpr{x, lbrack, low, high, rbrack} - } - return &ast.IndexExpr{x, lbrack, low, rbrack} -} - -func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr { - if p.trace { - defer un(trace(p, "CallOrConversion")) - } - - lparen := p.expect(token.LPAREN) - p.exprLev++ - var list []ast.Expr - var ellipsis token.Pos - for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() { - list = append(list, p.parseRhs()) - if p.tok == token.ELLIPSIS { - ellipsis = p.pos - p.next() - } - if p.tok != token.COMMA { - break - } - p.next() - } - p.exprLev-- - rparen := p.expect(token.RPAREN) - - return &ast.CallExpr{fun, lparen, list, ellipsis, rparen} -} - -func (p *parser) parseElement(keyOk bool) ast.Expr { - if p.trace { - defer un(trace(p, "Element")) - } - - if p.tok == token.LBRACE { - return p.parseLiteralValue(nil) - } - - x := p.parseExpr(keyOk) // don't resolve if map key - if keyOk { - if p.tok == token.COLON { - colon := p.pos - p.next() - return &ast.KeyValueExpr{x, colon, p.parseElement(false)} - } - p.resolve(x) // not a map key - } - - return x -} - -func (p *parser) parseElementList() (list []ast.Expr) { - if p.trace { - defer un(trace(p, "ElementList")) - } - - for p.tok != token.RBRACE && p.tok != token.EOF { - list = append(list, p.parseElement(true)) - if p.tok != token.COMMA { - break - } - p.next() - } - - return -} - -func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr { - if p.trace { - defer un(trace(p, "LiteralValue")) - } - - lbrace := p.expect(token.LBRACE) - var elts []ast.Expr - p.exprLev++ - if p.tok != token.RBRACE { - elts = p.parseElementList() - } - p.exprLev-- - rbrace := p.expect(token.RBRACE) - return &ast.CompositeLit{typ, lbrace, elts, rbrace} -} - -// checkExpr checks that x is an expression (and not a type). -func (p *parser) checkExpr(x ast.Expr) ast.Expr { - switch t := unparen(x).(type) { - case *ast.BadExpr: - case *ast.Ident: - case *ast.BasicLit: - case *ast.FuncLit: - case *ast.CompositeLit: - case *ast.ParenExpr: - panic("unreachable") - case *ast.SelectorExpr: - case *ast.IndexExpr: - case *ast.SliceExpr: - 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(), x.End()} - } - 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(), x.End()} - } - case *ast.BinaryExpr: - default: - // all other nodes are not proper expressions - p.errorExpected(x.Pos(), "expression") - x = &ast.BadExpr{x.Pos(), x.End()} - } - return x -} - -// isTypeName returns true iff x is a (qualified) TypeName. -func isTypeName(x ast.Expr) bool { - switch t := x.(type) { - case *ast.BadExpr: - case *ast.Ident: - case *ast.SelectorExpr: - _, isIdent := t.X.(*ast.Ident) - return isIdent - default: - return false // all other nodes are not type names - } - return true -} - -// isLiteralType returns true iff x is a legal composite literal type. -func isLiteralType(x ast.Expr) bool { - switch t := x.(type) { - case *ast.BadExpr: - case *ast.Ident: - case *ast.SelectorExpr: - _, isIdent := t.X.(*ast.Ident) - return isIdent - case *ast.ArrayType: - case *ast.StructType: - case *ast.MapType: - default: - return false // all other nodes are not legal composite literal types - } - return true -} - -// If x is of the form *T, deref returns T, otherwise it returns x. -func deref(x ast.Expr) ast.Expr { - if p, isPtr := x.(*ast.StarExpr); isPtr { - x = p.X - } - return x -} - -// If x is of the form (T), unparen returns unparen(T), otherwise it returns x. -func unparen(x ast.Expr) ast.Expr { - if p, isParen := x.(*ast.ParenExpr); isParen { - x = unparen(p.X) - } - return x -} - -// checkExprOrType checks that x is an expression or a type -// (and not a raw type such as [...]T). -// -func (p *parser) checkExprOrType(x ast.Expr) ast.Expr { - switch t := unparen(x).(type) { - case *ast.ParenExpr: - panic("unreachable") - 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(), x.End()} - } - case *ast.ArrayType: - if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis { - p.error(len.Pos(), "expected array length, found '...'") - x = &ast.BadExpr{x.Pos(), x.End()} - } - } - - // all other nodes are expressions or types - return x -} - -// If lhs is set and the result is an identifier, it is not resolved. -func (p *parser) parsePrimaryExpr(lhs bool) ast.Expr { - if p.trace { - defer un(trace(p, "PrimaryExpr")) - } - - x := p.parseOperand(lhs) -L: - for { - switch p.tok { - case token.PERIOD: - p.next() - if lhs { - p.resolve(x) - } - switch p.tok { - case token.IDENT: - x = p.parseSelector(p.checkExpr(x)) - case token.LPAREN: - x = p.parseTypeAssertion(p.checkExpr(x)) - default: - pos := p.pos - p.next() // make progress - p.errorExpected(pos, "selector or type assertion") - x = &ast.BadExpr{pos, p.pos} - } - case token.LBRACK: - if lhs { - p.resolve(x) - } - x = p.parseIndexOrSlice(p.checkExpr(x)) - case token.LPAREN: - if lhs { - p.resolve(x) - } - x = p.parseCallOrConversion(p.checkExprOrType(x)) - case token.LBRACE: - if isLiteralType(x) && (p.exprLev >= 0 || !isTypeName(x)) { - if lhs { - p.resolve(x) - } - x = p.parseLiteralValue(x) - } else { - break L - } - default: - break L - } - lhs = false // no need to try to resolve again - } - - return x -} - -// If lhs is set and the result is an identifier, it is not resolved. -func (p *parser) parseUnaryExpr(lhs bool) ast.Expr { - if p.trace { - defer un(trace(p, "UnaryExpr")) - } - - switch p.tok { - case token.ADD, token.SUB, token.NOT, token.XOR, token.AND, token.RANGE: - pos, op := p.pos, p.tok - p.next() - x := p.parseUnaryExpr(false) - return &ast.UnaryExpr{pos, op, p.checkExpr(x)} - - case token.ARROW: - // channel type or receive expression - pos := p.pos - p.next() - if p.tok == token.CHAN { - p.next() - value := p.parseType() - return &ast.ChanType{pos, ast.RECV, value} - } - - x := p.parseUnaryExpr(false) - return &ast.UnaryExpr{pos, token.ARROW, p.checkExpr(x)} - - case token.MUL: - // pointer type or unary "*" expression - pos := p.pos - p.next() - x := p.parseUnaryExpr(false) - return &ast.StarExpr{pos, p.checkExprOrType(x)} - } - - return p.parsePrimaryExpr(lhs) -} - -// If lhs is set and the result is an identifier, it is not resolved. -func (p *parser) parseBinaryExpr(lhs bool, prec1 int) ast.Expr { - if p.trace { - defer un(trace(p, "BinaryExpr")) - } - - x := p.parseUnaryExpr(lhs) - for prec := p.tok.Precedence(); prec >= prec1; prec-- { - for p.tok.Precedence() == prec { - pos, op := p.pos, p.tok - p.next() - if lhs { - p.resolve(x) - lhs = false - } - y := p.parseBinaryExpr(false, prec+1) - x = &ast.BinaryExpr{p.checkExpr(x), pos, op, p.checkExpr(y)} - } - } - - return x -} - -// If lhs is set and the result is an identifier, it is not resolved. -// TODO(gri): parseExpr may return a type or even a raw type ([..]int) - -// should reject when a type/raw type is obviously not allowed -func (p *parser) parseExpr(lhs bool) ast.Expr { - if p.trace { - defer un(trace(p, "Expression")) - } - - return p.parseBinaryExpr(lhs, token.LowestPrec+1) -} - -func (p *parser) parseRhs() ast.Expr { - return p.parseExpr(false) -} - -// ---------------------------------------------------------------------------- -// Statements - -func (p *parser) parseSimpleStmt(labelOk bool) ast.Stmt { - if p.trace { - defer un(trace(p, "SimpleStmt")) - } - - x := p.parseLhsList() - - switch p.tok { - case - token.DEFINE, token.ASSIGN, token.ADD_ASSIGN, - token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN, - 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.parseRhsList() - return &ast.AssignStmt{x, pos, tok, y} - } - - if len(x) > 1 { - p.errorExpected(x[0].Pos(), "1 expression") - // continue with first expression - } - - switch p.tok { - case token.COLON: - // labeled statement - colon := p.pos - p.next() - if label, isIdent := x[0].(*ast.Ident); labelOk && isIdent { - // Go spec: The scope of a label is the body of the function - // in which it is declared and excludes the body of any nested - // function. - stmt := &ast.LabeledStmt{label, colon, p.parseStmt()} - p.declare(stmt, p.labelScope, ast.Lbl, label) - return stmt - } - p.error(x[0].Pos(), "illegal label declaration") - return &ast.BadStmt{x[0].Pos(), colon + 1} - - case token.ARROW: - // send statement - arrow := p.pos - p.next() // consume "<-" - y := p.parseRhs() - return &ast.SendStmt{x[0], arrow, y} - - case token.INC, token.DEC: - // increment or decrement - s := &ast.IncDecStmt{x[0], p.pos, p.tok} - p.next() // consume "++" or "--" - return s - } - - // expression - return &ast.ExprStmt{x[0]} -} - -func (p *parser) parseCallExpr() *ast.CallExpr { - x := p.parseRhs() - if call, isCall := x.(*ast.CallExpr); isCall { - return call - } - p.errorExpected(x.Pos(), "function/method call") - return nil -} - -func (p *parser) parseGoStmt() ast.Stmt { - if p.trace { - defer un(trace(p, "GoStmt")) - } - - pos := p.expect(token.GO) - call := p.parseCallExpr() - p.expectSemi() - if call == nil { - return &ast.BadStmt{pos, pos + 2} // len("go") - } - - return &ast.GoStmt{pos, call} -} - -func (p *parser) parseDeferStmt() ast.Stmt { - if p.trace { - defer un(trace(p, "DeferStmt")) - } - - pos := p.expect(token.DEFER) - call := p.parseCallExpr() - p.expectSemi() - if call == nil { - return &ast.BadStmt{pos, pos + 5} // len("defer") - } - - return &ast.DeferStmt{pos, call} -} - -func (p *parser) parseReturnStmt() *ast.ReturnStmt { - if p.trace { - defer un(trace(p, "ReturnStmt")) - } - - pos := p.pos - p.expect(token.RETURN) - var x []ast.Expr - if p.tok != token.SEMICOLON && p.tok != token.RBRACE { - x = p.parseRhsList() - } - p.expectSemi() - - return &ast.ReturnStmt{pos, x} -} - -func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt { - if p.trace { - defer un(trace(p, "BranchStmt")) - } - - pos := p.expect(tok) - var label *ast.Ident - if tok != token.FALLTHROUGH && p.tok == token.IDENT { - label = p.parseIdent() - // add to list of unresolved targets - n := len(p.targetStack) - 1 - p.targetStack[n] = append(p.targetStack[n], label) - } - p.expectSemi() - - return &ast.BranchStmt{pos, tok, label} -} - -func (p *parser) makeExpr(s ast.Stmt) ast.Expr { - if s == nil { - return nil - } - 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(), s.End()} -} - -func (p *parser) parseIfStmt() *ast.IfStmt { - if p.trace { - defer un(trace(p, "IfStmt")) - } - - pos := p.expect(token.IF) - p.openScope() - defer p.closeScope() - - var s ast.Stmt - var x ast.Expr - { - prevLev := p.exprLev - p.exprLev = -1 - if p.tok == token.SEMICOLON { - p.next() - x = p.parseRhs() - } else { - s = p.parseSimpleStmt(false) - if p.tok == token.SEMICOLON { - p.next() - x = p.parseRhs() - } else { - x = p.makeExpr(s) - s = nil - } - } - p.exprLev = prevLev - } - - body := p.parseBlockStmt() - var else_ ast.Stmt - if p.tok == token.ELSE { - p.next() - else_ = p.parseStmt() - } else { - p.expectSemi() - } - - return &ast.IfStmt{pos, s, x, body, else_} -} - -func (p *parser) parseTypeList() (list []ast.Expr) { - if p.trace { - defer un(trace(p, "TypeList")) - } - - list = append(list, p.parseType()) - for p.tok == token.COMMA { - p.next() - list = append(list, p.parseType()) - } - - return -} - -func (p *parser) parseCaseClause(exprSwitch bool) *ast.CaseClause { - if p.trace { - defer un(trace(p, "CaseClause")) - } - - pos := p.pos - var list []ast.Expr - if p.tok == token.CASE { - p.next() - if exprSwitch { - list = p.parseRhsList() - } else { - list = p.parseTypeList() - } - } else { - p.expect(token.DEFAULT) - } - - colon := p.expect(token.COLON) - p.openScope() - body := p.parseStmtList() - p.closeScope() - - return &ast.CaseClause{pos, list, colon, body} -} - -func isExprSwitch(s ast.Stmt) bool { - if s == nil { - return true - } - if e, ok := s.(*ast.ExprStmt); ok { - if a, ok := e.X.(*ast.TypeAssertExpr); ok { - return a.Type != nil // regular type assertion - } - return true - } - return false -} - -func (p *parser) parseSwitchStmt() ast.Stmt { - if p.trace { - defer un(trace(p, "SwitchStmt")) - } - - pos := p.expect(token.SWITCH) - p.openScope() - defer p.closeScope() - - var s1, s2 ast.Stmt - if p.tok != token.LBRACE { - prevLev := p.exprLev - p.exprLev = -1 - if p.tok != token.SEMICOLON { - s2 = p.parseSimpleStmt(false) - } - if p.tok == token.SEMICOLON { - p.next() - s1 = s2 - s2 = nil - if p.tok != token.LBRACE { - s2 = p.parseSimpleStmt(false) - } - } - p.exprLev = prevLev - } - - exprSwitch := isExprSwitch(s2) - lbrace := p.expect(token.LBRACE) - var list []ast.Stmt - for p.tok == token.CASE || p.tok == token.DEFAULT { - list = append(list, p.parseCaseClause(exprSwitch)) - } - rbrace := p.expect(token.RBRACE) - p.expectSemi() - body := &ast.BlockStmt{lbrace, list, rbrace} - - if exprSwitch { - return &ast.SwitchStmt{pos, s1, p.makeExpr(s2), body} - } - // type switch - // TODO(gri): do all the checks! - return &ast.TypeSwitchStmt{pos, s1, s2, body} -} - -func (p *parser) parseCommClause() *ast.CommClause { - if p.trace { - defer un(trace(p, "CommClause")) - } - - p.openScope() - pos := p.pos - var comm ast.Stmt - if p.tok == token.CASE { - p.next() - lhs := p.parseLhsList() - if p.tok == token.ARROW { - // SendStmt - if len(lhs) > 1 { - p.errorExpected(lhs[0].Pos(), "1 expression") - // continue with first expression - } - arrow := p.pos - p.next() - rhs := p.parseRhs() - comm = &ast.SendStmt{lhs[0], arrow, rhs} - } else { - // RecvStmt - pos := p.pos - tok := p.tok - var rhs ast.Expr - if tok == token.ASSIGN || tok == token.DEFINE { - // RecvStmt with assignment - if len(lhs) > 2 { - p.errorExpected(lhs[0].Pos(), "1 or 2 expressions") - // continue with first two expressions - lhs = lhs[0:2] - } - p.next() - rhs = p.parseRhs() - } else { - // rhs must be single receive operation - if len(lhs) > 1 { - p.errorExpected(lhs[0].Pos(), "1 expression") - // continue with first expression - } - rhs = lhs[0] - lhs = nil // there is no lhs - } - if x, isUnary := rhs.(*ast.UnaryExpr); !isUnary || x.Op != token.ARROW { - p.errorExpected(rhs.Pos(), "send or receive operation") - rhs = &ast.BadExpr{rhs.Pos(), rhs.End()} - } - if lhs != nil { - comm = &ast.AssignStmt{lhs, pos, tok, []ast.Expr{rhs}} - } else { - comm = &ast.ExprStmt{rhs} - } - } - } else { - p.expect(token.DEFAULT) - } - - colon := p.expect(token.COLON) - body := p.parseStmtList() - p.closeScope() - - return &ast.CommClause{pos, comm, colon, body} -} - -func (p *parser) parseSelectStmt() *ast.SelectStmt { - if p.trace { - defer un(trace(p, "SelectStmt")) - } - - pos := p.expect(token.SELECT) - lbrace := p.expect(token.LBRACE) - var list []ast.Stmt - for p.tok == token.CASE || p.tok == token.DEFAULT { - list = append(list, p.parseCommClause()) - } - rbrace := p.expect(token.RBRACE) - p.expectSemi() - body := &ast.BlockStmt{lbrace, list, rbrace} - - return &ast.SelectStmt{pos, body} -} - -func (p *parser) parseForStmt() ast.Stmt { - if p.trace { - defer un(trace(p, "ForStmt")) - } - - pos := p.expect(token.FOR) - p.openScope() - defer p.closeScope() - - var s1, s2, s3 ast.Stmt - if p.tok != token.LBRACE { - prevLev := p.exprLev - p.exprLev = -1 - if p.tok != token.SEMICOLON { - s2 = p.parseSimpleStmt(false) - } - if p.tok == token.SEMICOLON { - p.next() - s1 = s2 - s2 = nil - if p.tok != token.SEMICOLON { - s2 = p.parseSimpleStmt(false) - } - p.expectSemi() - if p.tok != token.LBRACE { - s3 = p.parseSimpleStmt(false) - } - } - p.exprLev = prevLev - } - - 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, body.End()} - } - // check lhs - var key, value ast.Expr - switch len(as.Lhs) { - case 2: - key, value = as.Lhs[0], as.Lhs[1] - case 1: - key = as.Lhs[0] - default: - p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions") - return &ast.BadStmt{pos, body.End()} - } - // check rhs - if len(as.Rhs) != 1 { - p.errorExpected(as.Rhs[0].Pos(), "1 expression") - return &ast.BadStmt{pos, body.End()} - } - if rhs, isUnary := as.Rhs[0].(*ast.UnaryExpr); isUnary && rhs.Op == token.RANGE { - // rhs is range expression - // (any short variable declaration was handled by parseSimpleStat above) - return &ast.RangeStmt{pos, key, value, as.TokPos, as.Tok, rhs.X, body} - } - p.errorExpected(s2.Pos(), "range clause") - return &ast.BadStmt{pos, body.End()} - } - - // regular for statement - return &ast.ForStmt{pos, s1, p.makeExpr(s2), s3, body} -} - -func (p *parser) parseStmt() (s ast.Stmt) { - if p.trace { - defer un(trace(p, "Statement")) - } - - switch p.tok { - case token.CONST, token.TYPE, token.VAR: - 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) - // because of the required look-ahead, labeled statements are - // parsed by parseSimpleStmt - don't expect a semicolon after - // them - if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt { - p.expectSemi() - } - case token.GO: - s = p.parseGoStmt() - case token.DEFER: - s = p.parseDeferStmt() - case token.RETURN: - s = p.parseReturnStmt() - case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH: - s = p.parseBranchStmt(p.tok) - case token.LBRACE: - s = p.parseBlockStmt() - p.expectSemi() - case token.IF: - s = p.parseIfStmt() - case token.SWITCH: - s = p.parseSwitchStmt() - case token.SELECT: - s = p.parseSelectStmt() - case token.FOR: - s = p.parseForStmt() - case token.SEMICOLON: - s = &ast.EmptyStmt{p.pos} - p.next() - case token.RBRACE: - // a semicolon may be omitted before a closing "}" - s = &ast.EmptyStmt{p.pos} - default: - // no statement found - pos := p.pos - p.errorExpected(pos, "statement") - p.next() // make progress - s = &ast.BadStmt{pos, p.pos} - } - - return -} - -// ---------------------------------------------------------------------------- -// Declarations - -type parseSpecFunction func(p *parser, doc *ast.CommentGroup, iota int) ast.Spec - -func parseImportSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { - if p.trace { - defer un(trace(p, "ImportSpec")) - } - - var ident *ast.Ident - switch p.tok { - case token.PERIOD: - ident = &ast.Ident{p.pos, ".", nil} - p.next() - case token.IDENT: - ident = p.parseIdent() - } - - var path *ast.BasicLit - if p.tok == token.STRING { - path = &ast.BasicLit{p.pos, p.tok, p.lit} - p.next() - } else { - p.expect(token.STRING) // use expect() error handling - } - p.expectSemi() // call before accessing p.linecomment - - // collect imports - spec := &ast.ImportSpec{doc, ident, path, p.lineComment} - p.imports = append(p.imports, spec) - - return spec -} - -func parseConstSpec(p *parser, doc *ast.CommentGroup, iota int) ast.Spec { - if p.trace { - defer un(trace(p, "ConstSpec")) - } - - idents := p.parseIdentList() - typ := p.tryType() - var values []ast.Expr - if typ != nil || p.tok == token.ASSIGN || iota == 0 { - p.expect(token.ASSIGN) - values = p.parseRhsList() - } - p.expectSemi() // call before accessing p.linecomment - - // Go spec: The scope of a constant or variable identifier declared inside - // a function begins at the end of the ConstSpec or VarSpec and ends at - // the end of the innermost containing block. - // (Global identifiers are resolved in a separate phase after parsing.) - spec := &ast.ValueSpec{doc, idents, typ, values, p.lineComment} - p.declare(spec, p.topScope, ast.Con, idents...) - - return spec -} - -func parseTypeSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { - if p.trace { - defer un(trace(p, "TypeSpec")) - } - - ident := p.parseIdent() - - // Go spec: The scope of a type identifier declared inside a function begins - // at the identifier in the TypeSpec and ends at the end of the innermost - // containing block. - // (Global identifiers are resolved in a separate phase after parsing.) - spec := &ast.TypeSpec{doc, ident, nil, nil} - p.declare(spec, p.topScope, ast.Typ, ident) - - spec.Type = p.parseType() - p.expectSemi() // call before accessing p.linecomment - spec.Comment = p.lineComment - - return spec -} - -func parseVarSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { - if p.trace { - defer un(trace(p, "VarSpec")) - } - - idents := p.parseIdentList() - typ := p.tryType() - var values []ast.Expr - if typ == nil || p.tok == token.ASSIGN { - p.expect(token.ASSIGN) - values = p.parseRhsList() - } - p.expectSemi() // call before accessing p.linecomment - - // Go spec: The scope of a constant or variable identifier declared inside - // a function begins at the end of the ConstSpec or VarSpec and ends at - // the end of the innermost containing block. - // (Global identifiers are resolved in a separate phase after parsing.) - spec := &ast.ValueSpec{doc, idents, typ, values, p.lineComment} - p.declare(spec, p.topScope, ast.Var, idents...) - - return spec -} - -func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl { - if p.trace { - defer un(trace(p, "GenDecl("+keyword.String()+")")) - } - - doc := p.leadComment - pos := p.expect(keyword) - var lparen, rparen token.Pos - var list []ast.Spec - if p.tok == token.LPAREN { - lparen = p.pos - p.next() - for iota := 0; p.tok != token.RPAREN && p.tok != token.EOF; iota++ { - list = append(list, f(p, p.leadComment, iota)) - } - rparen = p.expect(token.RPAREN) - p.expectSemi() - } else { - list = append(list, f(p, nil, 0)) - } - - return &ast.GenDecl{doc, pos, keyword, lparen, list, rparen} -} - -func (p *parser) parseReceiver(scope *ast.Scope) *ast.FieldList { - if p.trace { - defer un(trace(p, "Receiver")) - } - - pos := p.pos - par := p.parseParameters(scope, false) - - // must have exactly one receiver - if par.NumFields() != 1 { - p.errorExpected(pos, "exactly one receiver") - // TODO determine a better range for BadExpr below - par.List = []*ast.Field{{Type: &ast.BadExpr{pos, pos}}} - return par - } - - // recv type must be of the form ["*"] identifier - recv := par.List[0] - base := deref(recv.Type) - if _, isIdent := base.(*ast.Ident); !isIdent { - p.errorExpected(base.Pos(), "(unqualified) identifier") - par.List = []*ast.Field{{Type: &ast.BadExpr{recv.Pos(), recv.End()}}} - } - - return par -} - -func (p *parser) parseFuncDecl() *ast.FuncDecl { - if p.trace { - defer un(trace(p, "FunctionDecl")) - } - - doc := p.leadComment - pos := p.expect(token.FUNC) - scope := ast.NewScope(p.topScope) // function scope - - var recv *ast.FieldList - if p.tok == token.LPAREN { - recv = p.parseReceiver(scope) - } - - ident := p.parseIdent() - - params, results := p.parseSignature(scope) - - var body *ast.BlockStmt - if p.tok == token.LBRACE { - body = p.parseBody(scope) - } - p.expectSemi() - - decl := &ast.FuncDecl{doc, recv, ident, &ast.FuncType{pos, params, results}, body} - if recv == nil { - // Go spec: The scope of an identifier denoting a constant, type, - // variable, or function (but not method) declared at top level - // (outside any function) is the package block. - // - // init() functions cannot be referred to and there may - // be more than one - don't put them in the pkgScope - if ident.Name != "init" { - p.declare(decl, p.pkgScope, ast.Fun, ident) - } - } - - return decl -} - -func (p *parser) parseDecl() ast.Decl { - if p.trace { - defer un(trace(p, "Declaration")) - } - - var f parseSpecFunction - switch p.tok { - case token.CONST: - f = parseConstSpec - - case token.TYPE: - f = parseTypeSpec - - case token.VAR: - f = parseVarSpec - - case token.FUNC: - return p.parseFuncDecl() - - default: - pos := p.pos - p.errorExpected(pos, "declaration") - p.next() // make progress - decl := &ast.BadDecl{pos, p.pos} - return decl - } - - return p.parseGenDecl(p.tok, f) -} - -func (p *parser) parseDeclList() (list []ast.Decl) { - if p.trace { - defer un(trace(p, "DeclList")) - } - - for p.tok != token.EOF { - list = append(list, p.parseDecl()) - } - - return -} - -// ---------------------------------------------------------------------------- -// Source files - -func (p *parser) parseFile() *ast.File { - if p.trace { - defer un(trace(p, "File")) - } - - // package clause - doc := p.leadComment - pos := p.expect(token.PACKAGE) - // Go spec: The package clause is not a declaration; - // the package name does not appear in any scope. - ident := p.parseIdent() - if ident.Name == "_" { - p.error(p.pos, "invalid package name _") - } - p.expectSemi() - - 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 - for p.tok == token.IMPORT { - decls = append(decls, p.parseGenDecl(token.IMPORT, parseImportSpec)) - } - - if p.mode&ImportsOnly == 0 { - // rest of package body - for p.tok != token.EOF { - decls = append(decls, p.parseDecl()) - } - } - } - - assert(p.topScope == p.pkgScope, "imbalanced scopes") - - // resolve global identifiers within the same file - i := 0 - for _, ident := range p.unresolved { - // i <= index for current ident - assert(ident.Obj == unresolved, "object already resolved") - ident.Obj = p.pkgScope.Lookup(ident.Name) // also removes unresolved sentinel - if ident.Obj == nil { - p.unresolved[i] = ident - i++ - } - } - - // TODO(gri): store p.imports in AST - return &ast.File{doc, pos, ident, decls, p.pkgScope, p.imports, p.unresolved[0:i], p.comments} -} diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/slow.golden b/gcc-4.8.1/libgo/go/go/printer/testdata/slow.golden deleted file mode 100644 index 43a15cb1d..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/slow.golden +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package deepequal_test - -import ( - "testing" - "google3/spam/archer/frontend/deepequal" -) - -func TestTwoNilValues(t *testing.T) { - if err := deepequal.Check(nil, nil); err != nil { - t.Errorf("expected nil, saw %v", err) - } -} - -type Foo struct { - bar *Bar - bang *Bar -} - -type Bar struct { - baz *Baz - foo []*Foo -} - -type Baz struct { - entries map[int]interface{} - whatever string -} - -func newFoo() *Foo { - return &Foo{bar: &Bar{baz: &Baz{ - entries: map[int]interface{}{ - 42: &Foo{}, - 21: &Bar{}, - 11: &Baz{whatever: "it's just a test"}}}}, - bang: &Bar{foo: []*Foo{ - &Foo{bar: &Bar{baz: &Baz{ - entries: map[int]interface{}{ - 43: &Foo{}, - 22: &Bar{}, - 13: &Baz{whatever: "this is nuts"}}}}, - bang: &Bar{foo: []*Foo{ - &Foo{bar: &Bar{baz: &Baz{ - entries: map[int]interface{}{ - 61: &Foo{}, - 71: &Bar{}, - 11: &Baz{whatever: "no, it's Go"}}}}, - bang: &Bar{foo: []*Foo{ - &Foo{bar: &Bar{baz: &Baz{ - entries: map[int]interface{}{ - 0: &Foo{}, - -2: &Bar{}, - -11: &Baz{whatever: "we need to go deeper"}}}}, - bang: &Bar{foo: []*Foo{ - &Foo{bar: &Bar{baz: &Baz{ - entries: map[int]interface{}{ - -2: &Foo{}, - -5: &Bar{}, - -7: &Baz{whatever: "are you serious?"}}}}, - bang: &Bar{foo: []*Foo{}}}, - &Foo{bar: &Bar{baz: &Baz{ - entries: map[int]interface{}{ - -100: &Foo{}, - 50: &Bar{}, - 20: &Baz{whatever: "na, not really ..."}}}}, - bang: &Bar{foo: []*Foo{}}}}}}}}}, - &Foo{bar: &Bar{baz: &Baz{ - entries: map[int]interface{}{ - 2: &Foo{}, - 1: &Bar{}, - -1: &Baz{whatever: "... it's just a test."}}}}, - bang: &Bar{foo: []*Foo{}}}}}}}}} -} - -func TestElaborate(t *testing.T) { - a := newFoo() - b := newFoo() - - if err := deepequal.Check(a, b); err != nil { - t.Errorf("expected nil, saw %v", err) - } -} diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/slow.input b/gcc-4.8.1/libgo/go/go/printer/testdata/slow.input deleted file mode 100644 index 0e5a23d88..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/slow.input +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package deepequal_test - -import ( - "testing" - "google3/spam/archer/frontend/deepequal" -) - -func TestTwoNilValues(t *testing.T) { - if err := deepequal.Check(nil, nil); err != nil { - t.Errorf("expected nil, saw %v", err) - } -} - -type Foo struct { - bar *Bar - bang *Bar -} - -type Bar struct { - baz *Baz - foo []*Foo -} - -type Baz struct { - entries map[int]interface{} - whatever string -} - -func newFoo() (*Foo) { -return &Foo{bar: &Bar{ baz: &Baz{ -entries: map[int]interface{}{ -42: &Foo{}, -21: &Bar{}, -11: &Baz{ whatever: "it's just a test" }}}}, - bang: &Bar{foo: []*Foo{ -&Foo{bar: &Bar{ baz: &Baz{ -entries: map[int]interface{}{ -43: &Foo{}, -22: &Bar{}, -13: &Baz{ whatever: "this is nuts" }}}}, - bang: &Bar{foo: []*Foo{ -&Foo{bar: &Bar{ baz: &Baz{ -entries: map[int]interface{}{ -61: &Foo{}, -71: &Bar{}, -11: &Baz{ whatever: "no, it's Go" }}}}, - bang: &Bar{foo: []*Foo{ -&Foo{bar: &Bar{ baz: &Baz{ -entries: map[int]interface{}{ -0: &Foo{}, --2: &Bar{}, --11: &Baz{ whatever: "we need to go deeper" }}}}, - bang: &Bar{foo: []*Foo{ -&Foo{bar: &Bar{ baz: &Baz{ -entries: map[int]interface{}{ --2: &Foo{}, --5: &Bar{}, --7: &Baz{ whatever: "are you serious?" }}}}, - bang: &Bar{foo: []*Foo{}}}, -&Foo{bar: &Bar{ baz: &Baz{ -entries: map[int]interface{}{ --100: &Foo{}, -50: &Bar{}, -20: &Baz{ whatever: "na, not really ..." }}}}, - bang: &Bar{foo: []*Foo{}}}}}}}}}, -&Foo{bar: &Bar{ baz: &Baz{ -entries: map[int]interface{}{ -2: &Foo{}, -1: &Bar{}, --1: &Baz{ whatever: "... it's just a test." }}}}, - bang: &Bar{foo: []*Foo{}}}}}}}}} -} - -func TestElaborate(t *testing.T) { - a := newFoo() - b := newFoo() - - if err := deepequal.Check(a, b); err != nil { - t.Errorf("expected nil, saw %v", err) - } -} diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/statements.golden b/gcc-4.8.1/libgo/go/go/printer/testdata/statements.golden deleted file mode 100644 index 3b298f95e..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/statements.golden +++ /dev/null @@ -1,635 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package statements - -var expr bool - -func use(x interface{}) {} - -// Formatting of multi-line return statements. -func _f() { - return - return x, y, z - return T{} - return T{1, 2, 3}, - x, y, z - return T{1, 2, 3}, - x, y, - z - return T{1, - 2, - 3} - return T{1, - 2, - 3, - } - return T{ - 1, - 2, - 3} - return T{ - 1, - 2, - 3, - } - return T{ - 1, - T{1, 2, 3}, - 3, - } - return T{ - 1, - T{1, - 2, 3}, - 3, - } - return T{ - 1, - T{1, - 2, - 3}, - 3, - } - return T{ - 1, - 2, - }, nil - return T{ - 1, - 2, - }, - T{ - x: 3, - y: 4, - }, nil - return T{ - 1, - 2, - }, - nil - return T{ - 1, - 2, - }, - T{ - x: 3, - y: 4, - }, - nil - return x + y + - z - return func() {} - return func() { - _ = 0 - }, T{ - 1, 2, - } - return func() { - _ = 0 - } - return func() T { - return T{ - 1, 2, - } - } -} - -// Formatting of multi-line returns: test cases from issue 1207. -func F() (*T, os.Error) { - return &T{ - X: 1, - Y: 2, - }, - nil -} - -func G() (*T, *T, os.Error) { - return &T{ - X: 1, - Y: 2, - }, - &T{ - X: 3, - Y: 4, - }, - nil -} - -func _() interface{} { - return &fileStat{ - name: basename(file.name), - size: mkSize(d.FileSizeHigh, d.FileSizeLow), - modTime: mkModTime(d.LastWriteTime), - mode: mkMode(d.FileAttributes), - sys: mkSysFromFI(&d), - }, nil -} - -// Formatting of if-statement headers. -func _() { - if true { - } - if true { - } // no semicolon printed - if expr { - } - if expr { - } // no semicolon printed - if expr { - } // no parens printed - if expr { - } // no semicolon and parens printed - if x := expr; true { - use(x) - } - if x := expr; expr { - use(x) - } -} - -// Formatting of switch-statement headers. -func _() { - switch { - } - switch { - } // no semicolon printed - switch expr { - } - switch expr { - } // no semicolon printed - switch expr { - } // no parens printed - switch expr { - } // no semicolon and parens printed - switch x := expr; { - default: - use( - x) - } - switch x := expr; expr { - default: - use(x) - } -} - -// Formatting of switch statement bodies. -func _() { - switch { - } - - switch x := 0; x { - case 1: - use(x) - use(x) // followed by an empty line - - case 2: // followed by an empty line - - use(x) // followed by an empty line - - case 3: // no empty lines - use(x) - use(x) - } - - switch x { - case 0: - use(x) - case 1: // this comment should have no effect on the previous or next line - use(x) - } - - switch x := 0; x { - case 1: - x = 0 - // this comment should be indented - case 2: - x = 0 - // this comment should not be indented, it is aligned with the next case - case 3: - x = 0 - /* indented comment - aligned - aligned - */ - // bla - /* and more */ - case 4: - x = 0 - /* not indented comment - aligned - aligned - */ - // bla - /* and more */ - case 5: - } -} - -// Formatting of selected select statements. -func _() { - select {} - select { /* this comment should not be tab-aligned because the closing } is on the same line */ - } - select { /* this comment should be tab-aligned */ - } - select { // this comment should be tab-aligned - } - select { - case <-c: - } -} - -// Formatting of for-statement headers for single-line for-loops. -func _() { - for { - } - for expr { - } - for expr { - } // no parens printed - for { - } // no semicolons printed - for x := expr; ; { - use(x) - } - for expr { - } // no semicolons printed - for expr { - } // no semicolons and parens printed - for ; ; expr = false { - } - for x := expr; expr; { - use(x) - } - for x := expr; ; expr = false { - use(x) - } - for ; expr; expr = false { - } - for x := expr; expr; expr = false { - use(x) - } - for x := range []int{} { - use(x) - } - for x := range []int{} { - use(x) - } // no parens printed -} - -// Formatting of for-statement headers for multi-line for-loops. -func _() { - for { - } - for expr { - } - for expr { - } // no parens printed - for { - } // no semicolons printed - for x := expr; ; { - use(x) - } - for expr { - } // no semicolons printed - for expr { - } // no semicolons and parens printed - for ; ; expr = false { - } - for x := expr; expr; { - use(x) - } - for x := expr; ; expr = false { - use(x) - } - for ; expr; expr = false { - } - for x := expr; expr; expr = false { - use(x) - } - for x := range []int{} { - use(x) - } - for x := range []int{} { - use(x) - } // no parens printed -} - -// Formatting of selected short single- and multi-line statements. -func _() { - if cond { - } - if cond { - } // multiple lines - if cond { - } else { - } // else clause always requires multiple lines - - for { - } - for i := 0; i < len(a); 1++ { - } - for i := 0; i < len(a); 1++ { - a[i] = i - } - for i := 0; i < len(a); 1++ { - a[i] = i - } // multiple lines - - for i := range a { - } - for i := range a { - a[i] = i - } - for i := range a { - a[i] = i - } // multiple lines - - go func() { - for { - a <- <-b - } - }() - defer func() { - if x := recover(); x != nil { - err = fmt.Sprintf("error: %s", x.msg) - } - }() -} - -// Don't remove mandatory parentheses around composite literals in control clauses. -func _() { - // strip parentheses - no composite literals or composite literals don't start with a type name - if x { - } - if x { - } - if []T{} { - } - if []T{} { - } - if []T{} { - } - - for x { - } - for x { - } - for []T{} { - } - for []T{} { - } - for []T{} { - } - - switch x { - } - switch x { - } - switch []T{} { - } - switch []T{} { - } - - for _ = range []T{T{42}} { - } - - // leave parentheses - composite literals start with a type name - if (T{}) { - } - if (T{}) { - } - if (T{}) { - } - - for (T{}) { - } - for (T{}) { - } - for (T{}) { - } - - switch (T{}) { - } - switch (T{}) { - } - - for _ = range (T1{T{42}}) { - } - - if x == (T{42}[0]) { - } - if (x == T{42}[0]) { - } - if x == (T{42}[0]) { - } - if x == (T{42}[0]) { - } - if x == (T{42}[0]) { - } - if x == a+b*(T{42}[0]) { - } - if (x == a+b*T{42}[0]) { - } - if x == a+b*(T{42}[0]) { - } - if x == a+(b * (T{42}[0])) { - } - if x == a+b*(T{42}[0]) { - } - if (a + b*(T{42}[0])) == x { - } - if (a + b*(T{42}[0])) == x { - } - - if struct{ x bool }{false}.x { - } - if (struct{ x bool }{false}.x) == false { - } - if struct{ x bool }{false}.x == false { - } -} - -// Extra empty lines inside functions. Do respect source code line -// breaks between statement boundaries but print at most one empty -// line at a time. -func _() { - - const _ = 0 - - const _ = 1 - type _ int - type _ float - - var _ = 0 - var x = 1 - - // Each use(x) call below should have at most one empty line before and after. - // Known bug: The first use call may have more than one empty line before - // (see go/printer/nodes.go, func linebreak). - - use(x) - - if x < x { - - use(x) - - } else { - - use(x) - - } -} - -// Formatting around labels. -func _() { -L: -} - -func _() { - // this comment should be indented -L: // no semicolon needed -} - -func _() { - switch 0 { - case 0: - L0: - ; // semicolon required - case 1: - L1: - ; // semicolon required - default: - L2: // no semicolon needed - } -} - -func _() { - f() -L1: - f() -L2: - ; -L3: -} - -func _() { - // this comment should be indented -L: -} - -func _() { -L: - _ = 0 -} - -func _() { - // this comment should be indented -L: - _ = 0 -} - -func _() { - for { - L1: - _ = 0 - L2: - _ = 0 - } -} - -func _() { - // this comment should be indented - for { - L1: - _ = 0 - L2: - _ = 0 - } -} - -func _() { - if true { - _ = 0 - } - _ = 0 // the indentation here should not be affected by the long label name -AnOverlongLabel: - _ = 0 - - if true { - _ = 0 - } - _ = 0 - -L: - _ = 0 -} - -func _() { - for { - goto L - } -L: - - MoreCode() -} - -func _() { - for { - goto L - } -L: // A comment on the same line as the label, followed by a single empty line. - // Known bug: There may be more than one empty line before MoreCode() - // (see go/printer/nodes.go, func linebreak). - - MoreCode() -} - -func _() { - for { - goto L - } -L: - - // There should be a single empty line before this comment. - MoreCode() -} - -func _() { - for { - goto AVeryLongLabelThatShouldNotAffectFormatting - } -AVeryLongLabelThatShouldNotAffectFormatting: - // There should be a single empty line after this comment. - - // There should be a single empty line before this comment. - MoreCode() -} - -// Formatting of empty statements. -func _() { - -} - -func _() { -} - -func _() { -} - -func _() { - f() -} - -func _() { -L: - ; -} - -func _() { -L: - ; - f() -} diff --git a/gcc-4.8.1/libgo/go/go/printer/testdata/statements.input b/gcc-4.8.1/libgo/go/go/printer/testdata/statements.input deleted file mode 100644 index e7fcc0e54..000000000 --- a/gcc-4.8.1/libgo/go/go/printer/testdata/statements.input +++ /dev/null @@ -1,550 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package statements - -var expr bool - -func use(x interface{}) {} - -// Formatting of multi-line return statements. -func _f() { - return - return x, y, z - return T{} - return T{1, 2, 3}, - x, y, z - return T{1, 2, 3}, - x, y, - z - return T{1, - 2, - 3} - return T{1, - 2, - 3, - } - return T{ - 1, - 2, - 3} - return T{ - 1, - 2, - 3, - } - return T{ - 1, - T{1, 2, 3}, - 3, - } - return T{ - 1, - T{1, - 2, 3}, - 3, - } - return T{ - 1, - T{1, - 2, - 3}, - 3, - } - return T{ - 1, - 2, - }, nil - return T{ - 1, - 2, - }, - T{ - x: 3, - y: 4, - }, nil - return T{ - 1, - 2, - }, - nil - return T{ - 1, - 2, - }, - T{ - x: 3, - y: 4, - }, - nil - return x + y + - z - return func() {} - return func() { - _ = 0 - }, T{ - 1, 2, - } - return func() { - _ = 0 - } - return func() T { - return T { - 1, 2, - } - } -} - -// Formatting of multi-line returns: test cases from issue 1207. -func F() (*T, os.Error) { - return &T{ - X: 1, - Y: 2, - }, - nil -} - -func G() (*T, *T, os.Error) { - return &T{ - X: 1, - Y: 2, - }, - &T{ - X: 3, - Y: 4, - }, - nil -} - -func _() interface{} { - return &fileStat{ - name: basename(file.name), - size: mkSize(d.FileSizeHigh, d.FileSizeLow), - modTime: mkModTime(d.LastWriteTime), - mode: mkMode(d.FileAttributes), - sys: mkSysFromFI(&d), - }, nil -} - -// Formatting of if-statement headers. -func _() { - if true {} - if; true {} // no semicolon printed - if expr{} - if;expr{} // no semicolon printed - if (expr){} // no parens printed - if;((expr)){} // no semicolon and parens printed - if x:=expr;true{ - use(x)} - if x:=expr; expr {use(x)} -} - - -// Formatting of switch-statement headers. -func _() { - switch {} - switch;{} // no semicolon printed - switch expr {} - switch;expr{} // no semicolon printed - switch (expr) {} // no parens printed - switch;((expr)){} // no semicolon and parens printed - switch x := expr; { default:use( -x) - } - switch x := expr; expr {default:use(x)} -} - - -// Formatting of switch statement bodies. -func _() { - switch { - } - - switch x := 0; x { - case 1: - use(x) - use(x) // followed by an empty line - - case 2: // followed by an empty line - - use(x) // followed by an empty line - - case 3: // no empty lines - use(x) - use(x) - } - - switch x { - case 0: - use(x) - case 1: // this comment should have no effect on the previous or next line - use(x) - } - - switch x := 0; x { - case 1: - x = 0 - // this comment should be indented - case 2: - x = 0 - // this comment should not be indented, it is aligned with the next case - case 3: - x = 0 - /* indented comment - aligned - aligned - */ - // bla - /* and more */ - case 4: - x = 0 - /* not indented comment - aligned - aligned - */ - // bla - /* and more */ - case 5: - } -} - - -// Formatting of selected select statements. -func _() { - select { - } - select { /* this comment should not be tab-aligned because the closing } is on the same line */ } - select { /* this comment should be tab-aligned */ - } - select { // this comment should be tab-aligned - } - select { case <-c: } -} - - -// Formatting of for-statement headers for single-line for-loops. -func _() { - for{} - for expr {} - for (expr) {} // no parens printed - for;;{} // no semicolons printed - for x :=expr;; {use( x)} - for; expr;{} // no semicolons printed - for; ((expr));{} // no semicolons and parens printed - for; ; expr = false {} - for x :=expr; expr; {use(x)} - for x := expr;; expr=false {use(x)} - for;expr;expr =false {} - for x := expr;expr;expr = false { use(x) } - for x := range []int{} { use(x) } - for x := range (([]int{})) { use(x) } // no parens printed -} - - -// Formatting of for-statement headers for multi-line for-loops. -func _() { - for{ - } - for expr { - } - for (expr) { - } // no parens printed - for;;{ - } // no semicolons printed - for x :=expr;; {use( x) - } - for; expr;{ - } // no semicolons printed - for; ((expr));{ - } // no semicolons and parens printed - for; ; expr = false { - } - for x :=expr; expr; {use(x) - } - for x := expr;; expr=false {use(x) - } - for;expr;expr =false { - } - for x := expr;expr;expr = false { - use(x) - } - for x := range []int{} { - use(x) } - for x := range (([]int{})) { - use(x) } // no parens printed -} - - -// Formatting of selected short single- and multi-line statements. -func _() { - if cond {} - if cond { - } // multiple lines - if cond {} else {} // else clause always requires multiple lines - - for {} - for i := 0; i < len(a); 1++ {} - for i := 0; i < len(a); 1++ { a[i] = i } - for i := 0; i < len(a); 1++ { a[i] = i - } // multiple lines - - for i := range a {} - for i := range a { a[i] = i } - for i := range a { a[i] = i - } // multiple lines - - go func() { for { a <- <-b } }() - defer func() { if x := recover(); x != nil { err = fmt.Sprintf("error: %s", x.msg) } }() -} - - -// Don't remove mandatory parentheses around composite literals in control clauses. -func _() { - // strip parentheses - no composite literals or composite literals don't start with a type name - if (x) {} - if (((x))) {} - if ([]T{}) {} - if (([]T{})) {} - if ; (((([]T{})))) {} - - for (x) {} - for (((x))) {} - for ([]T{}) {} - for (([]T{})) {} - for ; (((([]T{})))) ; {} - - switch (x) {} - switch (((x))) {} - switch ([]T{}) {} - switch ; (((([]T{})))) {} - - for _ = range ((([]T{T{42}}))) {} - - // leave parentheses - composite literals start with a type name - if (T{}) {} - if ((T{})) {} - if ; ((((T{})))) {} - - for (T{}) {} - for ((T{})) {} - for ; ((((T{})))) ; {} - - switch (T{}) {} - switch ; ((((T{})))) {} - - for _ = range (((T1{T{42}}))) {} - - if x == (T{42}[0]) {} - if (x == T{42}[0]) {} - if (x == (T{42}[0])) {} - if (x == (((T{42}[0])))) {} - if (((x == (T{42}[0])))) {} - if x == a + b*(T{42}[0]) {} - if (x == a + b*T{42}[0]) {} - if (x == a + b*(T{42}[0])) {} - if (x == a + ((b * (T{42}[0])))) {} - if (((x == a + b * (T{42}[0])))) {} - if (((a + b * (T{42}[0])) == x)) {} - if (((a + b * (T{42}[0])))) == x {} - - if (struct{x bool}{false}.x) {} - if (struct{x bool}{false}.x) == false {} - if (struct{x bool}{false}.x == false) {} -} - - -// Extra empty lines inside functions. Do respect source code line -// breaks between statement boundaries but print at most one empty -// line at a time. -func _() { - - const _ = 0 - - const _ = 1 - type _ int - type _ float - - var _ = 0 - var x = 1 - - // Each use(x) call below should have at most one empty line before and after. - // Known bug: The first use call may have more than one empty line before - // (see go/printer/nodes.go, func linebreak). - - - - use(x) - - if x < x { - - use(x) - - } else { - - use(x) - - } -} - - -// Formatting around labels. -func _() { - L: -} - - -func _() { - // this comment should be indented - L: ; // no semicolon needed -} - - -func _() { - switch 0 { - case 0: - L0: ; // semicolon required - case 1: - L1: ; // semicolon required - default: - L2: ; // no semicolon needed - } -} - - -func _() { - f() -L1: - f() -L2: - ; -L3: -} - - -func _() { - // this comment should be indented - L: -} - - -func _() { - L: _ = 0 -} - - -func _() { - // this comment should be indented - L: _ = 0 -} - - -func _() { - for { - L1: _ = 0 - L2: - _ = 0 - } -} - - -func _() { - // this comment should be indented - for { - L1: _ = 0 - L2: - _ = 0 - } -} - - -func _() { - if true { - _ = 0 - } - _ = 0 // the indentation here should not be affected by the long label name -AnOverlongLabel: - _ = 0 - - if true { - _ = 0 - } - _ = 0 - -L: _ = 0 -} - - -func _() { - for { - goto L - } -L: - - MoreCode() -} - - -func _() { - for { - goto L - } -L: // A comment on the same line as the label, followed by a single empty line. - // Known bug: There may be more than one empty line before MoreCode() - // (see go/printer/nodes.go, func linebreak). - - - - - MoreCode() -} - - -func _() { - for { - goto L - } -L: - - - - - // There should be a single empty line before this comment. - MoreCode() -} - - -func _() { - for { - goto AVeryLongLabelThatShouldNotAffectFormatting - } -AVeryLongLabelThatShouldNotAffectFormatting: - // There should be a single empty line after this comment. - - // There should be a single empty line before this comment. - MoreCode() -} - - -// Formatting of empty statements. -func _() { - ;;;;;;;;;;;;;;;;;;;;;;;;; -} - -func _() {;;;;;;;;;;;;;;;;;;;;;;;;; -} - -func _() {;;;;;;;;;;;;;;;;;;;;;;;;;} - -func _() { -f();;;;;;;;;;;;;;;;;;;;;;;;; -} - -func _() { -L:;;;;;;;;;;;; -} - -func _() { -L:;;;;;;;;;;;; - f() -} diff --git a/gcc-4.8.1/libgo/go/go/scanner/errors.go b/gcc-4.8.1/libgo/go/go/scanner/errors.go deleted file mode 100644 index 22de69c3c..000000000 --- a/gcc-4.8.1/libgo/go/go/scanner/errors.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package scanner - -import ( - "fmt" - "go/token" - "io" - "sort" -) - -// In an ErrorList, an error is represented by an *Error. -// The position Pos, if valid, points to the beginning of -// the offending token, and the error condition is described -// by Msg. -// -type Error struct { - Pos token.Position - Msg string -} - -// Error implements the error interface. -func (e Error) Error() string { - if e.Pos.Filename != "" || e.Pos.IsValid() { - // don't print "<unknown position>" - // TODO(gri) reconsider the semantics of Position.IsValid - return e.Pos.String() + ": " + e.Msg - } - return e.Msg -} - -// ErrorList is a list of *Errors. -// The zero value for an ErrorList is an empty ErrorList ready to use. -// -type ErrorList []*Error - -// Add adds an Error with given position and error message to an ErrorList. -func (p *ErrorList) Add(pos token.Position, msg string) { - *p = append(*p, &Error{pos, msg}) -} - -// Reset resets an ErrorList to no errors. -func (p *ErrorList) Reset() { *p = (*p)[0:0] } - -// ErrorList implements the sort Interface. -func (p ErrorList) Len() int { return len(p) } -func (p ErrorList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p ErrorList) Less(i, j int) bool { - e := &p[i].Pos - f := &p[j].Pos - // Note that it is not sufficient to simply compare file offsets because - // the offsets do not reflect modified line information (through //line - // comments). - if e.Filename < f.Filename { - return true - } - if e.Filename == f.Filename { - if e.Line < f.Line { - return true - } - if e.Line == f.Line { - return e.Column < f.Column - } - } - return false -} - -// Sort sorts an ErrorList. *Error entries are sorted by position, -// other errors are sorted by error message, and before any *Error -// entry. -// -func (p ErrorList) Sort() { - sort.Sort(p) -} - -// RemoveMultiples sorts an ErrorList and removes all but the first error per line. -func (p *ErrorList) RemoveMultiples() { - sort.Sort(p) - var last token.Position // initial last.Line is != any legal error line - i := 0 - for _, e := range *p { - if e.Pos.Filename != last.Filename || e.Pos.Line != last.Line { - last = e.Pos - (*p)[i] = e - i++ - } - } - (*p) = (*p)[0:i] -} - -// An ErrorList implements the error interface. -func (p ErrorList) Error() string { - switch len(p) { - case 0: - return "no errors" - case 1: - return p[0].Error() - } - return fmt.Sprintf("%s (and %d more errors)", p[0], len(p)-1) -} - -// Err returns an error equivalent to this error list. -// If the list is empty, Err returns nil. -func (p ErrorList) Err() error { - if len(p) == 0 { - return nil - } - return p -} - -// PrintError is a utility function that prints a list of errors to w, -// one error per line, if the err parameter is an ErrorList. Otherwise -// it prints the err string. -// -func PrintError(w io.Writer, err error) { - if list, ok := err.(ErrorList); ok { - for _, e := range list { - fmt.Fprintf(w, "%s\n", e) - } - } else if err != nil { - fmt.Fprintf(w, "%s\n", err) - } -} diff --git a/gcc-4.8.1/libgo/go/go/scanner/scanner.go b/gcc-4.8.1/libgo/go/go/scanner/scanner.go deleted file mode 100644 index 3322c58b3..000000000 --- a/gcc-4.8.1/libgo/go/go/scanner/scanner.go +++ /dev/null @@ -1,727 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package scanner implements a scanner for Go source text. -// It takes a []byte as source which can then be tokenized -// through repeated calls to the Scan method. -// -package scanner - -import ( - "bytes" - "fmt" - "go/token" - "path/filepath" - "strconv" - "unicode" - "unicode/utf8" -) - -// An ErrorHandler may be provided to Scanner.Init. If a syntax error is -// encountered and a handler was installed, the handler is called with a -// position and an error message. The position points to the beginning of -// the offending token. -// -type ErrorHandler func(pos token.Position, msg string) - -// A Scanner holds the scanner's internal state while processing -// a given text. It can be allocated as part of another data -// structure but must be initialized via Init before use. -// -type Scanner struct { - // immutable state - file *token.File // source file handle - dir string // directory portion of file.Name() - src []byte // source - err ErrorHandler // error reporting; or nil - mode Mode // scanning mode - - // scanning state - ch rune // current character - offset int // character offset - rdOffset int // reading offset (position after current character) - lineOffset int // current line offset - insertSemi bool // insert a semicolon before next newline - - // public state - ok to modify - ErrorCount int // number of errors encountered -} - -// Read the next Unicode char into s.ch. -// s.ch < 0 means end-of-file. -// -func (s *Scanner) next() { - if s.rdOffset < len(s.src) { - s.offset = s.rdOffset - if s.ch == '\n' { - s.lineOffset = s.offset - s.file.AddLine(s.offset) - } - r, w := rune(s.src[s.rdOffset]), 1 - switch { - case r == 0: - s.error(s.offset, "illegal character NUL") - case r >= 0x80: - // not ASCII - r, w = utf8.DecodeRune(s.src[s.rdOffset:]) - if r == utf8.RuneError && w == 1 { - s.error(s.offset, "illegal UTF-8 encoding") - } - } - s.rdOffset += w - s.ch = r - } else { - s.offset = len(s.src) - if s.ch == '\n' { - s.lineOffset = s.offset - s.file.AddLine(s.offset) - } - s.ch = -1 // eof - } -} - -// A mode value is a set of flags (or 0). -// They control scanner behavior. -// -type Mode uint - -const ( - ScanComments Mode = 1 << iota // return comments as COMMENT tokens - dontInsertSemis // do not automatically insert semicolons - for testing only -) - -// Init prepares the scanner s to tokenize the text src by setting the -// scanner at the beginning of src. The scanner uses the file set file -// for position information and it adds line information for each line. -// It is ok to re-use the same file when re-scanning the same file as -// line information which is already present is ignored. Init causes a -// panic if the file size does not match the src size. -// -// Calls to Scan will invoke the error handler err if they encounter a -// syntax error and err is not nil. Also, for each error encountered, -// the Scanner field ErrorCount is incremented by one. The mode parameter -// determines how comments are handled. -// -// Note that Init may call err if there is an error in the first character -// of the file. -// -func (s *Scanner) Init(file *token.File, src []byte, err ErrorHandler, mode Mode) { - // Explicitly initialize all fields since a scanner may be reused. - if file.Size() != len(src) { - panic(fmt.Sprintf("file size (%d) does not match src len (%d)", file.Size(), len(src))) - } - s.file = file - s.dir, _ = filepath.Split(file.Name()) - s.src = src - s.err = err - s.mode = mode - - s.ch = ' ' - s.offset = 0 - s.rdOffset = 0 - s.lineOffset = 0 - s.insertSemi = false - s.ErrorCount = 0 - - s.next() - if s.ch == '\uFEFF' { - s.next() // ignore BOM - } -} - -func (s *Scanner) error(offs int, msg string) { - if s.err != nil { - s.err(s.file.Position(s.file.Pos(offs)), msg) - } - s.ErrorCount++ -} - -var prefix = []byte("//line ") - -func (s *Scanner) interpretLineComment(text []byte) { - if bytes.HasPrefix(text, prefix) { - // get filename and line number, if any - if i := bytes.LastIndex(text, []byte{':'}); i > 0 { - if line, err := strconv.Atoi(string(text[i+1:])); err == nil && line > 0 { - // valid //line filename:line comment; - filename := filepath.Clean(string(text[len(prefix):i])) - if !filepath.IsAbs(filename) { - // make filename relative to current directory - filename = filepath.Join(s.dir, filename) - } - // update scanner position - s.file.AddLineInfo(s.lineOffset+len(text)+1, filename, line) // +len(text)+1 since comment applies to next line - } - } - } -} - -func (s *Scanner) scanComment() string { - // initial '/' already consumed; s.ch == '/' || s.ch == '*' - offs := s.offset - 1 // position of initial '/' - hasCR := false - - if s.ch == '/' { - //-style comment - s.next() - for s.ch != '\n' && s.ch >= 0 { - if s.ch == '\r' { - hasCR = true - } - s.next() - } - if offs == s.lineOffset { - // comment starts at the beginning of the current line - s.interpretLineComment(s.src[offs:s.offset]) - } - goto exit - } - - /*-style comment */ - s.next() - for s.ch >= 0 { - ch := s.ch - if ch == '\r' { - hasCR = true - } - s.next() - if ch == '*' && s.ch == '/' { - s.next() - goto exit - } - } - - s.error(offs, "comment not terminated") - -exit: - lit := s.src[offs:s.offset] - if hasCR { - lit = stripCR(lit) - } - - return string(lit) -} - -func (s *Scanner) findLineEnd() bool { - // initial '/' already consumed - - defer func(offs int) { - // reset scanner state to where it was upon calling findLineEnd - s.ch = '/' - s.offset = offs - s.rdOffset = offs + 1 - s.next() // consume initial '/' again - }(s.offset - 1) - - // read ahead until a newline, EOF, or non-comment token is found - for s.ch == '/' || s.ch == '*' { - if s.ch == '/' { - //-style comment always contains a newline - return true - } - /*-style comment: look for newline */ - s.next() - for s.ch >= 0 { - ch := s.ch - if ch == '\n' { - return true - } - s.next() - if ch == '*' && s.ch == '/' { - s.next() - break - } - } - s.skipWhitespace() // s.insertSemi is set - if s.ch < 0 || s.ch == '\n' { - return true - } - if s.ch != '/' { - // non-comment token - return false - } - s.next() // consume '/' - } - - return false -} - -func isLetter(ch rune) bool { - return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch) -} - -func isDigit(ch rune) bool { - return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch) -} - -func (s *Scanner) scanIdentifier() string { - offs := s.offset - for isLetter(s.ch) || isDigit(s.ch) { - s.next() - } - return string(s.src[offs:s.offset]) -} - -func digitVal(ch rune) int { - switch { - case '0' <= ch && ch <= '9': - return int(ch - '0') - case 'a' <= ch && ch <= 'f': - return int(ch - 'a' + 10) - case 'A' <= ch && ch <= 'F': - return int(ch - 'A' + 10) - } - return 16 // larger than any legal digit val -} - -func (s *Scanner) scanMantissa(base int) { - for digitVal(s.ch) < base { - s.next() - } -} - -func (s *Scanner) scanNumber(seenDecimalPoint bool) (token.Token, string) { - // digitVal(s.ch) < 10 - offs := s.offset - tok := token.INT - - if seenDecimalPoint { - offs-- - tok = token.FLOAT - s.scanMantissa(10) - goto exponent - } - - if s.ch == '0' { - // int or float - offs := s.offset - s.next() - if s.ch == 'x' || s.ch == 'X' { - // hexadecimal int - s.next() - s.scanMantissa(16) - if s.offset-offs <= 2 { - // only scanned "0x" or "0X" - s.error(offs, "illegal hexadecimal number") - } - } else { - // octal int or float - seenDecimalDigit := false - s.scanMantissa(8) - if s.ch == '8' || s.ch == '9' { - // illegal octal int or float - seenDecimalDigit = true - s.scanMantissa(10) - } - if s.ch == '.' || s.ch == 'e' || s.ch == 'E' || s.ch == 'i' { - goto fraction - } - // octal int - if seenDecimalDigit { - s.error(offs, "illegal octal number") - } - } - goto exit - } - - // decimal int or float - s.scanMantissa(10) - -fraction: - if s.ch == '.' { - tok = token.FLOAT - s.next() - s.scanMantissa(10) - } - -exponent: - if s.ch == 'e' || s.ch == 'E' { - tok = token.FLOAT - s.next() - if s.ch == '-' || s.ch == '+' { - s.next() - } - s.scanMantissa(10) - } - - if s.ch == 'i' { - tok = token.IMAG - s.next() - } - -exit: - return tok, string(s.src[offs:s.offset]) -} - -func (s *Scanner) scanEscape(quote rune) { - offs := s.offset - - var i, base, max uint32 - switch s.ch { - case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', quote: - s.next() - return - case '0', '1', '2', '3', '4', '5', '6', '7': - i, base, max = 3, 8, 255 - case 'x': - s.next() - i, base, max = 2, 16, 255 - case 'u': - s.next() - i, base, max = 4, 16, unicode.MaxRune - case 'U': - s.next() - i, base, max = 8, 16, unicode.MaxRune - default: - s.next() // always make progress - s.error(offs, "unknown escape sequence") - return - } - - var x uint32 - for ; i > 0 && s.ch != quote && s.ch >= 0; i-- { - d := uint32(digitVal(s.ch)) - if d >= base { - s.error(s.offset, "illegal character in escape sequence") - break - } - x = x*base + d - s.next() - } - // in case of an error, consume remaining chars - for ; i > 0 && s.ch != quote && s.ch >= 0; i-- { - s.next() - } - if x > max || 0xD800 <= x && x < 0xE000 { - s.error(offs, "escape sequence is invalid Unicode code point") - } -} - -func (s *Scanner) scanChar() string { - // '\'' opening already consumed - offs := s.offset - 1 - - n := 0 - for s.ch != '\'' { - ch := s.ch - n++ - s.next() - if ch == '\n' || ch < 0 { - s.error(offs, "character literal not terminated") - n = 1 - break - } - if ch == '\\' { - s.scanEscape('\'') - } - } - - s.next() - - if n != 1 { - s.error(offs, "illegal character literal") - } - - return string(s.src[offs:s.offset]) -} - -func (s *Scanner) scanString() string { - // '"' opening already consumed - offs := s.offset - 1 - - for s.ch != '"' { - ch := s.ch - s.next() - if ch == '\n' || ch < 0 { - s.error(offs, "string not terminated") - break - } - if ch == '\\' { - s.scanEscape('"') - } - } - - s.next() - - return string(s.src[offs:s.offset]) -} - -func stripCR(b []byte) []byte { - c := make([]byte, len(b)) - i := 0 - for _, ch := range b { - if ch != '\r' { - c[i] = ch - i++ - } - } - return c[:i] -} - -func (s *Scanner) scanRawString() string { - // '`' opening already consumed - offs := s.offset - 1 - - hasCR := false - for s.ch != '`' { - ch := s.ch - s.next() - if ch == '\r' { - hasCR = true - } - if ch < 0 { - s.error(offs, "string not terminated") - break - } - } - - s.next() - - lit := s.src[offs:s.offset] - if hasCR { - lit = stripCR(lit) - } - - return string(lit) -} - -func (s *Scanner) skipWhitespace() { - for s.ch == ' ' || s.ch == '\t' || s.ch == '\n' && !s.insertSemi || s.ch == '\r' { - s.next() - } -} - -// Helper functions for scanning multi-byte tokens such as >> += >>= . -// Different routines recognize different length tok_i based on matches -// of ch_i. If a token ends in '=', the result is tok1 or tok3 -// respectively. Otherwise, the result is tok0 if there was no other -// matching character, or tok2 if the matching character was ch2. - -func (s *Scanner) switch2(tok0, tok1 token.Token) token.Token { - if s.ch == '=' { - s.next() - return tok1 - } - return tok0 -} - -func (s *Scanner) switch3(tok0, tok1 token.Token, ch2 rune, tok2 token.Token) token.Token { - if s.ch == '=' { - s.next() - return tok1 - } - if s.ch == ch2 { - s.next() - return tok2 - } - return tok0 -} - -func (s *Scanner) switch4(tok0, tok1 token.Token, ch2 rune, tok2, tok3 token.Token) token.Token { - if s.ch == '=' { - s.next() - return tok1 - } - if s.ch == ch2 { - s.next() - if s.ch == '=' { - s.next() - return tok3 - } - return tok2 - } - return tok0 -} - -// Scan scans the next token and returns the token position, the token, -// and its literal string if applicable. The source end is indicated by -// token.EOF. -// -// If the returned token is a literal (token.IDENT, token.INT, token.FLOAT, -// token.IMAG, token.CHAR, token.STRING) or token.COMMENT, the literal string -// has the corresponding value. -// -// If the returned token is a keyword, the literal string is the keyword. -// -// If the returned token is token.SEMICOLON, the corresponding -// literal string is ";" if the semicolon was present in the source, -// and "\n" if the semicolon was inserted because of a newline or -// at EOF. -// -// If the returned token is token.ILLEGAL, the literal string is the -// offending character. -// -// In all other cases, Scan returns an empty literal string. -// -// For more tolerant parsing, Scan will return a valid token if -// possible even if a syntax error was encountered. Thus, even -// if the resulting token sequence contains no illegal tokens, -// a client may not assume that no error occurred. Instead it -// must check the scanner's ErrorCount or the number of calls -// of the error handler, if there was one installed. -// -// Scan adds line information to the file added to the file -// set with Init. Token positions are relative to that file -// and thus relative to the file set. -// -func (s *Scanner) Scan() (pos token.Pos, tok token.Token, lit string) { -scanAgain: - s.skipWhitespace() - - // current token start - pos = s.file.Pos(s.offset) - - // determine token value - insertSemi := false - switch ch := s.ch; { - case isLetter(ch): - lit = s.scanIdentifier() - if len(lit) > 1 { - // keywords are longer than one letter - avoid lookup otherwise - tok = token.Lookup(lit) - switch tok { - case token.IDENT, token.BREAK, token.CONTINUE, token.FALLTHROUGH, token.RETURN: - insertSemi = true - } - } else { - insertSemi = true - tok = token.IDENT - } - case '0' <= ch && ch <= '9': - insertSemi = true - tok, lit = s.scanNumber(false) - default: - s.next() // always make progress - switch ch { - case -1: - if s.insertSemi { - s.insertSemi = false // EOF consumed - return pos, token.SEMICOLON, "\n" - } - tok = token.EOF - case '\n': - // we only reach here if s.insertSemi was - // set in the first place and exited early - // from s.skipWhitespace() - s.insertSemi = false // newline consumed - return pos, token.SEMICOLON, "\n" - case '"': - insertSemi = true - tok = token.STRING - lit = s.scanString() - case '\'': - insertSemi = true - tok = token.CHAR - lit = s.scanChar() - case '`': - insertSemi = true - tok = token.STRING - lit = s.scanRawString() - case ':': - tok = s.switch2(token.COLON, token.DEFINE) - case '.': - if '0' <= s.ch && s.ch <= '9' { - insertSemi = true - tok, lit = s.scanNumber(true) - } else if s.ch == '.' { - s.next() - if s.ch == '.' { - s.next() - tok = token.ELLIPSIS - } - } else { - tok = token.PERIOD - } - case ',': - tok = token.COMMA - case ';': - tok = token.SEMICOLON - lit = ";" - case '(': - tok = token.LPAREN - case ')': - insertSemi = true - tok = token.RPAREN - case '[': - tok = token.LBRACK - case ']': - insertSemi = true - tok = token.RBRACK - case '{': - tok = token.LBRACE - case '}': - insertSemi = true - tok = token.RBRACE - case '+': - 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) - if tok == token.DEC { - insertSemi = true - } - case '*': - tok = s.switch2(token.MUL, token.MUL_ASSIGN) - case '/': - if s.ch == '/' || s.ch == '*' { - // comment - if s.insertSemi && s.findLineEnd() { - // reset position to the beginning of the comment - s.ch = '/' - s.offset = s.file.Offset(pos) - s.rdOffset = s.offset + 1 - s.insertSemi = false // newline consumed - return pos, token.SEMICOLON, "\n" - } - lit = s.scanComment() - if s.mode&ScanComments == 0 { - // skip comment - s.insertSemi = false // newline consumed - goto scanAgain - } - tok = token.COMMENT - } else { - tok = s.switch2(token.QUO, token.QUO_ASSIGN) - } - case '%': - tok = s.switch2(token.REM, token.REM_ASSIGN) - case '^': - tok = s.switch2(token.XOR, token.XOR_ASSIGN) - case '<': - if s.ch == '-' { - s.next() - tok = token.ARROW - } else { - tok = s.switch4(token.LSS, token.LEQ, '<', token.SHL, token.SHL_ASSIGN) - } - case '>': - tok = s.switch4(token.GTR, token.GEQ, '>', token.SHR, token.SHR_ASSIGN) - case '=': - tok = s.switch2(token.ASSIGN, token.EQL) - case '!': - tok = s.switch2(token.NOT, token.NEQ) - case '&': - if s.ch == '^' { - s.next() - tok = s.switch2(token.AND_NOT, token.AND_NOT_ASSIGN) - } else { - tok = s.switch3(token.AND, token.AND_ASSIGN, '&', token.LAND) - } - case '|': - tok = s.switch3(token.OR, token.OR_ASSIGN, '|', token.LOR) - default: - s.error(s.file.Offset(pos), fmt.Sprintf("illegal character %#U", ch)) - insertSemi = s.insertSemi // preserve insertSemi info - tok = token.ILLEGAL - lit = string(ch) - } - } - if s.mode&dontInsertSemis == 0 { - s.insertSemi = insertSemi - } - - return -} diff --git a/gcc-4.8.1/libgo/go/go/scanner/scanner_test.go b/gcc-4.8.1/libgo/go/go/scanner/scanner_test.go deleted file mode 100644 index 1c19053e6..000000000 --- a/gcc-4.8.1/libgo/go/go/scanner/scanner_test.go +++ /dev/null @@ -1,745 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package scanner - -import ( - "go/token" - "io/ioutil" - "os" - "path/filepath" - "runtime" - "testing" -) - -var fset = token.NewFileSet() - -const /* class */ ( - special = iota - literal - operator - keyword -) - -func tokenclass(tok token.Token) int { - switch { - case tok.IsLiteral(): - return literal - case tok.IsOperator(): - return operator - case tok.IsKeyword(): - return keyword - } - return special -} - -type elt struct { - tok token.Token - lit string - class int -} - -var tokens = [...]elt{ - // Special tokens - {token.COMMENT, "/* a comment */", special}, - {token.COMMENT, "// a comment \n", special}, - {token.COMMENT, "/*\r*/", special}, - {token.COMMENT, "//\r\n", special}, - - // Identifiers and basic type literals - {token.IDENT, "foobar", literal}, - {token.IDENT, "a۰۱۸", literal}, - {token.IDENT, "foo६४", literal}, - {token.IDENT, "bar9876", literal}, - {token.IDENT, "ŝ", literal}, // was bug (issue 4000) - {token.IDENT, "ŝfoo", literal}, // was bug (issue 4000) - {token.INT, "0", literal}, - {token.INT, "1", literal}, - {token.INT, "123456789012345678890", literal}, - {token.INT, "01234567", literal}, - {token.INT, "0xcafebabe", literal}, - {token.FLOAT, "0.", literal}, - {token.FLOAT, ".0", literal}, - {token.FLOAT, "3.14159265", literal}, - {token.FLOAT, "1e0", literal}, - {token.FLOAT, "1e+100", literal}, - {token.FLOAT, "1e-100", literal}, - {token.FLOAT, "2.71828e-1000", literal}, - {token.IMAG, "0i", literal}, - {token.IMAG, "1i", literal}, - {token.IMAG, "012345678901234567889i", literal}, - {token.IMAG, "123456789012345678890i", literal}, - {token.IMAG, "0.i", literal}, - {token.IMAG, ".0i", literal}, - {token.IMAG, "3.14159265i", literal}, - {token.IMAG, "1e0i", literal}, - {token.IMAG, "1e+100i", literal}, - {token.IMAG, "1e-100i", literal}, - {token.IMAG, "2.71828e-1000i", literal}, - {token.CHAR, "'a'", literal}, - {token.CHAR, "'\\000'", literal}, - {token.CHAR, "'\\xFF'", literal}, - {token.CHAR, "'\\uff16'", literal}, - {token.CHAR, "'\\U0000ff16'", literal}, - {token.STRING, "`foobar`", literal}, - {token.STRING, "`" + `foo - bar` + - "`", - literal, - }, - {token.STRING, "`\r`", literal}, - {token.STRING, "`foo\r\nbar`", literal}, - - // Operators and delimiters - {token.ADD, "+", operator}, - {token.SUB, "-", operator}, - {token.MUL, "*", operator}, - {token.QUO, "/", operator}, - {token.REM, "%", operator}, - - {token.AND, "&", operator}, - {token.OR, "|", operator}, - {token.XOR, "^", operator}, - {token.SHL, "<<", operator}, - {token.SHR, ">>", operator}, - {token.AND_NOT, "&^", operator}, - - {token.ADD_ASSIGN, "+=", operator}, - {token.SUB_ASSIGN, "-=", operator}, - {token.MUL_ASSIGN, "*=", operator}, - {token.QUO_ASSIGN, "/=", operator}, - {token.REM_ASSIGN, "%=", operator}, - - {token.AND_ASSIGN, "&=", operator}, - {token.OR_ASSIGN, "|=", operator}, - {token.XOR_ASSIGN, "^=", operator}, - {token.SHL_ASSIGN, "<<=", operator}, - {token.SHR_ASSIGN, ">>=", operator}, - {token.AND_NOT_ASSIGN, "&^=", operator}, - - {token.LAND, "&&", operator}, - {token.LOR, "||", operator}, - {token.ARROW, "<-", operator}, - {token.INC, "++", operator}, - {token.DEC, "--", operator}, - - {token.EQL, "==", operator}, - {token.LSS, "<", operator}, - {token.GTR, ">", operator}, - {token.ASSIGN, "=", operator}, - {token.NOT, "!", operator}, - - {token.NEQ, "!=", operator}, - {token.LEQ, "<=", operator}, - {token.GEQ, ">=", operator}, - {token.DEFINE, ":=", operator}, - {token.ELLIPSIS, "...", operator}, - - {token.LPAREN, "(", operator}, - {token.LBRACK, "[", operator}, - {token.LBRACE, "{", operator}, - {token.COMMA, ",", operator}, - {token.PERIOD, ".", operator}, - - {token.RPAREN, ")", operator}, - {token.RBRACK, "]", operator}, - {token.RBRACE, "}", operator}, - {token.SEMICOLON, ";", operator}, - {token.COLON, ":", operator}, - - // Keywords - {token.BREAK, "break", keyword}, - {token.CASE, "case", keyword}, - {token.CHAN, "chan", keyword}, - {token.CONST, "const", keyword}, - {token.CONTINUE, "continue", keyword}, - - {token.DEFAULT, "default", keyword}, - {token.DEFER, "defer", keyword}, - {token.ELSE, "else", keyword}, - {token.FALLTHROUGH, "fallthrough", keyword}, - {token.FOR, "for", keyword}, - - {token.FUNC, "func", keyword}, - {token.GO, "go", keyword}, - {token.GOTO, "goto", keyword}, - {token.IF, "if", keyword}, - {token.IMPORT, "import", keyword}, - - {token.INTERFACE, "interface", keyword}, - {token.MAP, "map", keyword}, - {token.PACKAGE, "package", keyword}, - {token.RANGE, "range", keyword}, - {token.RETURN, "return", keyword}, - - {token.SELECT, "select", keyword}, - {token.STRUCT, "struct", keyword}, - {token.SWITCH, "switch", keyword}, - {token.TYPE, "type", keyword}, - {token.VAR, "var", keyword}, -} - -const whitespace = " \t \n\n\n" // to separate tokens - -var source = func() []byte { - var src []byte - for _, t := range tokens { - src = append(src, t.lit...) - src = append(src, whitespace...) - } - return src -}() - -func newlineCount(s string) int { - n := 0 - for i := 0; i < len(s); i++ { - if s[i] == '\n' { - n++ - } - } - return n -} - -func checkPos(t *testing.T, lit string, p token.Pos, expected token.Position) { - pos := fset.Position(p) - if pos.Filename != expected.Filename { - t.Errorf("bad filename for %q: got %s, expected %s", lit, pos.Filename, expected.Filename) - } - if pos.Offset != expected.Offset { - t.Errorf("bad position for %q: got %d, expected %d", lit, pos.Offset, expected.Offset) - } - if pos.Line != expected.Line { - t.Errorf("bad line for %q: got %d, expected %d", lit, pos.Line, expected.Line) - } - if pos.Column != expected.Column { - t.Errorf("bad column for %q: got %d, expected %d", lit, pos.Column, expected.Column) - } -} - -// Verify that calling Scan() provides the correct results. -func TestScan(t *testing.T) { - whitespace_linecount := newlineCount(whitespace) - - // error handler - eh := func(_ token.Position, msg string) { - t.Errorf("error handler called (msg = %s)", msg) - } - - // verify scan - var s Scanner - s.Init(fset.AddFile("", fset.Base(), len(source)), source, eh, ScanComments|dontInsertSemis) - - // set up expected position - epos := token.Position{ - Filename: "", - Offset: 0, - Line: 1, - Column: 1, - } - - index := 0 - for { - pos, tok, lit := s.Scan() - - // check position - if tok == token.EOF { - // correction for EOF - epos.Line = newlineCount(string(source)) - epos.Column = 2 - } - checkPos(t, lit, pos, epos) - - // check token - e := elt{token.EOF, "", special} - if index < len(tokens) { - e = tokens[index] - index++ - } - if tok != e.tok { - t.Errorf("bad token for %q: got %s, expected %s", lit, tok, e.tok) - } - - // check token class - if tokenclass(tok) != e.class { - t.Errorf("bad class for %q: got %d, expected %d", lit, tokenclass(tok), e.class) - } - - // check literal - elit := "" - switch e.tok { - case token.COMMENT: - // no CRs in comments - elit = string(stripCR([]byte(e.lit))) - //-style comment literal doesn't contain newline - if elit[1] == '/' { - elit = elit[0 : len(elit)-1] - } - case token.IDENT: - elit = e.lit - case token.SEMICOLON: - elit = ";" - default: - if e.tok.IsLiteral() { - // no CRs in raw string literals - elit = e.lit - if elit[0] == '`' { - elit = string(stripCR([]byte(elit))) - } - } else if e.tok.IsKeyword() { - elit = e.lit - } - } - if lit != elit { - t.Errorf("bad literal for %q: got %q, expected %q", lit, lit, elit) - } - - if tok == token.EOF { - break - } - - // update position - epos.Offset += len(e.lit) + len(whitespace) - epos.Line += newlineCount(e.lit) + whitespace_linecount - - } - - if s.ErrorCount != 0 { - t.Errorf("found %d errors", s.ErrorCount) - } -} - -func checkSemi(t *testing.T, line string, mode Mode) { - var S Scanner - file := fset.AddFile("TestSemis", fset.Base(), len(line)) - S.Init(file, []byte(line), nil, mode) - pos, tok, lit := S.Scan() - for tok != token.EOF { - if tok == token.ILLEGAL { - // the illegal token literal indicates what - // kind of semicolon literal to expect - semiLit := "\n" - if lit[0] == '#' { - semiLit = ";" - } - // next token must be a semicolon - semiPos := file.Position(pos) - semiPos.Offset++ - semiPos.Column++ - pos, tok, lit = S.Scan() - if tok == token.SEMICOLON { - if lit != semiLit { - t.Errorf(`bad literal for %q: got %q, expected %q`, line, lit, semiLit) - } - checkPos(t, line, pos, semiPos) - } else { - t.Errorf("bad token for %q: got %s, expected ;", line, tok) - } - } else if tok == token.SEMICOLON { - t.Errorf("bad token for %q: got ;, expected no ;", line) - } - pos, tok, lit = S.Scan() - } -} - -var lines = []string{ - // # indicates a semicolon present in the source - // $ indicates an automatically inserted semicolon - "", - "\ufeff#;", // first BOM is ignored - "#;", - "foo$\n", - "123$\n", - "1.2$\n", - "'x'$\n", - `"x"` + "$\n", - "`x`$\n", - - "+\n", - "-\n", - "*\n", - "/\n", - "%\n", - - "&\n", - "|\n", - "^\n", - "<<\n", - ">>\n", - "&^\n", - - "+=\n", - "-=\n", - "*=\n", - "/=\n", - "%=\n", - - "&=\n", - "|=\n", - "^=\n", - "<<=\n", - ">>=\n", - "&^=\n", - - "&&\n", - "||\n", - "<-\n", - "++$\n", - "--$\n", - - "==\n", - "<\n", - ">\n", - "=\n", - "!\n", - - "!=\n", - "<=\n", - ">=\n", - ":=\n", - "...\n", - - "(\n", - "[\n", - "{\n", - ",\n", - ".\n", - - ")$\n", - "]$\n", - "}$\n", - "#;\n", - ":\n", - - "break$\n", - "case\n", - "chan\n", - "const\n", - "continue$\n", - - "default\n", - "defer\n", - "else\n", - "fallthrough$\n", - "for\n", - - "func\n", - "go\n", - "goto\n", - "if\n", - "import\n", - - "interface\n", - "map\n", - "package\n", - "range\n", - "return$\n", - - "select\n", - "struct\n", - "switch\n", - "type\n", - "var\n", - - "foo$//comment\n", - "foo$//comment", - "foo$/*comment*/\n", - "foo$/*\n*/", - "foo$/*comment*/ \n", - "foo$/*\n*/ ", - - "foo $// comment\n", - "foo $// comment", - "foo $/*comment*/\n", - "foo $/*\n*/", - "foo $/* */ /* \n */ bar$/**/\n", - "foo $/*0*/ /*1*/ /*2*/\n", - - "foo $/*comment*/ \n", - "foo $/*0*/ /*1*/ /*2*/ \n", - "foo $/**/ /*-------------*/ /*----\n*/bar $/* \n*/baa$\n", - "foo $/* an EOF terminates a line */", - "foo $/* an EOF terminates a line */ /*", - "foo $/* an EOF terminates a line */ //", - - "package main$\n\nfunc main() {\n\tif {\n\t\treturn /* */ }$\n}$\n", - "package main$", -} - -func TestSemis(t *testing.T) { - for _, line := range lines { - checkSemi(t, line, 0) - checkSemi(t, line, ScanComments) - - // if the input ended in newlines, the input must tokenize the - // same with or without those newlines - for i := len(line) - 1; i >= 0 && line[i] == '\n'; i-- { - checkSemi(t, line[0:i], 0) - checkSemi(t, line[0:i], ScanComments) - } - } -} - -type segment struct { - srcline string // a line of source text - filename string // filename for current token - line int // line number for current token -} - -var segments = []segment{ - // exactly one token per line since the test consumes one token per segment - {" line1", filepath.Join("dir", "TestLineComments"), 1}, - {"\nline2", filepath.Join("dir", "TestLineComments"), 2}, - {"\nline3 //line File1.go:100", filepath.Join("dir", "TestLineComments"), 3}, // bad line comment, ignored - {"\nline4", filepath.Join("dir", "TestLineComments"), 4}, - {"\n//line File1.go:100\n line100", filepath.Join("dir", "File1.go"), 100}, - {"\n//line File2.go:200\n line200", filepath.Join("dir", "File2.go"), 200}, - {"\n//line :1\n line1", "dir", 1}, - {"\n//line foo:42\n line42", filepath.Join("dir", "foo"), 42}, - {"\n //line foo:42\n line44", filepath.Join("dir", "foo"), 44}, // bad line comment, ignored - {"\n//line foo 42\n line46", filepath.Join("dir", "foo"), 46}, // bad line comment, ignored - {"\n//line foo:42 extra text\n line48", filepath.Join("dir", "foo"), 48}, // bad line comment, ignored - {"\n//line ./foo:42\n line42", filepath.Join("dir", "foo"), 42}, - {"\n//line a/b/c/File1.go:100\n line100", filepath.Join("dir", "a", "b", "c", "File1.go"), 100}, -} - -var unixsegments = []segment{ - {"\n//line /bar:42\n line42", "/bar", 42}, -} - -var winsegments = []segment{ - {"\n//line c:\\bar:42\n line42", "c:\\bar", 42}, - {"\n//line c:\\dir\\File1.go:100\n line100", "c:\\dir\\File1.go", 100}, -} - -// Verify that comments of the form "//line filename:line" are interpreted correctly. -func TestLineComments(t *testing.T) { - segs := segments - if runtime.GOOS == "windows" { - segs = append(segs, winsegments...) - } else { - segs = append(segs, unixsegments...) - } - - // make source - var src string - for _, e := range segs { - src += e.srcline - } - - // verify scan - var S Scanner - file := fset.AddFile(filepath.Join("dir", "TestLineComments"), fset.Base(), len(src)) - S.Init(file, []byte(src), nil, dontInsertSemis) - for _, s := range segs { - p, _, lit := S.Scan() - pos := file.Position(p) - checkPos(t, lit, p, token.Position{ - Filename: s.filename, - Offset: pos.Offset, - Line: s.line, - Column: pos.Column, - }) - } - - if S.ErrorCount != 0 { - t.Errorf("found %d errors", S.ErrorCount) - } -} - -// Verify that initializing the same scanner more than once works correctly. -func TestInit(t *testing.T) { - var s Scanner - - // 1st init - src1 := "if true { }" - f1 := fset.AddFile("src1", fset.Base(), len(src1)) - s.Init(f1, []byte(src1), nil, dontInsertSemis) - if f1.Size() != len(src1) { - t.Errorf("bad file size: got %d, expected %d", f1.Size(), len(src1)) - } - s.Scan() // if - s.Scan() // true - _, tok, _ := s.Scan() // { - if tok != token.LBRACE { - t.Errorf("bad token: got %s, expected %s", tok, token.LBRACE) - } - - // 2nd init - src2 := "go true { ]" - f2 := fset.AddFile("src2", fset.Base(), len(src2)) - s.Init(f2, []byte(src2), nil, dontInsertSemis) - if f2.Size() != len(src2) { - t.Errorf("bad file size: got %d, expected %d", f2.Size(), len(src2)) - } - _, tok, _ = s.Scan() // go - if tok != token.GO { - t.Errorf("bad token: got %s, expected %s", tok, token.GO) - } - - if s.ErrorCount != 0 { - t.Errorf("found %d errors", s.ErrorCount) - } -} - -func TestStdErrorHander(t *testing.T) { - 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 - "//line File2:1\n" + - "@ @\n" + // same file, decreasing line number - "//line File1:1\n" + - "@ @ @" // original file, line 1 again - - var list ErrorList - eh := func(pos token.Position, msg string) { list.Add(pos, msg) } - - var s Scanner - s.Init(fset.AddFile("File1", fset.Base(), len(src)), []byte(src), eh, dontInsertSemis) - for { - if _, tok, _ := s.Scan(); tok == token.EOF { - break - } - } - - if len(list) != s.ErrorCount { - t.Errorf("found %d errors, expected %d", len(list), s.ErrorCount) - } - - if len(list) != 9 { - t.Errorf("found %d raw errors, expected 9", len(list)) - PrintError(os.Stderr, list) - } - - list.Sort() - if len(list) != 9 { - t.Errorf("found %d sorted errors, expected 9", len(list)) - PrintError(os.Stderr, list) - } - - list.RemoveMultiples() - if len(list) != 4 { - t.Errorf("found %d one-per-line errors, expected 4", len(list)) - PrintError(os.Stderr, list) - } -} - -type errorCollector struct { - cnt int // number of errors encountered - msg string // last error message encountered - pos token.Position // last error position encountered -} - -func checkError(t *testing.T, src string, tok token.Token, pos int, err string) { - var s Scanner - var h errorCollector - eh := func(pos token.Position, msg string) { - h.cnt++ - h.msg = msg - h.pos = pos - } - s.Init(fset.AddFile("", fset.Base(), len(src)), []byte(src), eh, ScanComments|dontInsertSemis) - _, tok0, _ := s.Scan() - _, tok1, _ := s.Scan() - if tok0 != tok { - t.Errorf("%q: got %s, expected %s", src, tok0, tok) - } - if tok1 != token.EOF { - t.Errorf("%q: got %s, expected EOF", src, tok1) - } - cnt := 0 - if err != "" { - cnt = 1 - } - if h.cnt != cnt { - t.Errorf("%q: got cnt %d, expected %d", src, h.cnt, cnt) - } - if h.msg != err { - t.Errorf("%q: got msg %q, expected %q", src, h.msg, err) - } - if h.pos.Offset != pos { - t.Errorf("%q: got offset %d, expected %d", src, h.pos.Offset, pos) - } -} - -var errors = []struct { - src string - tok token.Token - pos int - err string -}{ - {"\a", token.ILLEGAL, 0, "illegal character U+0007"}, - {`#`, token.ILLEGAL, 0, "illegal character U+0023 '#'"}, - {`…`, token.ILLEGAL, 0, "illegal character U+2026 '…'"}, - {`' '`, token.CHAR, 0, ""}, - {`''`, token.CHAR, 0, "illegal character literal"}, - {`'\8'`, token.CHAR, 2, "unknown escape sequence"}, - {`'\08'`, token.CHAR, 3, "illegal character in escape sequence"}, - {`'\x0g'`, token.CHAR, 4, "illegal character in escape sequence"}, - {`'\Uffffffff'`, token.CHAR, 2, "escape sequence is invalid Unicode code point"}, - {`'`, token.CHAR, 0, "character literal not terminated"}, - {`""`, token.STRING, 0, ""}, - {`"`, token.STRING, 0, "string not terminated"}, - {"``", token.STRING, 0, ""}, - {"`", token.STRING, 0, "string not terminated"}, - {"/**/", token.COMMENT, 0, ""}, - {"/*", token.COMMENT, 0, "comment not terminated"}, - {"077", token.INT, 0, ""}, - {"078.", token.FLOAT, 0, ""}, - {"07801234567.", token.FLOAT, 0, ""}, - {"078e0", token.FLOAT, 0, ""}, - {"078", token.INT, 0, "illegal octal number"}, - {"07800000009", token.INT, 0, "illegal octal number"}, - {"0x", token.INT, 0, "illegal hexadecimal number"}, - {"0X", token.INT, 0, "illegal hexadecimal number"}, - {"\"abc\x00def\"", token.STRING, 4, "illegal character NUL"}, - {"\"abc\x80def\"", token.STRING, 4, "illegal UTF-8 encoding"}, - {"\ufeff\ufeff", token.ILLEGAL, 3, "illegal character U+FEFF"}, // only first BOM is ignored -} - -func TestScanErrors(t *testing.T) { - for _, e := range errors { - checkError(t, e.src, e.tok, e.pos, e.err) - } -} - -func BenchmarkScan(b *testing.B) { - b.StopTimer() - fset := token.NewFileSet() - file := fset.AddFile("", fset.Base(), len(source)) - var s Scanner - b.StartTimer() - for i := 0; i < b.N; i++ { - s.Init(file, source, nil, ScanComments) - for { - _, tok, _ := s.Scan() - if tok == token.EOF { - break - } - } - } -} - -func BenchmarkScanFile(b *testing.B) { - b.StopTimer() - const filename = "scanner.go" - src, err := ioutil.ReadFile(filename) - if err != nil { - panic(err) - } - fset := token.NewFileSet() - file := fset.AddFile(filename, fset.Base(), len(src)) - b.SetBytes(int64(len(src))) - var s Scanner - b.StartTimer() - for i := 0; i < b.N; i++ { - s.Init(file, src, nil, ScanComments) - for { - _, tok, _ := s.Scan() - if tok == token.EOF { - break - } - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/token/position.go b/gcc-4.8.1/libgo/go/go/token/position.go deleted file mode 100644 index f5d999561..000000000 --- a/gcc-4.8.1/libgo/go/go/token/position.go +++ /dev/null @@ -1,437 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// TODO(gri) consider making this a separate package outside the go directory. - -package token - -import ( - "fmt" - "sort" - "sync" -) - -// ----------------------------------------------------------------------------- -// Positions - -// Position describes an arbitrary source position -// including the file, line, and column location. -// A Position is valid if the line number is > 0. -// -type Position struct { - Filename string // filename, if any - Offset int // offset, starting at 0 - Line int // line number, starting at 1 - Column int // column number, starting at 1 (character count) -} - -// IsValid returns true if the position is valid. -func (pos *Position) IsValid() bool { return pos.Line > 0 } - -// String returns a string in one of several forms: -// -// file:line:column valid position with file name -// line:column valid position without file name -// file invalid position with file name -// - invalid position without file name -// -func (pos Position) String() string { - s := pos.Filename - if pos.IsValid() { - if s != "" { - s += ":" - } - s += fmt.Sprintf("%d:%d", pos.Line, pos.Column) - } - if s == "" { - s = "-" - } - return s -} - -// Pos is a compact encoding of a source position within a file set. -// It can be converted into a Position for a more convenient, but much -// larger, representation. -// -// The Pos value for a given file is a number in the range [base, base+size], -// where base and size are specified when adding the file to the file set via -// AddFile. -// -// To create the Pos value for a specific source offset, first add -// the respective file to the current file set (via FileSet.AddFile) -// and then call File.Pos(offset) for that file. Given a Pos value p -// for a specific file set fset, the corresponding Position value is -// obtained by calling fset.Position(p). -// -// Pos values can be compared directly with the usual comparison operators: -// If two Pos values p and q are in the same file, comparing p and q is -// equivalent to comparing the respective source file offsets. If p and q -// are in different files, p < q is true if the file implied by p was added -// to the respective file set before the file implied by q. -// -type Pos int - -// The zero value for Pos is NoPos; there is no file and line information -// associated with it, and NoPos().IsValid() is false. NoPos is always -// smaller than any other Pos value. The corresponding Position value -// for NoPos is the zero value for Position. -// -const NoPos Pos = 0 - -// IsValid returns true if the position is valid. -func (p Pos) IsValid() bool { - return p != NoPos -} - -// ----------------------------------------------------------------------------- -// File - -// A File is a handle for a file belonging to a FileSet. -// A File has a name, size, and line offset table. -// -type File struct { - set *FileSet - name string // file name as provided to AddFile - base int // Pos value range for this file is [base...base+size] - size int // file size as provided to AddFile - - // lines and infos are protected by set.mutex - lines []int - infos []lineInfo -} - -// Name returns the file name of file f as registered with AddFile. -func (f *File) Name() string { - return f.name -} - -// Base returns the base offset of file f as registered with AddFile. -func (f *File) Base() int { - return f.base -} - -// Size returns the size of file f as registered with AddFile. -func (f *File) Size() int { - return f.size -} - -// LineCount returns the number of lines in file f. -func (f *File) LineCount() int { - f.set.mutex.RLock() - n := len(f.lines) - f.set.mutex.RUnlock() - return n -} - -// AddLine adds the line offset for a new line. -// The line offset must be larger than the offset for the previous line -// and smaller than the file size; otherwise the line offset is ignored. -// -func (f *File) AddLine(offset int) { - f.set.mutex.Lock() - if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size { - f.lines = append(f.lines, offset) - } - f.set.mutex.Unlock() -} - -// SetLines sets the line offsets for a file and returns true if successful. -// The line offsets are the offsets of the first character of each line; -// for instance for the content "ab\nc\n" the line offsets are {0, 3}. -// An empty file has an empty line offset table. -// Each line offset must be larger than the offset for the previous line -// and smaller than the file size; otherwise SetLines fails and returns -// false. -// -func (f *File) SetLines(lines []int) bool { - // verify validity of lines table - size := f.size - for i, offset := range lines { - if i > 0 && offset <= lines[i-1] || size <= offset { - return false - } - } - - // set lines table - f.set.mutex.Lock() - f.lines = lines - f.set.mutex.Unlock() - return true -} - -// SetLinesForContent sets the line offsets for the given file content. -func (f *File) SetLinesForContent(content []byte) { - var lines []int - line := 0 - for offset, b := range content { - if line >= 0 { - lines = append(lines, line) - } - line = -1 - if b == '\n' { - line = offset + 1 - } - } - - // set lines table - f.set.mutex.Lock() - f.lines = lines - f.set.mutex.Unlock() -} - -// A lineInfo object describes alternative file and line number -// information (such as provided via a //line comment in a .go -// file) for a given file offset. -type lineInfo struct { - // fields are exported to make them accessible to gob - Offset int - Filename string - Line int -} - -// AddLineInfo adds alternative file and line number information for -// a given file offset. The offset must be larger than the offset for -// the previously added alternative line info and smaller than the -// file size; otherwise the information is ignored. -// -// AddLineInfo is typically used to register alternative position -// information for //line filename:line comments in source files. -// -func (f *File) AddLineInfo(offset int, filename string, line int) { - f.set.mutex.Lock() - if i := len(f.infos); i == 0 || f.infos[i-1].Offset < offset && offset < f.size { - f.infos = append(f.infos, lineInfo{offset, filename, line}) - } - f.set.mutex.Unlock() -} - -// Pos returns the Pos value for the given file offset; -// the offset must be <= f.Size(). -// f.Pos(f.Offset(p)) == p. -// -func (f *File) Pos(offset int) Pos { - if offset > f.size { - panic("illegal file offset") - } - return Pos(f.base + offset) -} - -// Offset returns the offset for the given file position p; -// p must be a valid Pos value in that file. -// f.Offset(f.Pos(offset)) == offset. -// -func (f *File) Offset(p Pos) int { - if int(p) < f.base || int(p) > f.base+f.size { - panic("illegal Pos value") - } - return int(p) - f.base -} - -// Line returns the line number for the given file position p; -// p must be a Pos value in that file or NoPos. -// -func (f *File) Line(p Pos) int { - // TODO(gri) this can be implemented much more efficiently - return f.Position(p).Line -} - -func searchLineInfos(a []lineInfo, x int) int { - return sort.Search(len(a), func(i int) bool { return a[i].Offset > x }) - 1 -} - -// info returns the file name, line, and column number for a file offset. -func (f *File) info(offset int) (filename string, line, column int) { - filename = f.name - if i := searchInts(f.lines, offset); i >= 0 { - line, column = i+1, offset-f.lines[i]+1 - } - if len(f.infos) > 0 { - // almost no files have extra line infos - if i := searchLineInfos(f.infos, offset); i >= 0 { - alt := &f.infos[i] - filename = alt.Filename - if i := searchInts(f.lines, alt.Offset); i >= 0 { - line += alt.Line - i - 1 - } - } - } - return -} - -func (f *File) position(p Pos) (pos Position) { - offset := int(p) - f.base - pos.Offset = offset - pos.Filename, pos.Line, pos.Column = f.info(offset) - return -} - -// Position returns the Position value for the given file position p; -// p must be a Pos value in that file or NoPos. -// -func (f *File) Position(p Pos) (pos Position) { - if p != NoPos { - if int(p) < f.base || int(p) > f.base+f.size { - panic("illegal Pos value") - } - pos = f.position(p) - } - return -} - -// ----------------------------------------------------------------------------- -// FileSet - -// A FileSet represents a set of source files. -// Methods of file sets are synchronized; multiple goroutines -// may invoke them concurrently. -// -type FileSet struct { - mutex sync.RWMutex // protects the file set - base int // base offset for the next file - files []*File // list of files in the order added to the set - last *File // cache of last file looked up -} - -// NewFileSet creates a new file set. -func NewFileSet() *FileSet { - return &FileSet{ - base: 1, // 0 == NoPos - } -} - -// Base returns the minimum base offset that must be provided to -// AddFile when adding the next file. -// -func (s *FileSet) Base() int { - s.mutex.RLock() - b := s.base - s.mutex.RUnlock() - return b - -} - -// AddFile adds a new file with a given filename, base offset, and file size -// to the file set s and returns the file. Multiple files may have the same -// name. The base offset must not be smaller than the FileSet's Base(), and -// size must not be negative. -// -// Adding the file will set the file set's Base() value to base + size + 1 -// as the minimum base value for the next file. The following relationship -// exists between a Pos value p for a given file offset offs: -// -// int(p) = base + offs -// -// with offs in the range [0, size] and thus p in the range [base, base+size]. -// For convenience, File.Pos may be used to create file-specific position -// values from a file offset. -// -func (s *FileSet) AddFile(filename string, base, size int) *File { - s.mutex.Lock() - defer s.mutex.Unlock() - if base < s.base || size < 0 { - panic("illegal base or size") - } - // base >= s.base && size >= 0 - f := &File{s, filename, base, size, []int{0}, nil} - base += size + 1 // +1 because EOF also has a position - if base < 0 { - panic("token.Pos offset overflow (> 2G of source code in file set)") - } - // add the file to the file set - s.base = base - s.files = append(s.files, f) - s.last = f - return f -} - -// Iterate calls f for the files in the file set in the order they were added -// until f returns false. -// -func (s *FileSet) Iterate(f func(*File) bool) { - for i := 0; ; i++ { - var file *File - s.mutex.RLock() - if i < len(s.files) { - file = s.files[i] - } - s.mutex.RUnlock() - if file == nil || !f(file) { - break - } - } -} - -func searchFiles(a []*File, x int) int { - return sort.Search(len(a), func(i int) bool { return a[i].base > x }) - 1 -} - -func (s *FileSet) file(p Pos) *File { - s.mutex.RLock() - // common case: p is in last file - if f := s.last; f != nil && f.base <= int(p) && int(p) <= f.base+f.size { - s.mutex.RUnlock() - return f - } - // p is not in last file - search all files - if i := searchFiles(s.files, int(p)); i >= 0 { - f := s.files[i] - // f.base <= int(p) by definition of searchFiles - if int(p) <= f.base+f.size { - s.mutex.RUnlock() - s.mutex.Lock() - s.last = f // race is ok - s.last is only a cache - s.mutex.Unlock() - return f - } - } - s.mutex.RUnlock() - return nil -} - -// File returns the file that contains the position p. -// If no such file is found (for instance for p == NoPos), -// the result is nil. -// -func (s *FileSet) File(p Pos) (f *File) { - if p != NoPos { - f = s.file(p) - } - return -} - -// Position converts a Pos in the fileset into a general Position. -func (s *FileSet) Position(p Pos) (pos Position) { - if p != NoPos { - if f := s.file(p); f != nil { - pos = f.position(p) - } - } - return -} - -// ----------------------------------------------------------------------------- -// Helper functions - -func searchInts(a []int, x int) int { - // This function body is a manually inlined version of: - // - // return sort.Search(len(a), func(i int) bool { return a[i] > x }) - 1 - // - // With better compiler optimizations, this may not be needed in the - // future, but at the moment this change improves the go/printer - // benchmark performance by ~30%. This has a direct impact on the - // speed of gofmt and thus seems worthwhile (2011-04-29). - // TODO(gri): Remove this when compilers have caught up. - i, j := 0, len(a) - for i < j { - h := i + (j-i)/2 // avoid overflow when computing h - // i ≤ h < j - if a[h] <= x { - i = h + 1 - } else { - j = h - } - } - return i - 1 -} diff --git a/gcc-4.8.1/libgo/go/go/token/position_test.go b/gcc-4.8.1/libgo/go/go/token/position_test.go deleted file mode 100644 index 1d36c2226..000000000 --- a/gcc-4.8.1/libgo/go/go/token/position_test.go +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package token - -import ( - "fmt" - "math/rand" - "sync" - "testing" -) - -func checkPos(t *testing.T, msg string, p, q Position) { - if p.Filename != q.Filename { - t.Errorf("%s: expected filename = %q; got %q", msg, q.Filename, p.Filename) - } - if p.Offset != q.Offset { - t.Errorf("%s: expected offset = %d; got %d", msg, q.Offset, p.Offset) - } - if p.Line != q.Line { - t.Errorf("%s: expected line = %d; got %d", msg, q.Line, p.Line) - } - if p.Column != q.Column { - t.Errorf("%s: expected column = %d; got %d", msg, q.Column, p.Column) - } -} - -func TestNoPos(t *testing.T) { - if NoPos.IsValid() { - t.Errorf("NoPos should not be valid") - } - var fset *FileSet - checkPos(t, "nil NoPos", fset.Position(NoPos), Position{}) - fset = NewFileSet() - checkPos(t, "fset NoPos", fset.Position(NoPos), Position{}) -} - -var tests = []struct { - filename string - source []byte // may be nil - size int - lines []int -}{ - {"a", []byte{}, 0, []int{}}, - {"b", []byte("01234"), 5, []int{0}}, - {"c", []byte("\n\n\n\n\n\n\n\n\n"), 9, []int{0, 1, 2, 3, 4, 5, 6, 7, 8}}, - {"d", nil, 100, []int{0, 5, 10, 20, 30, 70, 71, 72, 80, 85, 90, 99}}, - {"e", nil, 777, []int{0, 80, 100, 120, 130, 180, 267, 455, 500, 567, 620}}, - {"f", []byte("package p\n\nimport \"fmt\""), 23, []int{0, 10, 11}}, - {"g", []byte("package p\n\nimport \"fmt\"\n"), 24, []int{0, 10, 11}}, - {"h", []byte("package p\n\nimport \"fmt\"\n "), 25, []int{0, 10, 11, 24}}, -} - -func linecol(lines []int, offs int) (int, int) { - prevLineOffs := 0 - for line, lineOffs := range lines { - if offs < lineOffs { - return line, offs - prevLineOffs + 1 - } - prevLineOffs = lineOffs - } - return len(lines), offs - prevLineOffs + 1 -} - -func verifyPositions(t *testing.T, fset *FileSet, f *File, lines []int) { - for offs := 0; offs < f.Size(); offs++ { - p := f.Pos(offs) - offs2 := f.Offset(p) - if offs2 != offs { - t.Errorf("%s, Offset: expected offset %d; got %d", f.Name(), offs, offs2) - } - line, col := linecol(lines, offs) - msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) - checkPos(t, msg, f.Position(f.Pos(offs)), Position{f.Name(), offs, line, col}) - checkPos(t, msg, fset.Position(p), Position{f.Name(), offs, line, col}) - } -} - -func makeTestSource(size int, lines []int) []byte { - src := make([]byte, size) - for _, offs := range lines { - if offs > 0 { - src[offs-1] = '\n' - } - } - return src -} - -func TestPositions(t *testing.T) { - const delta = 7 // a non-zero base offset increment - fset := NewFileSet() - for _, test := range tests { - // verify consistency of test case - if test.source != nil && len(test.source) != test.size { - t.Errorf("%s: inconsistent test case: expected file size %d; got %d", test.filename, test.size, len(test.source)) - } - - // add file and verify name and size - f := fset.AddFile(test.filename, fset.Base()+delta, test.size) - if f.Name() != test.filename { - t.Errorf("expected filename %q; got %q", test.filename, f.Name()) - } - if f.Size() != test.size { - t.Errorf("%s: expected file size %d; got %d", f.Name(), test.size, f.Size()) - } - if fset.File(f.Pos(0)) != f { - t.Errorf("%s: f.Pos(0) was not found in f", f.Name()) - } - - // add lines individually and verify all positions - for i, offset := range test.lines { - f.AddLine(offset) - if f.LineCount() != i+1 { - t.Errorf("%s, AddLine: expected line count %d; got %d", f.Name(), i+1, f.LineCount()) - } - // adding the same offset again should be ignored - f.AddLine(offset) - if f.LineCount() != i+1 { - t.Errorf("%s, AddLine: expected unchanged line count %d; got %d", f.Name(), i+1, f.LineCount()) - } - verifyPositions(t, fset, f, test.lines[0:i+1]) - } - - // add lines with SetLines and verify all positions - if ok := f.SetLines(test.lines); !ok { - t.Errorf("%s: SetLines failed", f.Name()) - } - if f.LineCount() != len(test.lines) { - t.Errorf("%s, SetLines: expected line count %d; got %d", f.Name(), len(test.lines), f.LineCount()) - } - verifyPositions(t, fset, f, test.lines) - - // add lines with SetLinesForContent and verify all positions - src := test.source - if src == nil { - // no test source available - create one from scratch - src = makeTestSource(test.size, test.lines) - } - f.SetLinesForContent(src) - if f.LineCount() != len(test.lines) { - t.Errorf("%s, SetLinesForContent: expected line count %d; got %d", f.Name(), len(test.lines), f.LineCount()) - } - verifyPositions(t, fset, f, test.lines) - } -} - -func TestLineInfo(t *testing.T) { - fset := NewFileSet() - f := fset.AddFile("foo", fset.Base(), 500) - lines := []int{0, 42, 77, 100, 210, 220, 277, 300, 333, 401} - // add lines individually and provide alternative line information - for _, offs := range lines { - f.AddLine(offs) - f.AddLineInfo(offs, "bar", 42) - } - // verify positions for all offsets - for offs := 0; offs <= f.Size(); offs++ { - p := f.Pos(offs) - _, col := linecol(lines, offs) - msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) - checkPos(t, msg, f.Position(f.Pos(offs)), Position{"bar", offs, 42, col}) - checkPos(t, msg, fset.Position(p), Position{"bar", offs, 42, col}) - } -} - -func TestFiles(t *testing.T) { - fset := NewFileSet() - for i, test := range tests { - fset.AddFile(test.filename, fset.Base(), test.size) - j := 0 - fset.Iterate(func(f *File) bool { - if f.Name() != tests[j].filename { - t.Errorf("expected filename = %s; got %s", tests[j].filename, f.Name()) - } - j++ - return true - }) - if j != i+1 { - t.Errorf("expected %d files; got %d", i+1, j) - } - } -} - -// FileSet.File should return nil if Pos is past the end of the FileSet. -func TestFileSetPastEnd(t *testing.T) { - fset := NewFileSet() - for _, test := range tests { - fset.AddFile(test.filename, fset.Base(), test.size) - } - if f := fset.File(Pos(fset.Base())); f != nil { - t.Errorf("expected nil, got %v", f) - } -} - -func TestFileSetCacheUnlikely(t *testing.T) { - fset := NewFileSet() - offsets := make(map[string]int) - for _, test := range tests { - offsets[test.filename] = fset.Base() - fset.AddFile(test.filename, fset.Base(), test.size) - } - for file, pos := range offsets { - f := fset.File(Pos(pos)) - if f.Name() != file { - t.Errorf("expecting %q at position %d, got %q", file, pos, f.Name()) - } - } -} - -// issue 4345. Test concurrent use of FileSet.Pos does not trigger a -// race in the FileSet position cache. -func TestFileSetRace(t *testing.T) { - fset := NewFileSet() - for i := 0; i < 100; i++ { - fset.AddFile(fmt.Sprintf("file-%d", i), fset.Base(), 1031) - } - max := int32(fset.Base()) - var stop sync.WaitGroup - r := rand.New(rand.NewSource(7)) - for i := 0; i < 2; i++ { - r := rand.New(rand.NewSource(r.Int63())) - stop.Add(1) - go func() { - for i := 0; i < 1000; i++ { - fset.Position(Pos(r.Int31n(max))) - } - stop.Done() - }() - } - stop.Wait() -} diff --git a/gcc-4.8.1/libgo/go/go/token/serialize.go b/gcc-4.8.1/libgo/go/go/token/serialize.go deleted file mode 100644 index 4adc8f9e3..000000000 --- a/gcc-4.8.1/libgo/go/go/token/serialize.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package token - -type serializedFile struct { - // fields correspond 1:1 to fields with same (lower-case) name in File - Name string - Base int - Size int - Lines []int - Infos []lineInfo -} - -type serializedFileSet struct { - Base int - Files []serializedFile -} - -// Read calls decode to deserialize a file set into s; s must not be nil. -func (s *FileSet) Read(decode func(interface{}) error) error { - var ss serializedFileSet - if err := decode(&ss); err != nil { - return err - } - - s.mutex.Lock() - s.base = ss.Base - files := make([]*File, len(ss.Files)) - for i := 0; i < len(ss.Files); i++ { - f := &ss.Files[i] - files[i] = &File{s, f.Name, f.Base, f.Size, f.Lines, f.Infos} - } - s.files = files - s.last = nil - s.mutex.Unlock() - - return nil -} - -// Write calls encode to serialize the file set s. -func (s *FileSet) Write(encode func(interface{}) error) error { - var ss serializedFileSet - - s.mutex.Lock() - ss.Base = s.base - files := make([]serializedFile, len(s.files)) - for i, f := range s.files { - files[i] = serializedFile{f.name, f.base, f.size, f.lines, f.infos} - } - ss.Files = files - s.mutex.Unlock() - - return encode(ss) -} diff --git a/gcc-4.8.1/libgo/go/go/token/serialize_test.go b/gcc-4.8.1/libgo/go/go/token/serialize_test.go deleted file mode 100644 index 4e925adb6..000000000 --- a/gcc-4.8.1/libgo/go/go/token/serialize_test.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package token - -import ( - "bytes" - "encoding/gob" - "fmt" - "testing" -) - -// equal returns nil if p and q describe the same file set; -// otherwise it returns an error describing the discrepancy. -func equal(p, q *FileSet) error { - if p == q { - // avoid deadlock if p == q - return nil - } - - // not strictly needed for the test - p.mutex.Lock() - q.mutex.Lock() - defer q.mutex.Unlock() - defer p.mutex.Unlock() - - if p.base != q.base { - return fmt.Errorf("different bases: %d != %d", p.base, q.base) - } - - if len(p.files) != len(q.files) { - return fmt.Errorf("different number of files: %d != %d", len(p.files), len(q.files)) - } - - for i, f := range p.files { - g := q.files[i] - if f.set != p { - return fmt.Errorf("wrong fileset for %q", f.name) - } - if g.set != q { - return fmt.Errorf("wrong fileset for %q", g.name) - } - if f.name != g.name { - return fmt.Errorf("different filenames: %q != %q", f.name, g.name) - } - if f.base != g.base { - return fmt.Errorf("different base for %q: %d != %d", f.name, f.base, g.base) - } - if f.size != g.size { - return fmt.Errorf("different size for %q: %d != %d", f.name, f.size, g.size) - } - for j, l := range f.lines { - m := g.lines[j] - if l != m { - return fmt.Errorf("different offsets for %q", f.name) - } - } - for j, l := range f.infos { - m := g.infos[j] - if l.Offset != m.Offset || l.Filename != m.Filename || l.Line != m.Line { - return fmt.Errorf("different infos for %q", f.name) - } - } - } - - // we don't care about .last - it's just a cache - return nil -} - -func checkSerialize(t *testing.T, p *FileSet) { - var buf bytes.Buffer - encode := func(x interface{}) error { - return gob.NewEncoder(&buf).Encode(x) - } - if err := p.Write(encode); err != nil { - t.Errorf("writing fileset failed: %s", err) - return - } - q := NewFileSet() - decode := func(x interface{}) error { - return gob.NewDecoder(&buf).Decode(x) - } - if err := q.Read(decode); err != nil { - t.Errorf("reading fileset failed: %s", err) - return - } - if err := equal(p, q); err != nil { - t.Errorf("filesets not identical: %s", err) - } -} - -func TestSerialization(t *testing.T) { - p := NewFileSet() - checkSerialize(t, p) - // add some files - for i := 0; i < 10; i++ { - f := p.AddFile(fmt.Sprintf("file%d", i), p.Base()+i, i*100) - checkSerialize(t, p) - // add some lines and alternative file infos - line := 1000 - for offs := 0; offs < f.Size(); offs += 40 + i { - f.AddLine(offs) - if offs%7 == 0 { - f.AddLineInfo(offs, fmt.Sprintf("file%d", offs), line) - line += 33 - } - } - checkSerialize(t, p) - } -} diff --git a/gcc-4.8.1/libgo/go/go/token/token.go b/gcc-4.8.1/libgo/go/go/token/token.go deleted file mode 100644 index 84b6314d5..000000000 --- a/gcc-4.8.1/libgo/go/go/token/token.go +++ /dev/null @@ -1,308 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package token defines constants representing the lexical tokens of the Go -// programming language and basic operations on tokens (printing, predicates). -// -package token - -import "strconv" - -// Token is the set of lexical tokens of the Go programming language. -type Token int - -// The list of tokens. -const ( - // Special tokens - ILLEGAL Token = iota - EOF - COMMENT - - literal_beg - // Identifiers and basic type literals - // (these tokens stand for classes of literals) - IDENT // main - INT // 12345 - FLOAT // 123.45 - IMAG // 123.45i - 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 - // 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 -) - -var tokens = [...]string{ - ILLEGAL: "ILLEGAL", - - EOF: "EOF", - COMMENT: "COMMENT", - - IDENT: "IDENT", - INT: "INT", - FLOAT: "FLOAT", - IMAG: "IMAG", - CHAR: "CHAR", - STRING: "STRING", - - 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: ":", - - BREAK: "break", - CASE: "case", - CHAN: "chan", - CONST: "const", - CONTINUE: "continue", - - DEFAULT: "default", - DEFER: "defer", - ELSE: "else", - FALLTHROUGH: "fallthrough", - FOR: "for", - - FUNC: "func", - GO: "go", - GOTO: "goto", - IF: "if", - IMPORT: "import", - - INTERFACE: "interface", - MAP: "map", - PACKAGE: "package", - RANGE: "range", - RETURN: "return", - - SELECT: "select", - STRUCT: "struct", - SWITCH: "switch", - TYPE: "type", - VAR: "var", -} - -// String returns the string corresponding to the token tok. -// For operators, delimiters, and keywords the string is the actual -// token character sequence (e.g., for the token ADD, the string is -// "+"). For all other tokens the string corresponds to the token -// constant name (e.g. for the token IDENT, the string is "IDENT"). -// -func (tok Token) String() string { - s := "" - if 0 <= tok && tok < Token(len(tokens)) { - s = tokens[tok] - } - if s == "" { - s = "token(" + strconv.Itoa(int(tok)) + ")" - } - return s -} - -// A set of constants for precedence-based expression parsing. -// Non-operators have lowest precedence, followed by operators -// starting with precedence 1 up to unary operators. The highest -// precedence corresponds serves as "catch-all" precedence for -// selector, indexing, and other operator and delimiter tokens. -// -const ( - LowestPrec = 0 // non-operators - UnaryPrec = 6 - HighestPrec = 7 -) - -// Precedence returns the operator precedence of the binary -// operator op. If op is not a binary operator, the result -// is LowestPrecedence. -// -func (op Token) Precedence() int { - switch op { - case LOR: - return 1 - case LAND: - return 2 - case EQL, NEQ, LSS, LEQ, GTR, GEQ: - return 3 - case ADD, SUB, OR, XOR: - return 4 - case MUL, QUO, REM, SHL, SHR, AND, AND_NOT: - return 5 - } - return LowestPrec -} - -var keywords map[string]Token - -func init() { - keywords = make(map[string]Token) - for i := keyword_beg + 1; i < keyword_end; i++ { - keywords[tokens[i]] = i - } -} - -// Lookup maps an identifier to its keyword token or IDENT (if not a keyword). -// -func Lookup(ident string) Token { - if tok, is_keyword := keywords[ident]; is_keyword { - return tok - } - return IDENT -} - -// Predicates - -// IsLiteral returns true for tokens corresponding to identifiers -// and basic type literals; it returns false otherwise. -// -func (tok Token) IsLiteral() bool { return literal_beg < tok && tok < literal_end } - -// IsOperator returns true for tokens corresponding to operators and -// delimiters; it returns false otherwise. -// -func (tok Token) IsOperator() bool { return operator_beg < tok && tok < operator_end } - -// IsKeyword returns true for tokens corresponding to keywords; -// it returns false otherwise. -// -func (tok Token) IsKeyword() bool { return keyword_beg < tok && tok < keyword_end } diff --git a/gcc-4.8.1/libgo/go/go/types/api.go b/gcc-4.8.1/libgo/go/go/types/api.go deleted file mode 100644 index e5b6aa12c..000000000 --- a/gcc-4.8.1/libgo/go/go/types/api.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package types declares the data structures for representing -// Go types and implements typechecking of package files. -// -// WARNING: THE TYPES API IS SUBJECT TO CHANGE. -// -package types - -import ( - "go/ast" - "go/token" -) - -// A Context specifies the supporting context for type checking. -type Context struct { - IntSize int64 // size in bytes of int and uint values - PtrSize int64 // size in bytes of pointers - - // If Error is not nil, it is called with each error found - // during type checking. Most error messages have accurate - // position information; those error strings are formatted - // filename:line:column: message. - Error func(err error) - - // If Ident is not nil, it is called for each identifier id - // denoting an Object in the files provided to Check, and - // obj is the denoted object. - // Ident is not called for fields and methods in struct or - // interface types or composite literals, or for blank (_) - // or dot (.) identifiers in dot-imports. - // TODO(gri) Consider making Fields and Methods ordinary - // Objects - than we could lift this restriction. - Ident func(id *ast.Ident, obj Object) - - // If Expr is not nil, it is called for each expression x that is - // type-checked: typ is the expression type, and val is the value - // if x is constant, val is nil otherwise. - // - // Constants are represented as follows: - // - // bool -> bool - // numeric -> int64, *big.Int, *big.Rat, Complex - // string -> string - // nil -> NilType - // - // Constant values are normalized, that is, they are represented - // using the "smallest" possible type that can represent the value. - // For instance, 1.0 is represented as an int64 because it can be - // represented accurately as an int64. - Expr func(x ast.Expr, typ Type, val interface{}) - - // If Import is not nil, it is used instead of GcImport. - Import Importer -} - -// An Importer resolves import paths to Package objects. -// The imports map records the packages already imported, -// indexed by package id (canonical import path). -// An Importer must determine the canonical import path and -// check the map to see if it is already present in the imports map. -// If so, the Importer can return the map entry. Otherwise, the -// Importer should load the package data for the given path into -// a new *Package, record pkg in the imports map, and then -// return pkg. -type Importer func(imports map[string]*Package, path string) (pkg *Package, err error) - -// Default is the default context for type checking. -var Default = Context{ - // TODO(gri) Perhaps this should depend on GOARCH? - IntSize: 8, - PtrSize: 8, -} - -// Check resolves and typechecks a set of package files within the given -// context. The package files' ASTs are augmented by assigning types to -// ast.Objects. If there are no errors, Check returns the package, otherwise -// it returns the first error. If the context's Error handler is nil, -// Check terminates as soon as the first error is encountered. -// -// CAUTION: At the moment, the returned *ast.Package only contains the package -// name and scope - the other fields are not set up. The returned -// *Package contains the name and imports (but no scope yet). Once -// we have the scope moved from *ast.Scope to *Scope, only *Package -// will be returned. -// -func (ctxt *Context) Check(fset *token.FileSet, files []*ast.File) (*Package, error) { - return check(ctxt, fset, files) -} - -// Check is shorthand for Default.Check. -func Check(fset *token.FileSet, files []*ast.File) (*Package, error) { - return Default.Check(fset, files) -} diff --git a/gcc-4.8.1/libgo/go/go/types/builtins.go b/gcc-4.8.1/libgo/go/go/types/builtins.go deleted file mode 100644 index 867f1e9c6..000000000 --- a/gcc-4.8.1/libgo/go/go/types/builtins.go +++ /dev/null @@ -1,457 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements typechecking of builtin function calls. - -package types - -import ( - "go/ast" - "go/token" -) - -// builtin typechecks a built-in call. The built-in type is bin, and iota is the current -// value of iota or -1 if iota doesn't have a value in the current context. The result -// of the call is returned via x. If the call has type errors, the returned x is marked -// as invalid (x.mode == invalid). -// -func (check *checker) builtin(x *operand, call *ast.CallExpr, bin *builtin, iota int) { - args := call.Args - id := bin.id - - // declare before goto's - var arg0 ast.Expr // first argument, if present - - // check argument count - n := len(args) - msg := "" - if n < bin.nargs { - msg = "not enough" - } else if !bin.isVariadic && n > bin.nargs { - msg = "too many" - } - if msg != "" { - check.invalidOp(call.Pos(), msg+" arguments for %s (expected %d, found %d)", call, bin.nargs, n) - goto Error - } - - // common case: evaluate first argument if present; - // if it is an expression, x has the expression value - if n > 0 { - arg0 = args[0] - switch id { - case _Make, _New, _Trace: - // respective cases below do the work - default: - // argument must be an expression - check.expr(x, arg0, nil, iota) - if x.mode == invalid { - goto Error - } - } - } - - switch id { - case _Append: - if _, ok := underlying(x.typ).(*Slice); !ok { - check.invalidArg(x.pos(), "%s is not a typed slice", x) - goto Error - } - resultTyp := x.typ - for _, arg := range args[1:] { - check.expr(x, arg, nil, iota) - if x.mode == invalid { - goto Error - } - // TODO(gri) check assignability - } - x.mode = value - x.typ = resultTyp - - case _Cap, _Len: - mode := invalid - var val interface{} - switch typ := implicitDeref(underlying(x.typ)).(type) { - case *Basic: - if isString(typ) && id == _Len { - if x.mode == constant { - mode = constant - val = int64(len(x.val.(string))) - } else { - mode = value - } - } - - case *Array: - mode = value - if !containsCallsOrReceives(arg0) { - mode = constant - val = typ.Len - } - - case *Slice, *Chan: - mode = value - - case *Map: - if id == _Len { - mode = value - } - } - - if mode == invalid { - check.invalidArg(x.pos(), "%s for %s", x, bin.name) - goto Error - } - x.mode = mode - x.typ = Typ[Int] - x.val = val - - case _Close: - ch, ok := underlying(x.typ).(*Chan) - if !ok { - check.invalidArg(x.pos(), "%s is not a channel", x) - goto Error - } - if ch.Dir&ast.SEND == 0 { - check.invalidArg(x.pos(), "%s must not be a receive-only channel", x) - goto Error - } - x.mode = novalue - - case _Complex: - if !check.complexArg(x) { - goto Error - } - - var y operand - check.expr(&y, args[1], nil, iota) - if y.mode == invalid { - goto Error - } - if !check.complexArg(&y) { - goto Error - } - - check.convertUntyped(x, y.typ) - if x.mode == invalid { - goto Error - } - check.convertUntyped(&y, x.typ) - if y.mode == invalid { - goto Error - } - - if !IsIdentical(x.typ, y.typ) { - check.invalidArg(x.pos(), "mismatched types %s and %s", x.typ, y.typ) - goto Error - } - - typ := underlying(x.typ).(*Basic) - if x.mode == constant && y.mode == constant { - x.val = binaryOpConst(x.val, toImagConst(y.val), token.ADD, typ) - } else { - x.mode = value - } - - switch typ.Kind { - case Float32: - x.typ = Typ[Complex64] - case Float64: - x.typ = Typ[Complex128] - case UntypedInt, UntypedRune, UntypedFloat: - x.typ = Typ[UntypedComplex] - default: - check.invalidArg(x.pos(), "float32 or float64 arguments expected") - goto Error - } - - case _Copy: - var y operand - check.expr(&y, args[1], nil, iota) - if y.mode == invalid { - goto Error - } - - var dst, src Type - if t, ok := underlying(x.typ).(*Slice); ok { - dst = t.Elt - } - switch t := underlying(y.typ).(type) { - case *Basic: - if isString(y.typ) { - src = Typ[Byte] - } - case *Slice: - src = t.Elt - } - - if dst == nil || src == nil { - check.invalidArg(x.pos(), "copy expects slice arguments; found %s and %s", x, &y) - goto Error - } - - if !IsIdentical(dst, src) { - check.invalidArg(x.pos(), "arguments to copy %s and %s have different element types %s and %s", x, &y, dst, src) - goto Error - } - - x.mode = value - x.typ = Typ[Int] - - case _Delete: - m, ok := underlying(x.typ).(*Map) - if !ok { - check.invalidArg(x.pos(), "%s is not a map", x) - goto Error - } - check.expr(x, args[1], nil, iota) - if x.mode == invalid { - goto Error - } - if !x.isAssignable(m.Key) { - check.invalidArg(x.pos(), "%s is not assignable to %s", x, m.Key) - goto Error - } - x.mode = novalue - - case _Imag, _Real: - if !isComplex(x.typ) { - check.invalidArg(x.pos(), "%s must be a complex number", x) - goto Error - } - if x.mode == constant { - // nothing to do for x.val == 0 - if !isZeroConst(x.val) { - c := x.val.(Complex) - if id == _Real { - x.val = c.Re - } else { - x.val = c.Im - } - } - } else { - x.mode = value - } - k := Invalid - switch underlying(x.typ).(*Basic).Kind { - case Complex64: - k = Float32 - case Complex128: - k = Float64 - case UntypedComplex: - k = UntypedFloat - default: - unreachable() - } - x.typ = Typ[k] - - case _Make: - resultTyp := check.typ(arg0, false) - if resultTyp == Typ[Invalid] { - goto Error - } - var min int // minimum number of arguments - switch underlying(resultTyp).(type) { - case *Slice: - min = 2 - case *Map, *Chan: - min = 1 - default: - check.invalidArg(arg0.Pos(), "cannot make %s; type must be slice, map, or channel", arg0) - goto Error - } - if n := len(args); n < min || min+1 < n { - check.errorf(call.Pos(), "%s expects %d or %d arguments; found %d", call, min, min+1, n) - goto Error - } - var sizes []interface{} // constant integer arguments, if any - for _, arg := range args[1:] { - check.expr(x, arg, nil, iota) - if x.isInteger() { - if x.mode == constant { - if isNegConst(x.val) { - check.invalidArg(x.pos(), "%s must not be negative", x) - // safe to continue - } else { - sizes = append(sizes, x.val) // x.val >= 0 - } - } - } else { - check.invalidArg(x.pos(), "%s must be an integer", x) - // safe to continue - } - } - if len(sizes) == 2 && compareConst(sizes[0], sizes[1], token.GTR) { - check.invalidArg(args[1].Pos(), "length and capacity swapped") - // safe to continue - } - x.mode = variable - x.typ = resultTyp - - case _New: - resultTyp := check.typ(arg0, false) - if resultTyp == Typ[Invalid] { - goto Error - } - x.mode = variable - x.typ = &Pointer{Base: resultTyp} - - case _Panic, _Print, _Println: - for _, arg := range args[1:] { - check.expr(x, arg, nil, -1) - } - x.mode = novalue - - case _Recover: - x.mode = value - x.typ = new(Interface) - - case _Alignof: - x.mode = constant - x.typ = Typ[Uintptr] - // For now we return 1 always as it satisfies the spec's alignment guarantees. - // TODO(gri) Extend typechecker API so that platform-specific values can be - // provided. - x.val = int64(1) - - case _Offsetof: - if _, ok := unparen(x.expr).(*ast.SelectorExpr); !ok { - check.invalidArg(x.pos(), "%s is not a selector", x) - goto Error - } - x.mode = constant - x.typ = Typ[Uintptr] - // because of the size guarantees for basic types (> 0 for some), - // returning 0 is only correct if two distinct non-zero size - // structs can have the same address (the spec permits that) - x.val = int64(0) - - case _Sizeof: - x.mode = constant - x.val = sizeof(check.ctxt, x.typ) - x.typ = Typ[Uintptr] - - case _Assert: - // assert(pred) causes a typechecker error if pred is false. - // The result of assert is the value of pred if there is no error. - // Note: assert is only available in self-test mode. - if x.mode != constant || !isBoolean(x.typ) { - check.invalidArg(x.pos(), "%s is not a boolean constant", x) - goto Error - } - pred, ok := x.val.(bool) - if !ok { - check.errorf(x.pos(), "internal error: value of %s should be a boolean constant", x) - goto Error - } - if !pred { - check.errorf(call.Pos(), "%s failed", call) - // compile-time assertion failure - safe to continue - } - - case _Trace: - // trace(x, y, z, ...) dumps the positions, expressions, and - // values of its arguments. The result of trace is the value - // of the first argument. - // Note: trace is only available in self-test mode. - if len(args) == 0 { - check.dump("%s: trace() without arguments", call.Pos()) - x.mode = novalue - x.expr = call - return - } - var t operand - x1 := x - for _, arg := range args { - check.rawExpr(x1, arg, nil, iota, true) // permit trace for types, e.g.: new(trace(T)) - check.dump("%s: %s", x1.pos(), x1) - x1 = &t // use incoming x only for first argument - } - - default: - check.invalidAST(call.Pos(), "unknown builtin id %d", id) - goto Error - } - - x.expr = call - return - -Error: - x.mode = invalid - x.expr = call -} - -// implicitDeref returns A if typ is of the form *A and A is an array; -// otherwise it returns typ. -// -func implicitDeref(typ Type) Type { - if p, ok := typ.(*Pointer); ok { - if a, ok := underlying(p.Base).(*Array); ok { - return a - } - } - return typ -} - -// containsCallsOrReceives returns true if the expression x contains -// function calls or channel receives; it returns false otherwise. -// -func containsCallsOrReceives(x ast.Expr) bool { - res := false - ast.Inspect(x, func(x ast.Node) bool { - switch x := x.(type) { - case *ast.CallExpr: - res = true - return false - case *ast.UnaryExpr: - if x.Op == token.ARROW { - res = true - return false - } - } - return true - }) - return res -} - -// unparen removes any parentheses surrounding an expression and returns -// the naked expression. -// -func unparen(x ast.Expr) ast.Expr { - if p, ok := x.(*ast.ParenExpr); ok { - return unparen(p.X) - } - return x -} - -func (check *checker) complexArg(x *operand) bool { - t, _ := underlying(x.typ).(*Basic) - if t != nil && (t.Info&IsFloat != 0 || t.Kind == UntypedInt || t.Kind == UntypedRune) { - return true - } - check.invalidArg(x.pos(), "%s must be a float32, float64, or an untyped non-complex numeric constant", x) - return false -} - -func sizeof(ctxt *Context, typ Type) int64 { - switch typ := underlying(typ).(type) { - case *Basic: - switch typ.Kind { - case Int, Uint: - return ctxt.IntSize - case Uintptr: - return ctxt.PtrSize - } - return typ.Size - case *Array: - return sizeof(ctxt, typ.Elt) * typ.Len - case *Struct: - var size int64 - for _, f := range typ.Fields { - size += sizeof(ctxt, f.Type) - } - return size - } - return ctxt.PtrSize // good enough -} diff --git a/gcc-4.8.1/libgo/go/go/types/check.go b/gcc-4.8.1/libgo/go/go/types/check.go deleted file mode 100644 index fb9d7573d..000000000 --- a/gcc-4.8.1/libgo/go/go/types/check.go +++ /dev/null @@ -1,454 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements the Check function, which typechecks a package. - -package types - -import ( - "fmt" - "go/ast" - "go/token" -) - -// enable for debugging -const trace = false - -type checker struct { - ctxt *Context - fset *token.FileSet - files []*ast.File - - // lazily initialized - pkg *Package // current package - firsterr error // first error encountered - idents map[*ast.Ident]Object // maps identifiers to their unique object - objects map[*ast.Object]Object // maps *ast.Objects to their unique object - initspecs map[*ast.ValueSpec]*ast.ValueSpec // "inherited" type and initialization expressions for constant declarations - methods map[*TypeName]*Scope // maps type names to associated methods - funclist []function // list of functions/methods with correct signatures and non-empty bodies - funcsig *Signature // signature of currently typechecked function - pos []token.Pos // stack of expr positions; debugging support, used if trace is set -} - -func (check *checker) register(id *ast.Ident, obj Object) { - // When an expression is evaluated more than once (happens - // in rare cases, e.g. for statement expressions, see - // comment in stmt.go), the object has been registered - // before. Don't do anything in that case. - if alt := check.idents[id]; alt != nil { - assert(alt == obj) - return - } - check.idents[id] = obj - if f := check.ctxt.Ident; f != nil { - f(id, obj) - } -} - -// lookup returns the unique Object denoted by the identifier. -// For identifiers without assigned *ast.Object, it uses the -// checker.idents map; for identifiers with an *ast.Object it -// uses the checker.objects map. -// -// TODO(gri) Once identifier resolution is done entirely by -// the typechecker, only the idents map is needed. -// -func (check *checker) lookup(ident *ast.Ident) Object { - obj := check.idents[ident] - astObj := ident.Obj - - if obj != nil { - assert(astObj == nil || check.objects[astObj] == nil || check.objects[astObj] == obj) - return obj - } - - if astObj == nil { - return nil - } - - if obj = check.objects[astObj]; obj == nil { - obj = newObj(astObj) - check.objects[astObj] = obj - } - check.register(ident, obj) - - return obj -} - -type function struct { - obj *Func // for debugging/tracing only - sig *Signature - body *ast.BlockStmt -} - -// later adds a function with non-empty body to the list of functions -// that need to be processed after all package-level declarations -// are typechecked. -// -func (check *checker) later(f *Func, sig *Signature, body *ast.BlockStmt) { - // functions implemented elsewhere (say in assembly) have no body - if body != nil { - check.funclist = append(check.funclist, function{f, sig, body}) - } -} - -func (check *checker) declareIdent(scope *Scope, ident *ast.Ident, obj Object) { - assert(check.lookup(ident) == nil) // identifier already declared or resolved - check.register(ident, obj) - if ident.Name != "_" { - if alt := scope.Insert(obj); alt != nil { - prevDecl := "" - if pos := alt.GetPos(); pos.IsValid() { - prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", check.fset.Position(pos)) - } - check.errorf(ident.Pos(), fmt.Sprintf("%s redeclared in this block%s", ident.Name, prevDecl)) - } - } -} - -func (check *checker) valueSpec(pos token.Pos, obj Object, lhs []*ast.Ident, spec *ast.ValueSpec, iota int) { - if len(lhs) == 0 { - check.invalidAST(pos, "missing lhs in declaration") - return - } - - // determine type for all of lhs, if any - // (but only set it for the object we typecheck!) - var typ Type - if spec.Type != nil { - typ = check.typ(spec.Type, false) - } - - // len(lhs) > 0 - rhs := spec.Values - if len(lhs) == len(rhs) { - // check only lhs and rhs corresponding to obj - var l, r ast.Expr - for i, name := range lhs { - if check.lookup(name) == obj { - l = lhs[i] - r = rhs[i] - break - } - } - assert(l != nil) - switch obj := obj.(type) { - case *Const: - obj.Type = typ - case *Var: - obj.Type = typ - default: - unreachable() - } - check.assign1to1(l, r, nil, true, iota) - return - } - - // there must be a type or initialization expressions - if typ == nil && len(rhs) == 0 { - check.invalidAST(pos, "missing type or initialization expression") - typ = Typ[Invalid] - } - - // if we have a type, mark all of lhs - if typ != nil { - for _, name := range lhs { - switch obj := check.lookup(name).(type) { - case *Const: - obj.Type = typ - case *Var: - obj.Type = typ - default: - unreachable() - } - } - } - - // check initial values, if any - if len(rhs) > 0 { - // TODO(gri) should try to avoid this conversion - lhx := make([]ast.Expr, len(lhs)) - for i, e := range lhs { - lhx[i] = e - } - check.assignNtoM(lhx, rhs, true, iota) - } -} - -// object typechecks an object by assigning it a type. -// -func (check *checker) object(obj Object, cycleOk bool) { - switch obj := obj.(type) { - case *Package: - // nothing to do - case *Const: - if obj.Type != nil { - return // already checked - } - // The obj.Val field for constants is initialized to its respective - // iota value by the parser. - // The object's fields can be in one of the following states: - // Type != nil => the constant value is Val - // Type == nil => the constant is not typechecked yet, and Val can be: - // Val is int => Val is the value of iota for this declaration - // Val == nil => the object's expression is being evaluated - if obj.Val == nil { - check.errorf(obj.GetPos(), "illegal cycle in initialization of %s", obj.Name) - obj.Type = Typ[Invalid] - return - } - spec := obj.spec - iota := obj.Val.(int) - obj.Val = nil // mark obj as "visited" for cycle detection - // determine spec for type and initialization expressions - init := spec - if len(init.Values) == 0 { - init = check.initspecs[spec] - } - check.valueSpec(spec.Pos(), obj, spec.Names, init, iota) - - case *Var: - if obj.Type != nil { - return // already checked - } - if obj.visited { - check.errorf(obj.GetPos(), "illegal cycle in initialization of %s", obj.Name) - obj.Type = Typ[Invalid] - return - } - spec := obj.decl.(*ast.ValueSpec) - obj.visited = true - check.valueSpec(spec.Pos(), obj, spec.Names, spec, 0) - - case *TypeName: - if obj.Type != nil { - return // already checked - } - typ := &NamedType{Obj: obj} - obj.Type = typ // "mark" object so recursion terminates - typ.Underlying = underlying(check.typ(obj.spec.Type, cycleOk)) - // typecheck associated method signatures - if scope := check.methods[obj]; scope != nil { - switch t := typ.Underlying.(type) { - case *Struct: - // struct fields must not conflict with methods - for _, f := range t.Fields { - if m := scope.Lookup(f.Name); m != nil { - check.errorf(m.GetPos(), "type %s has both field and method named %s", obj.Name, f.Name) - // ok to continue - } - } - case *Interface: - // methods cannot be associated with an interface type - for _, m := range scope.Entries { - recv := m.(*Func).decl.Recv.List[0].Type - check.errorf(recv.Pos(), "invalid receiver type %s (%s is an interface type)", obj.Name, obj.Name) - // ok to continue - } - } - // typecheck method signatures - var methods []*Method - for _, obj := range scope.Entries { - m := obj.(*Func) - sig := check.typ(m.decl.Type, cycleOk).(*Signature) - params, _ := check.collectParams(m.decl.Recv, false) - sig.Recv = params[0] // the parser/assocMethod ensure there is exactly one parameter - m.Type = sig - methods = append(methods, &Method{QualifiedName{check.pkg, m.Name}, sig}) - check.later(m, sig, m.decl.Body) - } - typ.Methods = methods - delete(check.methods, obj) // we don't need this scope anymore - } - - case *Func: - if obj.Type != nil { - return // already checked - } - fdecl := obj.decl - // methods are typechecked when their receivers are typechecked - if fdecl.Recv == nil { - sig := check.typ(fdecl.Type, cycleOk).(*Signature) - if obj.Name == "init" && (len(sig.Params) != 0 || len(sig.Results) != 0) { - check.errorf(fdecl.Pos(), "func init must have no arguments and no return values") - // ok to continue - } - obj.Type = sig - check.later(obj, sig, fdecl.Body) - } - - default: - unreachable() - } -} - -// assocInitvals associates "inherited" initialization expressions -// with the corresponding *ast.ValueSpec in the check.initspecs map -// for constant declarations without explicit initialization expressions. -// -func (check *checker) assocInitvals(decl *ast.GenDecl) { - var last *ast.ValueSpec - for _, s := range decl.Specs { - if s, ok := s.(*ast.ValueSpec); ok { - if len(s.Values) > 0 { - last = s - } else { - check.initspecs[s] = last - } - } - } - if last == nil { - check.invalidAST(decl.Pos(), "no initialization values provided") - } -} - -// assocMethod associates a method declaration with the respective -// receiver base type. meth.Recv must exist. -// -func (check *checker) assocMethod(meth *ast.FuncDecl) { - // The receiver type is one of the following (enforced by parser): - // - *ast.Ident - // - *ast.StarExpr{*ast.Ident} - // - *ast.BadExpr (parser error) - typ := meth.Recv.List[0].Type - if ptr, ok := typ.(*ast.StarExpr); ok { - typ = ptr.X - } - // determine receiver base type name - ident, ok := typ.(*ast.Ident) - if !ok { - // not an identifier - parser reported error already - return // ignore this method - } - // determine receiver base type object - var tname *TypeName - if obj := check.lookup(ident); obj != nil { - obj, ok := obj.(*TypeName) - if !ok { - check.errorf(ident.Pos(), "%s is not a type", ident.Name) - return // ignore this method - } - if obj.spec == nil { - check.errorf(ident.Pos(), "cannot define method on non-local type %s", ident.Name) - return // ignore this method - } - tname = obj - } else { - // identifier not declared/resolved - parser reported error already - return // ignore this method - } - // declare method in receiver base type scope - scope := check.methods[tname] - if scope == nil { - scope = new(Scope) - check.methods[tname] = scope - } - check.declareIdent(scope, meth.Name, &Func{Name: meth.Name.Name, decl: meth}) -} - -func (check *checker) decl(decl ast.Decl) { - switch d := decl.(type) { - case *ast.BadDecl: - // ignore - case *ast.GenDecl: - for _, spec := range d.Specs { - switch s := spec.(type) { - case *ast.ImportSpec: - // nothing to do (handled by check.resolve) - case *ast.ValueSpec: - for _, name := range s.Names { - check.object(check.lookup(name), false) - } - case *ast.TypeSpec: - check.object(check.lookup(s.Name), false) - default: - check.invalidAST(s.Pos(), "unknown ast.Spec node %T", s) - } - } - case *ast.FuncDecl: - // methods are checked when their respective base types are checked - if d.Recv != nil { - return - } - obj := check.lookup(d.Name) - // Initialization functions don't have an object associated with them - // since they are not in any scope. Create a dummy object for them. - if d.Name.Name == "init" { - assert(obj == nil) // all other functions should have an object - obj = &Func{Name: d.Name.Name, decl: d} - check.register(d.Name, obj) - } - check.object(obj, false) - default: - check.invalidAST(d.Pos(), "unknown ast.Decl node %T", d) - } -} - -// A bailout panic is raised to indicate early termination. -type bailout struct{} - -func check(ctxt *Context, fset *token.FileSet, files []*ast.File) (pkg *Package, err error) { - // initialize checker - check := checker{ - ctxt: ctxt, - fset: fset, - files: files, - idents: make(map[*ast.Ident]Object), - objects: make(map[*ast.Object]Object), - initspecs: make(map[*ast.ValueSpec]*ast.ValueSpec), - methods: make(map[*TypeName]*Scope), - } - - // handle panics - defer func() { - switch p := recover().(type) { - case nil, bailout: - // normal return or early exit - err = check.firsterr - default: - // unexpected panic: don't crash clients - panic(p) // enable for debugging - // TODO(gri) add a test case for this scenario - err = fmt.Errorf("types internal error: %v", p) - } - }() - - // resolve identifiers - imp := ctxt.Import - if imp == nil { - imp = GcImport - } - pkg, methods := check.resolve(imp) - check.pkg = pkg - - // associate methods with types - for _, m := range methods { - check.assocMethod(m) - } - - // typecheck all declarations - for _, f := range check.files { - for _, d := range f.Decls { - check.decl(d) - } - } - - // typecheck all function/method bodies - // (funclist may grow when checking statements - do not use range clause!) - for i := 0; i < len(check.funclist); i++ { - f := check.funclist[i] - if trace { - s := "<function literal>" - if f.obj != nil { - s = f.obj.Name - } - fmt.Println("---", s) - } - check.funcsig = f.sig - check.stmtList(f.body.List) - } - - return -} diff --git a/gcc-4.8.1/libgo/go/go/types/check_test.go b/gcc-4.8.1/libgo/go/go/types/check_test.go deleted file mode 100644 index 375ae6724..000000000 --- a/gcc-4.8.1/libgo/go/go/types/check_test.go +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements a typechecker test harness. The packages specified -// in tests are typechecked. Error messages reported by the typechecker are -// compared against the error messages expected in the test files. -// -// Expected errors are indicated in the test files by putting a comment -// of the form /* ERROR "rx" */ immediately following an offending token. -// The harness will verify that an error matching the regular expression -// rx is reported at that source position. Consecutive comments may be -// used to indicate multiple errors for the same token position. -// -// For instance, the following test file indicates that a "not declared" -// error should be reported for the undeclared variable x: -// -// package p -// func f() { -// _ = x /* ERROR "not declared" */ + 1 -// } - -package types - -import ( - "flag" - "fmt" - "go/ast" - "go/parser" - "go/scanner" - "go/token" - "io/ioutil" - "os" - "regexp" - "testing" -) - -var listErrors = flag.Bool("list", false, "list errors") - -// The test filenames do not end in .go so that they are invisible -// to gofmt since they contain comments that must not change their -// positions relative to surrounding tokens. - -var tests = []struct { - name string - files []string -}{ - {"decls0", []string{"testdata/decls0.src"}}, - {"decls1", []string{"testdata/decls1.src"}}, - {"decls2", []string{"testdata/decls2a.src", "testdata/decls2b.src"}}, - {"decls3", []string{"testdata/decls3.src"}}, - {"const0", []string{"testdata/const0.src"}}, - {"expr0", []string{"testdata/expr0.src"}}, - {"expr1", []string{"testdata/expr1.src"}}, - {"expr2", []string{"testdata/expr2.src"}}, - {"expr3", []string{"testdata/expr3.src"}}, - {"builtins", []string{"testdata/builtins.src"}}, - {"conversions", []string{"testdata/conversions.src"}}, - {"stmt0", []string{"testdata/stmt0.src"}}, -} - -var fset = token.NewFileSet() - -func getFile(filename string) (file *token.File) { - fset.Iterate(func(f *token.File) bool { - if f.Name() == filename { - file = f - return false // end iteration - } - return true - }) - return file -} - -// Positioned errors are of the form filename:line:column: message . -var posMsgRx = regexp.MustCompile(`^(.*:[0-9]+:[0-9]+): *(.*)`) - -// splitError splits an error's error message into a position string -// and the actual error message. If there's no position information, -// pos is the empty string, and msg is the entire error message. -// -func splitError(err error) (pos, msg string) { - msg = err.Error() - if m := posMsgRx.FindStringSubmatch(msg); len(m) == 3 { - pos = m[1] - msg = m[2] - } - return -} - -func parseFiles(t *testing.T, testname string, filenames []string) ([]*ast.File, []error) { - var files []*ast.File - var errlist []error - for _, filename := range filenames { - file, err := parser.ParseFile(fset, filename, nil, parser.DeclarationErrors) - if file == nil { - t.Fatalf("%s: could not parse file %s", testname, filename) - } - files = append(files, file) - if err != nil { - if list, _ := err.(scanner.ErrorList); len(list) > 0 { - for _, err := range list { - errlist = append(errlist, err) - } - } else { - errlist = append(errlist, err) - } - } - } - return files, errlist -} - -// ERROR comments must be of the form /* ERROR "rx" */ and rx is -// a regular expression that matches the expected error message. -// -var errRx = regexp.MustCompile(`^/\* *ERROR *"([^"]*)" *\*/$`) - -// errMap collects the regular expressions of ERROR comments found -// in files and returns them as a map of error positions to error messages. -// -func errMap(t *testing.T, testname string, files []*ast.File) map[string][]string { - errmap := make(map[string][]string) - - for _, file := range files { - filename := fset.Position(file.Package).Filename - src, err := ioutil.ReadFile(filename) - if err != nil { - t.Fatalf("%s: could not read %s", testname, filename) - } - - var s scanner.Scanner - // file was parsed already - do not add it again to the file - // set otherwise the position information returned here will - // not match the position information collected by the parser - s.Init(getFile(filename), src, nil, scanner.ScanComments) - var prev string // position string of last non-comment, non-semicolon token - - scanFile: - for { - pos, tok, lit := s.Scan() - switch tok { - case token.EOF: - break scanFile - case token.COMMENT: - s := errRx.FindStringSubmatch(lit) - if len(s) == 2 { - errmap[prev] = append(errmap[prev], string(s[1])) - } - case token.SEMICOLON: - // ignore automatically inserted semicolon - if lit == "\n" { - continue scanFile - } - fallthrough - default: - prev = fset.Position(pos).String() - } - } - } - - return errmap -} - -func eliminate(t *testing.T, errmap map[string][]string, errlist []error) { - for _, err := range errlist { - pos, msg := splitError(err) - list := errmap[pos] - index := -1 // list index of matching message, if any - // we expect one of the messages in list to match the error at pos - for i, msg := range list { - rx, err := regexp.Compile(msg) - if err != nil { - t.Errorf("%s: %v", pos, err) - continue - } - if rx.MatchString(msg) { - index = i - break - } - } - if index >= 0 { - // eliminate from list - if n := len(list) - 1; n > 0 { - // not the last entry - swap in last element and shorten list by 1 - list[index] = list[n] - errmap[pos] = list[:n] - } else { - // last entry - remove list from map - delete(errmap, pos) - } - } else { - t.Errorf("%s: no error expected: %q", pos, msg) - } - - } -} - -func checkFiles(t *testing.T, testname string, testfiles []string) { - // parse files and collect parser errors - files, errlist := parseFiles(t, testname, testfiles) - - // typecheck and collect typechecker errors - ctxt := Default - ctxt.Error = func(err error) { errlist = append(errlist, err) } - ctxt.Check(fset, files) - - if *listErrors { - t.Errorf("--- %s: %d errors found:", testname, len(errlist)) - for _, err := range errlist { - t.Error(err) - } - return - } - - // match and eliminate errors - // we are expecting the following errors - // (collect these after parsing the files so that - // they are found in the file set) - errmap := errMap(t, testname, files) - eliminate(t, errmap, errlist) - - // there should be no expected errors left - if len(errmap) > 0 { - t.Errorf("--- %s: %d source positions with expected (but not reported) errors:", testname, len(errmap)) - for pos, list := range errmap { - for _, rx := range list { - t.Errorf("%s: %q", pos, rx) - } - } - } -} - -var testBuiltinsDeclared = false - -func TestCheck(t *testing.T) { - // Does not work with gccgo, because it requires reading gc - // import files. - return - - // Declare builtins for testing. - // Not done in an init func to avoid an init race with - // the construction of the Universe var. - if !testBuiltinsDeclared { - testBuiltinsDeclared = true - def(&Func{Name: "assert", Type: &builtin{_Assert, "assert", 1, false, true}}) - def(&Func{Name: "trace", Type: &builtin{_Trace, "trace", 0, true, true}}) - } - - // For easy debugging w/o changing the testing code, - // if there is a local test file, only test that file. - const testfile = "testdata/test.go" - if fi, err := os.Stat(testfile); err == nil && !fi.IsDir() { - fmt.Printf("WARNING: Testing only %s (remove it to run all tests)\n", testfile) - checkFiles(t, testfile, []string{testfile}) - return - } - - // Otherwise, run all the tests. - for _, test := range tests { - checkFiles(t, test.name, test.files) - } -} diff --git a/gcc-4.8.1/libgo/go/go/types/const.go b/gcc-4.8.1/libgo/go/go/types/const.go deleted file mode 100644 index a6c807c43..000000000 --- a/gcc-4.8.1/libgo/go/go/types/const.go +++ /dev/null @@ -1,734 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements operations on constant values. - -package types - -import ( - "fmt" - "go/token" - "math/big" - "strconv" -) - -// TODO(gri) At the moment, constants are different types -// passed around as interface{} values. Consider introducing -// a Const type and use methods instead of xConst functions. - -// Representation of constant values. -// -// bool -> bool (true, false) -// numeric -> int64, *big.Int, *big.Rat, Complex (ordered by increasing data structure "size") -// string -> string -// nil -> NilType (nilConst) -// -// Numeric constants are normalized after each operation such -// that they are represented by the "smallest" data structure -// required to represent the constant, independent of actual -// type. Non-numeric constants are always normalized. - -// Representation of complex numbers. -type Complex struct { - Re, Im *big.Rat -} - -func (c Complex) String() string { - if c.Re.Sign() == 0 { - return fmt.Sprintf("%si", c.Im) - } - // normalized complex values always have an imaginary part - return fmt.Sprintf("(%s + %si)", c.Re, c.Im) -} - -// Representation of nil. -type NilType struct{} - -func (NilType) String() string { - return "nil" -} - -// Implementation-specific constants. -// TODO(gri) These need to go elsewhere. -const ( - intBits = 32 - ptrBits = 64 -) - -// Frequently used values. -var ( - nilConst = NilType{} - zeroConst = int64(0) -) - -// int64 bounds -var ( - minInt64 = big.NewInt(-1 << 63) - maxInt64 = big.NewInt(1<<63 - 1) -) - -// normalizeIntConst returns the smallest constant representation -// for the specific value of x; either an int64 or a *big.Int value. -// -func normalizeIntConst(x *big.Int) interface{} { - if minInt64.Cmp(x) <= 0 && x.Cmp(maxInt64) <= 0 { - return x.Int64() - } - return x -} - -// normalizeRatConst returns the smallest constant representation -// for the specific value of x; either an int64, *big.Int, -// or *big.Rat value. -// -func normalizeRatConst(x *big.Rat) interface{} { - if x.IsInt() { - return normalizeIntConst(x.Num()) - } - return x -} - -// newComplex returns the smallest constant representation -// for the specific value re + im*i; either an int64, *big.Int, -// *big.Rat, or complex value. -// -func newComplex(re, im *big.Rat) interface{} { - if im.Sign() == 0 { - return normalizeRatConst(re) - } - return Complex{re, im} -} - -// makeRuneConst returns the int64 code point for the rune literal -// lit. The result is nil if lit is not a correct rune literal. -// -func makeRuneConst(lit string) interface{} { - if n := len(lit); n >= 2 { - if code, _, _, err := strconv.UnquoteChar(lit[1:n-1], '\''); err == nil { - return int64(code) - } - } - return nil -} - -// makeRuneConst returns the smallest integer constant representation -// (int64, *big.Int) for the integer literal lit. The result is nil if -// lit is not a correct integer literal. -// -func makeIntConst(lit string) interface{} { - if x, err := strconv.ParseInt(lit, 0, 64); err == nil { - return x - } - if x, ok := new(big.Int).SetString(lit, 0); ok { - return x - } - return nil -} - -// makeFloatConst returns the smallest floating-point constant representation -// (int64, *big.Int, *big.Rat) for the floating-point literal lit. The result -// is nil if lit is not a correct floating-point literal. -// -func makeFloatConst(lit string) interface{} { - if x, ok := new(big.Rat).SetString(lit); ok { - return normalizeRatConst(x) - } - return nil -} - -// makeComplexConst returns the complex constant representation (Complex) for -// the imaginary literal lit. The result is nil if lit is not a correct imaginary -// literal. -// -func makeComplexConst(lit string) interface{} { - n := len(lit) - if n > 0 && lit[n-1] == 'i' { - if im, ok := new(big.Rat).SetString(lit[0 : n-1]); ok { - return newComplex(big.NewRat(0, 1), im) - } - } - return nil -} - -// makeStringConst returns the string constant representation (string) for -// the string literal lit. The result is nil if lit is not a correct string -// literal. -// -func makeStringConst(lit string) interface{} { - if s, err := strconv.Unquote(lit); err == nil { - return s - } - return nil -} - -// toImagConst returns the constant Complex(0, x) for a non-complex x. -func toImagConst(x interface{}) interface{} { - var im *big.Rat - switch x := x.(type) { - case int64: - im = big.NewRat(x, 1) - case *big.Int: - im = new(big.Rat).SetFrac(x, int1) - case *big.Rat: - im = x - default: - unreachable() - } - return Complex{rat0, im} -} - -// isZeroConst reports whether the value of constant x is 0. -// x must be normalized. -// -func isZeroConst(x interface{}) bool { - i, ok := x.(int64) // good enough since constants are normalized - return ok && i == 0 -} - -// isNegConst reports whether the value of constant x is < 0. -// x must be a non-complex numeric value. -// -func isNegConst(x interface{}) bool { - switch x := x.(type) { - case int64: - return x < 0 - case *big.Int: - return x.Sign() < 0 - case *big.Rat: - return x.Sign() < 0 - } - unreachable() - return false -} - -// isRepresentableConst reports whether the value of constant x can -// be represented as a value of the basic type Typ[as] without loss -// of precision. -// -func isRepresentableConst(x interface{}, as BasicKind) bool { - switch x := x.(type) { - case bool: - return as == Bool || as == UntypedBool - - case int64: - switch as { - case Int: - return -1<<(intBits-1) <= x && x <= 1<<(intBits-1)-1 - case Int8: - return -1<<(8-1) <= x && x <= 1<<(8-1)-1 - case Int16: - return -1<<(16-1) <= x && x <= 1<<(16-1)-1 - case Int32, UntypedRune: - return -1<<(32-1) <= x && x <= 1<<(32-1)-1 - case Int64: - return true - case Uint: - return 0 <= x && x <= 1<<intBits-1 - case Uint8: - return 0 <= x && x <= 1<<8-1 - case Uint16: - return 0 <= x && x <= 1<<16-1 - case Uint32: - return 0 <= x && x <= 1<<32-1 - case Uint64: - return 0 <= x - case Uintptr: - assert(ptrBits == 64) - return 0 <= x - case Float32: - return true // TODO(gri) fix this - case Float64: - return true // TODO(gri) fix this - case Complex64: - return true // TODO(gri) fix this - case Complex128: - return true // TODO(gri) fix this - case UntypedInt, UntypedFloat, UntypedComplex: - return true - } - - case *big.Int: - switch as { - case Uint: - return x.Sign() >= 0 && x.BitLen() <= intBits - case Uint64: - return x.Sign() >= 0 && x.BitLen() <= 64 - case Uintptr: - return x.Sign() >= 0 && x.BitLen() <= ptrBits - case Float32: - return true // TODO(gri) fix this - case Float64: - return true // TODO(gri) fix this - case Complex64: - return true // TODO(gri) fix this - case Complex128: - return true // TODO(gri) fix this - case UntypedInt, UntypedFloat, UntypedComplex: - return true - } - - case *big.Rat: - switch as { - case Float32: - return true // TODO(gri) fix this - case Float64: - return true // TODO(gri) fix this - case Complex64: - return true // TODO(gri) fix this - case Complex128: - return true // TODO(gri) fix this - case UntypedFloat, UntypedComplex: - return true - } - - case Complex: - switch as { - case Complex64: - return true // TODO(gri) fix this - case Complex128: - return true // TODO(gri) fix this - case UntypedComplex: - return true - } - - case string: - return as == String || as == UntypedString - - case NilType: - return as == UntypedNil || as == UnsafePointer - - default: - unreachable() - } - - return false -} - -var ( - int1 = big.NewInt(1) - rat0 = big.NewRat(0, 1) -) - -// complexity returns a measure of representation complexity for constant x. -func complexity(x interface{}) int { - switch x.(type) { - case bool, string, NilType: - return 1 - case int64: - return 2 - case *big.Int: - return 3 - case *big.Rat: - return 4 - case Complex: - return 5 - } - unreachable() - return 0 -} - -// matchConst returns the matching representation (same type) with the -// smallest complexity for two constant values x and y. They must be -// of the same "kind" (boolean, numeric, string, or NilType). -// -func matchConst(x, y interface{}) (_, _ interface{}) { - if complexity(x) > complexity(y) { - y, x = matchConst(y, x) - return x, y - } - // complexity(x) <= complexity(y) - - switch x := x.(type) { - case bool, Complex, string, NilType: - return x, y - - case int64: - switch y := y.(type) { - case int64: - return x, y - case *big.Int: - return big.NewInt(x), y - case *big.Rat: - return big.NewRat(x, 1), y - case Complex: - return Complex{big.NewRat(x, 1), rat0}, y - } - - case *big.Int: - switch y := y.(type) { - case *big.Int: - return x, y - case *big.Rat: - return new(big.Rat).SetFrac(x, int1), y - case Complex: - return Complex{new(big.Rat).SetFrac(x, int1), rat0}, y - } - - case *big.Rat: - switch y := y.(type) { - case *big.Rat: - return x, y - case Complex: - return Complex{x, rat0}, y - } - } - - unreachable() - return nil, nil -} - -// is32bit reports whether x can be represented using 32 bits. -func is32bit(x int64) bool { - return -1<<31 <= x && x <= 1<<31-1 -} - -// is63bit reports whether x can be represented using 63 bits. -func is63bit(x int64) bool { - return -1<<62 <= x && x <= 1<<62-1 -} - -// unaryOpConst returns the result of the constant evaluation op x where x is of the given type. -func unaryOpConst(x interface{}, op token.Token, typ *Basic) interface{} { - switch op { - case token.ADD: - return x // nothing to do - case token.SUB: - switch x := x.(type) { - case int64: - if z := -x; z != x { - return z // no overflow - } - // overflow - need to convert to big.Int - return normalizeIntConst(new(big.Int).Neg(big.NewInt(x))) - case *big.Int: - return normalizeIntConst(new(big.Int).Neg(x)) - case *big.Rat: - return normalizeRatConst(new(big.Rat).Neg(x)) - case Complex: - return newComplex(new(big.Rat).Neg(x.Re), new(big.Rat).Neg(x.Im)) - } - case token.XOR: - var z big.Int - switch x := x.(type) { - case int64: - z.Not(big.NewInt(x)) - case *big.Int: - z.Not(x) - default: - unreachable() - } - // For unsigned types, the result will be negative and - // thus "too large": We must limit the result size to - // the type's size. - if typ.Info&IsUnsigned != 0 { - s := uint(typ.Size) * 8 - if s == 0 { - // platform-specific type - // TODO(gri) this needs to be factored out - switch typ.Kind { - case Uint: - s = intBits - case Uintptr: - s = ptrBits - default: - unreachable() - } - } - // z &^= (-1)<<s - z.AndNot(&z, new(big.Int).Lsh(big.NewInt(-1), s)) - } - return normalizeIntConst(&z) - case token.NOT: - return !x.(bool) - } - unreachable() - return nil -} - -// binaryOpConst returns the result of the constant evaluation x op y; -// both operands must be of the same constant "kind" (boolean, numeric, or string). -// If typ is an integer type, division (op == token.QUO) is using integer division -// (and the result is guaranteed to be integer) rather than floating-point -// division. Division by zero leads to a run-time panic. -// -func binaryOpConst(x, y interface{}, op token.Token, typ *Basic) interface{} { - x, y = matchConst(x, y) - - switch x := x.(type) { - case bool: - y := y.(bool) - switch op { - case token.LAND: - return x && y - case token.LOR: - return x || y - } - - case int64: - y := y.(int64) - switch op { - case token.ADD: - // TODO(gri) can do better than this - if is63bit(x) && is63bit(y) { - return x + y - } - return normalizeIntConst(new(big.Int).Add(big.NewInt(x), big.NewInt(y))) - case token.SUB: - // TODO(gri) can do better than this - if is63bit(x) && is63bit(y) { - return x - y - } - return normalizeIntConst(new(big.Int).Sub(big.NewInt(x), big.NewInt(y))) - case token.MUL: - // TODO(gri) can do better than this - if is32bit(x) && is32bit(y) { - return x * y - } - return normalizeIntConst(new(big.Int).Mul(big.NewInt(x), big.NewInt(y))) - case token.REM: - return x % y - case token.QUO: - if typ.Info&IsInteger != 0 { - return x / y - } - return normalizeRatConst(new(big.Rat).SetFrac(big.NewInt(x), big.NewInt(y))) - case token.AND: - return x & y - case token.OR: - return x | y - case token.XOR: - return x ^ y - case token.AND_NOT: - return x &^ y - } - - case *big.Int: - y := y.(*big.Int) - var z big.Int - switch op { - case token.ADD: - z.Add(x, y) - case token.SUB: - z.Sub(x, y) - case token.MUL: - z.Mul(x, y) - case token.REM: - z.Rem(x, y) - case token.QUO: - if typ.Info&IsInteger != 0 { - z.Quo(x, y) - } else { - return normalizeRatConst(new(big.Rat).SetFrac(x, y)) - } - case token.AND: - z.And(x, y) - case token.OR: - z.Or(x, y) - case token.XOR: - z.Xor(x, y) - case token.AND_NOT: - z.AndNot(x, y) - default: - unreachable() - } - return normalizeIntConst(&z) - - case *big.Rat: - y := y.(*big.Rat) - var z big.Rat - switch op { - case token.ADD: - z.Add(x, y) - case token.SUB: - z.Sub(x, y) - case token.MUL: - z.Mul(x, y) - case token.QUO: - z.Quo(x, y) - default: - unreachable() - } - return normalizeRatConst(&z) - - case Complex: - y := y.(Complex) - a, b := x.Re, x.Im - c, d := y.Re, y.Im - var re, im big.Rat - switch op { - case token.ADD: - // (a+c) + i(b+d) - re.Add(a, c) - im.Add(b, d) - case token.SUB: - // (a-c) + i(b-d) - re.Sub(a, c) - im.Sub(b, d) - case token.MUL: - // (ac-bd) + i(bc+ad) - var ac, bd, bc, ad big.Rat - ac.Mul(a, c) - bd.Mul(b, d) - bc.Mul(b, c) - ad.Mul(a, d) - re.Sub(&ac, &bd) - im.Add(&bc, &ad) - case token.QUO: - // (ac+bd)/s + i(bc-ad)/s, with s = cc + dd - var ac, bd, bc, ad, s big.Rat - ac.Mul(a, c) - bd.Mul(b, d) - bc.Mul(b, c) - ad.Mul(a, d) - s.Add(c.Mul(c, c), d.Mul(d, d)) - re.Add(&ac, &bd) - re.Quo(&re, &s) - im.Sub(&bc, &ad) - im.Quo(&im, &s) - default: - unreachable() - } - return newComplex(&re, &im) - - case string: - if op == token.ADD { - return x + y.(string) - } - } - - unreachable() - return nil -} - -// shiftConst returns the result of the constant evaluation x op s -// where op is token.SHL or token.SHR (<< or >>). x must be an -// integer constant. -// -func shiftConst(x interface{}, s uint, op token.Token) interface{} { - switch x := x.(type) { - case int64: - switch op { - case token.SHL: - z := big.NewInt(x) - return normalizeIntConst(z.Lsh(z, s)) - case token.SHR: - return x >> s - } - - case *big.Int: - var z big.Int - switch op { - case token.SHL: - return normalizeIntConst(z.Lsh(x, s)) - case token.SHR: - return normalizeIntConst(z.Rsh(x, s)) - } - } - - unreachable() - return nil -} - -// compareConst returns the result of the constant comparison x op y; -// both operands must be of the same "kind" (boolean, numeric, string, -// or NilType). -// -func compareConst(x, y interface{}, op token.Token) (z bool) { - x, y = matchConst(x, y) - - // x == y => x == y - // x != y => x != y - // x > y => y < x - // x >= y => u <= x - swap := false - switch op { - case token.GTR: - swap = true - op = token.LSS - case token.GEQ: - swap = true - op = token.LEQ - } - - // x == y => x == y - // x != y => !(x == y) - // x < y => x < y - // x <= y => !(y < x) - negate := false - switch op { - case token.NEQ: - negate = true - op = token.EQL - case token.LEQ: - swap = !swap - negate = true - op = token.LSS - } - - if negate { - defer func() { z = !z }() - } - - if swap { - x, y = y, x - } - - switch x := x.(type) { - case bool: - if op == token.EQL { - return x == y.(bool) - } - - case int64: - y := y.(int64) - switch op { - case token.EQL: - return x == y - case token.LSS: - return x < y - } - - case *big.Int: - s := x.Cmp(y.(*big.Int)) - switch op { - case token.EQL: - return s == 0 - case token.LSS: - return s < 0 - } - - case *big.Rat: - s := x.Cmp(y.(*big.Rat)) - switch op { - case token.EQL: - return s == 0 - case token.LSS: - return s < 0 - } - - case Complex: - y := y.(Complex) - if op == token.EQL { - return x.Re.Cmp(y.Re) == 0 && x.Im.Cmp(y.Im) == 0 - } - - case string: - y := y.(string) - switch op { - case token.EQL: - return x == y - case token.LSS: - return x < y - } - - case NilType: - if op == token.EQL { - return x == y.(NilType) - } - } - - fmt.Printf("x = %s (%T), y = %s (%T)\n", x, x, y, y) - unreachable() - return -} diff --git a/gcc-4.8.1/libgo/go/go/types/conversions.go b/gcc-4.8.1/libgo/go/go/types/conversions.go deleted file mode 100644 index 65359f319..000000000 --- a/gcc-4.8.1/libgo/go/go/types/conversions.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements typechecking of conversions. - -package types - -import ( - "go/ast" -) - -// conversion typechecks the type conversion conv to type typ. iota is the current -// value of iota or -1 if iota doesn't have a value in the current context. The result -// of the conversion is returned via x. If the conversion has type errors, the returned -// x is marked as invalid (x.mode == invalid). -// -func (check *checker) conversion(x *operand, conv *ast.CallExpr, typ Type, iota int) { - // all conversions have one argument - if len(conv.Args) != 1 { - check.invalidOp(conv.Pos(), "%s conversion requires exactly one argument", conv) - goto Error - } - - // evaluate argument - check.expr(x, conv.Args[0], nil, iota) - if x.mode == invalid { - goto Error - } - - if x.mode == constant && isConstType(typ) { - // constant conversion - // TODO(gri) implement this - } else { - // non-constant conversion - if !x.isConvertible(typ) { - check.invalidOp(conv.Pos(), "cannot convert %s to %s", x, typ) - goto Error - } - x.mode = value - } - - x.expr = conv - x.typ = typ - return - -Error: - x.mode = invalid -} - -func (x *operand) isConvertible(T Type) bool { - // "x is assignable to T" - if x.isAssignable(T) { - return true - } - - // "x's type and T have identical underlying types" - V := x.typ - Vu := underlying(V) - Tu := underlying(T) - if IsIdentical(Vu, Tu) { - return true - } - - // "x's type and T are unnamed pointer types and their pointer base types have identical underlying types" - if V, ok := V.(*Pointer); ok { - if T, ok := T.(*Pointer); ok { - if IsIdentical(underlying(V.Base), underlying(T.Base)) { - return true - } - } - } - - // "x's type and T are both integer or floating point types" - if (isInteger(V) || isFloat(V)) && (isInteger(T) || isFloat(T)) { - return true - } - - // "x's type and T are both complex types" - if isComplex(V) && isComplex(T) { - return true - } - - // "x is an integer or a slice of bytes or runes and T is a string type" - if (isInteger(V) || isBytesOrRunes(Vu)) && isString(T) { - return true - } - - // "x is a string and T is a slice of bytes or runes" - if isString(V) && isBytesOrRunes(Tu) { - return true - } - - // package unsafe: - // "any pointer or value of underlying type uintptr can be converted into a unsafe.Pointer" - if (isPointer(Vu) || isUintptr(Vu)) && isUnsafePointer(T) { - return true - } - // "and vice versa" - if isUnsafePointer(V) && (isPointer(Tu) || isUintptr(Tu)) { - return true - } - - return false -} - -func isUintptr(typ Type) bool { - t, ok := typ.(*Basic) - return ok && t.Kind == Uintptr -} - -func isUnsafePointer(typ Type) bool { - t, ok := typ.(*Basic) - return ok && t.Kind == UnsafePointer -} - -func isPointer(typ Type) bool { - _, ok := typ.(*Pointer) - return ok -} - -func isBytesOrRunes(typ Type) bool { - if s, ok := typ.(*Slice); ok { - t, ok := underlying(s.Elt).(*Basic) - return ok && (t.Kind == Byte || t.Kind == Rune) - } - return false -} diff --git a/gcc-4.8.1/libgo/go/go/types/errors.go b/gcc-4.8.1/libgo/go/go/types/errors.go deleted file mode 100644 index c8b420b4d..000000000 --- a/gcc-4.8.1/libgo/go/go/types/errors.go +++ /dev/null @@ -1,331 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements various error reporters. - -package types - -import ( - "bytes" - "fmt" - "go/ast" - "go/token" -) - -// TODO(gri) eventually assert and unimplemented should disappear. -func assert(p bool) { - if !p { - panic("assertion failed") - } -} - -func unreachable() { - panic("unreachable") -} - -func (check *checker) printTrace(format string, args []interface{}) { - const dots = ". . . . . . . . . . . . . . . . . . . . " - n := len(check.pos) - 1 - i := 3 * n - for i > len(dots) { - fmt.Print(dots) - i -= len(dots) - } - // i <= len(dots) - fmt.Printf("%s:\t", check.fset.Position(check.pos[n])) - fmt.Print(dots[0:i]) - fmt.Println(check.formatMsg(format, args)) -} - -func (check *checker) trace(pos token.Pos, format string, args ...interface{}) { - check.pos = append(check.pos, pos) - check.printTrace(format, args) -} - -func (check *checker) untrace(format string, args ...interface{}) { - if len(format) > 0 { - check.printTrace(format, args) - } - check.pos = check.pos[:len(check.pos)-1] -} - -func (check *checker) formatMsg(format string, args []interface{}) string { - for i, arg := range args { - switch a := arg.(type) { - case token.Pos: - args[i] = check.fset.Position(a) - case ast.Expr: - args[i] = exprString(a) - case Type: - args[i] = typeString(a) - case operand: - panic("internal error: should always pass *operand") - } - } - return fmt.Sprintf(format, args...) -} - -// dump is only needed for debugging -func (check *checker) dump(format string, args ...interface{}) { - fmt.Println(check.formatMsg(format, args)) -} - -func (check *checker) err(err error) { - if check.firsterr == nil { - check.firsterr = err - } - f := check.ctxt.Error - if f == nil { - panic(bailout{}) // report only first error - } - f(err) -} - -func (check *checker) errorf(pos token.Pos, format string, args ...interface{}) { - check.err(fmt.Errorf("%s: %s", check.fset.Position(pos), check.formatMsg(format, args))) -} - -func (check *checker) invalidAST(pos token.Pos, format string, args ...interface{}) { - check.errorf(pos, "invalid AST: "+format, args...) -} - -func (check *checker) invalidArg(pos token.Pos, format string, args ...interface{}) { - check.errorf(pos, "invalid argument: "+format, args...) -} - -func (check *checker) invalidOp(pos token.Pos, format string, args ...interface{}) { - check.errorf(pos, "invalid operation: "+format, args...) -} - -// exprString returns a (simplified) string representation for an expression. -func exprString(expr ast.Expr) string { - var buf bytes.Buffer - writeExpr(&buf, expr) - return buf.String() -} - -// TODO(gri) Need to merge with typeString since some expressions are types (try: ([]int)(a)) -func writeExpr(buf *bytes.Buffer, expr ast.Expr) { - switch x := expr.(type) { - case *ast.Ident: - buf.WriteString(x.Name) - - case *ast.BasicLit: - buf.WriteString(x.Value) - - case *ast.FuncLit: - buf.WriteString("(func literal)") - - case *ast.CompositeLit: - buf.WriteString("(composite literal)") - - case *ast.ParenExpr: - buf.WriteByte('(') - writeExpr(buf, x.X) - buf.WriteByte(')') - - case *ast.SelectorExpr: - writeExpr(buf, x.X) - buf.WriteByte('.') - buf.WriteString(x.Sel.Name) - - case *ast.IndexExpr: - writeExpr(buf, x.X) - buf.WriteByte('[') - writeExpr(buf, x.Index) - buf.WriteByte(']') - - case *ast.SliceExpr: - writeExpr(buf, x.X) - buf.WriteByte('[') - if x.Low != nil { - writeExpr(buf, x.Low) - } - buf.WriteByte(':') - if x.High != nil { - writeExpr(buf, x.High) - } - buf.WriteByte(']') - - case *ast.TypeAssertExpr: - writeExpr(buf, x.X) - buf.WriteString(".(...)") - - case *ast.CallExpr: - writeExpr(buf, x.Fun) - buf.WriteByte('(') - for i, arg := range x.Args { - if i > 0 { - buf.WriteString(", ") - } - writeExpr(buf, arg) - } - buf.WriteByte(')') - - case *ast.StarExpr: - buf.WriteByte('*') - writeExpr(buf, x.X) - - case *ast.UnaryExpr: - buf.WriteString(x.Op.String()) - writeExpr(buf, x.X) - - case *ast.BinaryExpr: - // The AST preserves source-level parentheses so there is - // no need to introduce parentheses here for correctness. - writeExpr(buf, x.X) - buf.WriteByte(' ') - buf.WriteString(x.Op.String()) - buf.WriteByte(' ') - writeExpr(buf, x.Y) - - default: - fmt.Fprintf(buf, "<expr %T>", x) - } -} - -// typeString returns a string representation for typ. -func typeString(typ Type) string { - var buf bytes.Buffer - writeType(&buf, typ) - return buf.String() -} - -func writeParams(buf *bytes.Buffer, params []*Var, isVariadic bool) { - buf.WriteByte('(') - for i, par := range params { - if i > 0 { - buf.WriteString(", ") - } - if par.Name != "" { - buf.WriteString(par.Name) - buf.WriteByte(' ') - } - if isVariadic && i == len(params)-1 { - buf.WriteString("...") - } - writeType(buf, par.Type) - } - buf.WriteByte(')') -} - -func writeSignature(buf *bytes.Buffer, sig *Signature) { - writeParams(buf, sig.Params, sig.IsVariadic) - if len(sig.Results) == 0 { - // no result - return - } - - buf.WriteByte(' ') - if len(sig.Results) == 1 && sig.Results[0].Name == "" { - // single unnamed result - writeType(buf, sig.Results[0].Type.(Type)) - return - } - - // multiple or named result(s) - writeParams(buf, sig.Results, false) -} - -func writeType(buf *bytes.Buffer, typ Type) { - switch t := typ.(type) { - case nil: - buf.WriteString("<nil>") - - case *Basic: - buf.WriteString(t.Name) - - case *Array: - fmt.Fprintf(buf, "[%d]", t.Len) - writeType(buf, t.Elt) - - case *Slice: - buf.WriteString("[]") - writeType(buf, t.Elt) - - case *Struct: - buf.WriteString("struct{") - for i, f := range t.Fields { - if i > 0 { - buf.WriteString("; ") - } - if !f.IsAnonymous { - buf.WriteString(f.Name) - buf.WriteByte(' ') - } - writeType(buf, f.Type) - if f.Tag != "" { - fmt.Fprintf(buf, " %q", f.Tag) - } - } - buf.WriteByte('}') - - case *Pointer: - buf.WriteByte('*') - writeType(buf, t.Base) - - case *Result: - writeParams(buf, t.Values, false) - - case *Signature: - buf.WriteString("func") - writeSignature(buf, t) - - case *builtin: - fmt.Fprintf(buf, "<type of %s>", t.name) - - case *Interface: - buf.WriteString("interface{") - for i, m := range t.Methods { - if i > 0 { - buf.WriteString("; ") - } - buf.WriteString(m.Name) - writeSignature(buf, m.Type) - } - buf.WriteByte('}') - - case *Map: - buf.WriteString("map[") - writeType(buf, t.Key) - buf.WriteByte(']') - writeType(buf, t.Elt) - - case *Chan: - var s string - switch t.Dir { - case ast.SEND: - s = "chan<- " - case ast.RECV: - s = "<-chan " - default: - s = "chan " - } - buf.WriteString(s) - writeType(buf, t.Elt) - - case *NamedType: - s := "<NamedType w/o object>" - if t.Obj != nil { - s = t.Obj.GetName() - } - buf.WriteString(s) - - default: - fmt.Fprintf(buf, "<type %T>", t) - } -} - -func (t *Array) String() string { return typeString(t) } -func (t *Basic) String() string { return typeString(t) } -func (t *Chan) String() string { return typeString(t) } -func (t *Interface) String() string { return typeString(t) } -func (t *Map) String() string { return typeString(t) } -func (t *NamedType) String() string { return typeString(t) } -func (t *Pointer) String() string { return typeString(t) } -func (t *Result) String() string { return typeString(t) } -func (t *Signature) String() string { return typeString(t) } -func (t *Slice) String() string { return typeString(t) } -func (t *Struct) String() string { return typeString(t) } -func (t *builtin) String() string { return typeString(t) } diff --git a/gcc-4.8.1/libgo/go/go/types/exportdata.go b/gcc-4.8.1/libgo/go/go/types/exportdata.go deleted file mode 100644 index 1f6a3c725..000000000 --- a/gcc-4.8.1/libgo/go/go/types/exportdata.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements FindGcExportData. - -package types - -import ( - "bufio" - "errors" - "fmt" - "io" - "strconv" - "strings" -) - -func readGopackHeader(r *bufio.Reader) (name string, size int, err error) { - // See $GOROOT/include/ar.h. - hdr := make([]byte, 16+12+6+6+8+10+2) - _, err = io.ReadFull(r, hdr) - if err != nil { - return - } - // leave for debugging - if false { - fmt.Printf("header: %s", hdr) - } - s := strings.TrimSpace(string(hdr[16+12+6+6+8:][:10])) - size, err = strconv.Atoi(s) - if err != nil || hdr[len(hdr)-2] != '`' || hdr[len(hdr)-1] != '\n' { - err = errors.New("invalid archive header") - return - } - name = strings.TrimSpace(string(hdr[:16])) - return -} - -// FindGcExportData positions the reader r at the beginning of the -// export data section of an underlying GC-created object/archive -// file by reading from it. The reader must be positioned at the -// start of the file before calling this function. -// -func FindGcExportData(r *bufio.Reader) (err error) { - // Read first line to make sure this is an object file. - line, err := r.ReadSlice('\n') - if err != nil { - return - } - if string(line) == "!<arch>\n" { - // Archive file. Scan to __.PKGDEF, which should - // be second archive entry. - var name string - var size int - - // First entry should be __.GOSYMDEF. - // Older archives used __.SYMDEF, so allow that too. - // Read and discard. - if name, size, err = readGopackHeader(r); err != nil { - return - } - if name != "__.SYMDEF" && name != "__.GOSYMDEF" { - err = errors.New("go archive does not begin with __.SYMDEF or __.GOSYMDEF") - return - } - const block = 4096 - tmp := make([]byte, block) - for size > 0 { - n := size - if n > block { - n = block - } - if _, err = io.ReadFull(r, tmp[:n]); err != nil { - return - } - size -= n - } - - // Second entry should be __.PKGDEF. - if name, size, err = readGopackHeader(r); err != nil { - return - } - if name != "__.PKGDEF" { - err = errors.New("go archive is missing __.PKGDEF") - return - } - - // Read first line of __.PKGDEF data, so that line - // is once again the first line of the input. - if line, err = r.ReadSlice('\n'); err != nil { - return - } - } - - // Now at __.PKGDEF in archive or still at beginning of file. - // Either way, line should begin with "go object ". - if !strings.HasPrefix(string(line), "go object ") { - err = errors.New("not a go object file") - return - } - - // Skip over object header to export data. - // Begins after first line with $$. - for line[0] != '$' { - if line, err = r.ReadSlice('\n'); err != nil { - return - } - } - - return -} diff --git a/gcc-4.8.1/libgo/go/go/types/expr.go b/gcc-4.8.1/libgo/go/go/types/expr.go deleted file mode 100644 index 696a0cae6..000000000 --- a/gcc-4.8.1/libgo/go/go/types/expr.go +++ /dev/null @@ -1,1334 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements typechecking of expressions. - -package types - -import ( - "go/ast" - "go/token" - "strconv" -) - -// TODO(gri) Cleanups -// - don't print error messages referring to invalid types (they are likely spurious errors) -// - simplify invalid handling: maybe just use Typ[Invalid] as marker, get rid of invalid Mode for values? -// - rethink error handling: should all callers check if x.mode == valid after making a call? -// - at the moment, iota is passed around almost everywhere - in many places we know it cannot be used -// - use "" or "_" consistently for anonymous identifiers? (e.g. reeceivers that have no name) - -// TODO(gri) API issues -// - clients need access to builtins type information -// - API tests are missing (e.g., identifiers should be handled as expressions in callbacks) - -func (check *checker) collectParams(list *ast.FieldList, variadicOk bool) (params []*Var, isVariadic bool) { - if list == nil { - return - } - var last *Var - for i, field := range list.List { - ftype := field.Type - if t, _ := ftype.(*ast.Ellipsis); t != nil { - ftype = t.Elt - if variadicOk && i == len(list.List)-1 { - isVariadic = true - } else { - check.invalidAST(field.Pos(), "... not permitted") - // ok to continue - } - } - // the parser ensures that f.Tag is nil and we don't - // care if a constructed AST contains a non-nil tag - typ := check.typ(ftype, true) - if len(field.Names) > 0 { - // named parameter - for _, name := range field.Names { - par := check.lookup(name).(*Var) - par.Type = typ - last = par - copy := *par - params = append(params, ©) - } - } else { - // anonymous parameter - par := &Var{Type: typ} - last = nil // not accessible inside function - params = append(params, par) - } - } - // For a variadic function, change the last parameter's object type - // from T to []T (this is the type used inside the function), but - // keep the params list unchanged (this is the externally visible type). - if isVariadic && last != nil { - last.Type = &Slice{Elt: last.Type} - } - return -} - -func (check *checker) collectMethods(list *ast.FieldList) (methods []*Method) { - if list == nil { - return - } - for _, f := range list.List { - typ := check.typ(f.Type, len(f.Names) > 0) // cycles are not ok for embedded interfaces - // the parser ensures that f.Tag is nil and we don't - // care if a constructed AST contains a non-nil tag - if len(f.Names) > 0 { - // methods (the parser ensures that there's only one - // and we don't care if a constructed AST has more) - sig, ok := typ.(*Signature) - if !ok { - check.invalidAST(f.Type.Pos(), "%s is not a method signature", typ) - continue - } - for _, name := range f.Names { - methods = append(methods, &Method{QualifiedName{check.pkg, name.Name}, sig}) - } - } else { - // embedded interface - utyp := underlying(typ) - if ityp, ok := utyp.(*Interface); ok { - methods = append(methods, ityp.Methods...) - } else if utyp != Typ[Invalid] { - // if utyp is invalid, don't complain (the root cause was reported before) - check.errorf(f.Type.Pos(), "%s is not an interface type", typ) - } - } - } - // Check for double declarations. - // The parser inserts methods into an interface-local scope, so local - // double declarations are reported by the parser already. We need to - // check again for conflicts due to embedded interfaces. This will lead - // to a 2nd error message if the double declaration was reported before - // by the parser. - // TODO(gri) clean this up a bit - seen := make(map[string]bool) - for _, m := range methods { - if seen[m.Name] { - check.errorf(list.Pos(), "multiple methods named %s", m.Name) - return // keep multiple entries, lookup will only return the first entry - } - seen[m.Name] = true - } - return -} - -func (check *checker) tag(t *ast.BasicLit) string { - if t != nil { - if t.Kind == token.STRING { - if val, err := strconv.Unquote(t.Value); err == nil { - return val - } - } - check.invalidAST(t.Pos(), "incorrect tag syntax: %q", t.Value) - } - return "" -} - -func (check *checker) collectFields(list *ast.FieldList, cycleOk bool) (fields []*Field) { - if list == nil { - return - } - for _, f := range list.List { - typ := check.typ(f.Type, cycleOk) - tag := check.tag(f.Tag) - if len(f.Names) > 0 { - // named fields - for _, name := range f.Names { - fields = append(fields, &Field{QualifiedName{check.pkg, name.Name}, typ, tag, false}) - } - } else { - // anonymous field - switch t := deref(typ).(type) { - case *Basic: - fields = append(fields, &Field{QualifiedName{check.pkg, t.Name}, typ, tag, true}) - case *NamedType: - fields = append(fields, &Field{QualifiedName{check.pkg, t.Obj.GetName()}, typ, tag, true}) - default: - if typ != Typ[Invalid] { - check.invalidAST(f.Type.Pos(), "anonymous field type %s must be named", typ) - } - } - } - } - return -} - -type opPredicates map[token.Token]func(Type) bool - -var unaryOpPredicates = opPredicates{ - token.ADD: isNumeric, - token.SUB: isNumeric, - token.XOR: isInteger, - token.NOT: isBoolean, -} - -func (check *checker) op(m opPredicates, x *operand, op token.Token) bool { - if pred := m[op]; pred != nil { - if !pred(x.typ) { - check.invalidOp(x.pos(), "operator %s not defined for %s", op, x) - return false - } - } else { - check.invalidAST(x.pos(), "unknown operator %s", op) - return false - } - return true -} - -func (check *checker) unary(x *operand, op token.Token) { - switch op { - case token.AND: - // spec: "As an exception to the addressability - // requirement x may also be a composite literal." - if _, ok := unparen(x.expr).(*ast.CompositeLit); ok { - x.mode = variable - } - if x.mode != variable { - check.invalidOp(x.pos(), "cannot take address of %s", x) - goto Error - } - x.typ = &Pointer{Base: x.typ} - return - - case token.ARROW: - typ, ok := underlying(x.typ).(*Chan) - if !ok { - check.invalidOp(x.pos(), "cannot receive from non-channel %s", x) - goto Error - } - if typ.Dir&ast.RECV == 0 { - check.invalidOp(x.pos(), "cannot receive from send-only channel %s", x) - goto Error - } - x.mode = valueok - x.typ = typ.Elt - return - } - - if !check.op(unaryOpPredicates, x, op) { - goto Error - } - - if x.mode == constant { - typ := underlying(x.typ).(*Basic) - x.val = unaryOpConst(x.val, op, typ) - // Typed constants must be representable in - // their type after each constant operation. - check.isRepresentable(x, typ) - return - } - - x.mode = value - // x.typ remains unchanged - return - -Error: - x.mode = invalid -} - -func isShift(op token.Token) bool { - return op == token.SHL || op == token.SHR -} - -func isComparison(op token.Token) bool { - // Note: tokens are not ordered well to make this much easier - switch op { - case token.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ: - return true - } - return false -} - -// isRepresentable checks that a constant operand is representable in the given type. -func (check *checker) isRepresentable(x *operand, typ *Basic) { - if x.mode != constant || isUntyped(typ) { - return - } - - if !isRepresentableConst(x.val, typ.Kind) { - var msg string - if isNumeric(x.typ) && isNumeric(typ) { - msg = "%s overflows %s" - } else { - msg = "cannot convert %s to %s" - } - check.errorf(x.pos(), msg, x, typ) - x.mode = invalid - } -} - -// convertUntyped attempts to set the type of an untyped value to the target type. -func (check *checker) convertUntyped(x *operand, target Type) { - if x.mode == invalid || !isUntyped(x.typ) { - return - } - - // TODO(gri) Sloppy code - clean up. This function is central - // to assignment and expression checking. - - if isUntyped(target) { - // both x and target are untyped - xkind := x.typ.(*Basic).Kind - tkind := target.(*Basic).Kind - if isNumeric(x.typ) && isNumeric(target) { - if xkind < tkind { - x.typ = target - } - } else if xkind != tkind { - goto Error - } - return - } - - // typed target - switch t := underlying(target).(type) { - case *Basic: - check.isRepresentable(x, t) - case *Interface: - if !x.isNil() && len(t.Methods) > 0 /* empty interfaces are ok */ { - goto Error - } - case *Pointer, *Signature, *Slice, *Map, *Chan: - if !x.isNil() { - goto Error - } - default: - unreachable() - } - - x.typ = target - return - -Error: - check.errorf(x.pos(), "cannot convert %s to %s", x, target) - x.mode = invalid -} - -func (check *checker) comparison(x, y *operand, op token.Token) { - // TODO(gri) deal with interface vs non-interface comparison - - valid := false - if x.isAssignable(y.typ) || y.isAssignable(x.typ) { - switch op { - case token.EQL, token.NEQ: - valid = isComparable(x.typ) || - x.isNil() && hasNil(y.typ) || - y.isNil() && hasNil(x.typ) - case token.LSS, token.LEQ, token.GTR, token.GEQ: - valid = isOrdered(x.typ) - default: - unreachable() - } - } - - if !valid { - check.invalidOp(x.pos(), "cannot compare %s %s %s", x, op, y) - x.mode = invalid - return - } - - if x.mode == constant && y.mode == constant { - x.val = compareConst(x.val, y.val, op) - } else { - x.mode = value - } - - x.typ = Typ[UntypedBool] -} - -// untyped lhs shift operands convert to the hint type -func (check *checker) shift(x, y *operand, op token.Token, hint Type) { - // spec: "The right operand in a shift expression must have unsigned - // integer type or be an untyped constant that can be converted to - // unsigned integer type." - switch { - case isInteger(y.typ) && isUnsigned(y.typ): - // nothing to do - case y.mode == constant && isUntyped(y.typ) && isRepresentableConst(y.val, UntypedInt): - y.typ = Typ[UntypedInt] - default: - check.invalidOp(y.pos(), "shift count %s must be unsigned integer", y) - x.mode = invalid - return - } - - // spec: "If the left operand of a non-constant shift expression is - // an untyped constant, the type of the constant is what it would be - // if the shift expression were replaced by its left operand alone; - // the type is int if it cannot be determined from the context (for - // instance, if the shift expression is an operand in a comparison - // against an untyped constant)". - if x.mode == constant && isUntyped(x.typ) { - if y.mode == constant { - // constant shift - accept values of any (untyped) type - // as long as the value is representable as an integer - if x.mode == constant && isUntyped(x.typ) { - if isRepresentableConst(x.val, UntypedInt) { - x.typ = Typ[UntypedInt] - } - } - } else { - // non-constant shift - if hint == nil { - // TODO(gri) need to check for x.isNil (see other uses of defaultType) - hint = defaultType(x.typ) - } - check.convertUntyped(x, hint) - if x.mode == invalid { - return - } - } - } - - if !isInteger(x.typ) { - check.invalidOp(x.pos(), "shifted operand %s must be integer", x) - x.mode = invalid - return - } - - if y.mode == constant { - const stupidShift = 1024 - s, ok := y.val.(int64) - if !ok || s < 0 || s >= stupidShift { - check.invalidOp(y.pos(), "%s: stupid shift", y) - x.mode = invalid - return - } - if x.mode == constant { - x.val = shiftConst(x.val, uint(s), op) - return - } - } - - x.mode = value - // x.typ is already set -} - -var binaryOpPredicates = opPredicates{ - token.ADD: func(typ Type) bool { return isNumeric(typ) || isString(typ) }, - token.SUB: isNumeric, - token.MUL: isNumeric, - token.QUO: isNumeric, - token.REM: isInteger, - - token.AND: isInteger, - token.OR: isInteger, - token.XOR: isInteger, - token.AND_NOT: isInteger, - - token.LAND: isBoolean, - token.LOR: isBoolean, -} - -func (check *checker) binary(x, y *operand, op token.Token, hint Type) { - if isShift(op) { - check.shift(x, y, op, hint) - return - } - - check.convertUntyped(x, y.typ) - if x.mode == invalid { - return - } - check.convertUntyped(y, x.typ) - if y.mode == invalid { - x.mode = invalid - return - } - - if isComparison(op) { - check.comparison(x, y, op) - return - } - - if !IsIdentical(x.typ, y.typ) { - check.invalidOp(x.pos(), "mismatched types %s and %s", x.typ, y.typ) - x.mode = invalid - return - } - - if !check.op(binaryOpPredicates, x, op) { - x.mode = invalid - return - } - - if (op == token.QUO || op == token.REM) && y.mode == constant && isZeroConst(y.val) { - check.invalidOp(y.pos(), "division by zero") - x.mode = invalid - return - } - - if x.mode == constant && y.mode == constant { - typ := underlying(x.typ).(*Basic) - x.val = binaryOpConst(x.val, y.val, op, typ) - // Typed constants must be representable in - // their type after each constant operation. - check.isRepresentable(x, typ) - return - } - - x.mode = value - // x.typ is unchanged -} - -// index checks an index expression for validity. If length >= 0, it is the upper -// bound for the index. The result is a valid index >= 0, or a negative value. -// -func (check *checker) index(index ast.Expr, length int64, iota int) int64 { - var x operand - - check.expr(&x, index, nil, iota) - if !x.isInteger() { - check.errorf(x.pos(), "index %s must be integer", &x) - return -1 - } - if x.mode != constant { - return -1 // we cannot check more - } - // The spec doesn't require int64 indices, but perhaps it should. - i, ok := x.val.(int64) - if !ok { - check.errorf(x.pos(), "stupid index %s", &x) - return -1 - } - if i < 0 { - check.errorf(x.pos(), "index %s must not be negative", &x) - return -1 - } - if length >= 0 && i >= length { - check.errorf(x.pos(), "index %s is out of bounds (>= %d)", &x, length) - return -1 - } - - return i -} - -// compositeLitKey resolves unresolved composite literal keys. -// For details, see comment in go/parser/parser.go, method parseElement. -func (check *checker) compositeLitKey(key ast.Expr) { - if ident, ok := key.(*ast.Ident); ok && ident.Obj == nil { - if obj := check.pkg.Scope.Lookup(ident.Name); obj != nil { - check.register(ident, obj) - } else { - check.errorf(ident.Pos(), "undeclared name: %s", ident.Name) - } - } -} - -// indexElts checks the elements (elts) of an array or slice composite literal -// against the literal's element type (typ), and the element indices against -// the literal length if known (length >= 0). It returns the length of the -// literal (maximum index value + 1). -// -func (check *checker) indexedElts(elts []ast.Expr, typ Type, length int64, iota int) int64 { - visited := make(map[int64]bool, len(elts)) - var index, max int64 - for _, e := range elts { - // determine and check index - validIndex := false - eval := e - if kv, _ := e.(*ast.KeyValueExpr); kv != nil { - check.compositeLitKey(kv.Key) - if i := check.index(kv.Key, length, iota); i >= 0 { - index = i - validIndex = true - } - eval = kv.Value - } else if length >= 0 && index >= length { - check.errorf(e.Pos(), "index %d is out of bounds (>= %d)", index, length) - } else { - validIndex = true - } - - // if we have a valid index, check for duplicate entries - if validIndex { - if visited[index] { - check.errorf(e.Pos(), "duplicate index %d in array or slice literal", index) - } - visited[index] = true - } - index++ - if index > max { - max = index - } - - // check element against composite literal element type - var x operand - check.expr(&x, eval, typ, iota) - if !x.isAssignable(typ) { - check.errorf(x.pos(), "cannot use %s as %s value in array or slice literal", &x, typ) - } - } - return max -} - -// argument typechecks passing an argument arg (if arg != nil) or -// x (if arg == nil) to the i'th parameter of the given signature. -// If passSlice is set, the argument is followed by ... in the call. -// -func (check *checker) argument(sig *Signature, i int, arg ast.Expr, x *operand, passSlice bool) { - // determine parameter - var par *Var - n := len(sig.Params) - if i < n { - par = sig.Params[i] - } else if sig.IsVariadic { - par = sig.Params[n-1] - } else { - check.errorf(arg.Pos(), "too many arguments") - return - } - - // determine argument - var z operand - z.mode = variable - z.expr = nil // TODO(gri) can we do better here? (for good error messages) - z.typ = par.Type - - if arg != nil { - check.expr(x, arg, z.typ, -1) - } - if x.mode == invalid { - return // ignore this argument - } - - // check last argument of the form x... - if passSlice { - if i+1 != n { - check.errorf(x.pos(), "can only use ... with matching parameter") - return // ignore this argument - } - // spec: "If the final argument is assignable to a slice type []T, - // it may be passed unchanged as the value for a ...T parameter if - // the argument is followed by ..." - z.typ = &Slice{Elt: z.typ} // change final parameter type to []T - } - - check.assignOperand(&z, x) -} - -var emptyResult Result - -func (check *checker) callExpr(x *operand) { - var typ Type - var val interface{} - switch x.mode { - case invalid: - return // nothing to do - case novalue: - typ = &emptyResult - case constant: - typ = x.typ - val = x.val - default: - typ = x.typ - } - check.ctxt.Expr(x.expr, typ, val) -} - -// rawExpr typechecks expression e and initializes x with the expression -// value or type. If an error occurred, x.mode is set to invalid. -// A hint != nil is used as operand type for untyped shifted operands; -// iota >= 0 indicates that the expression is part of a constant declaration. -// cycleOk indicates whether it is ok for a type expression to refer to itself. -// -func (check *checker) rawExpr(x *operand, e ast.Expr, hint Type, iota int, cycleOk bool) { - if trace { - c := "" - if cycleOk { - c = " ⨁" - } - check.trace(e.Pos(), "%s (%s, %d%s)", e, typeString(hint), iota, c) - defer check.untrace("=> %s", x) - } - - if check.ctxt.Expr != nil { - defer check.callExpr(x) - } - - switch e := e.(type) { - case *ast.BadExpr: - goto Error // error was reported before - - case *ast.Ident: - if e.Name == "_" { - check.invalidOp(e.Pos(), "cannot use _ as value or type") - goto Error - } - obj := check.lookup(e) - if obj == nil { - goto Error // error was reported before - } - check.object(obj, cycleOk) - switch obj := obj.(type) { - case *Package: - check.errorf(e.Pos(), "use of package %s not in selector", obj.Name) - goto Error - case *Const: - if obj.Val == nil { - goto Error // cycle detected - } - x.mode = constant - if obj == universeIota { - if iota < 0 { - check.invalidAST(e.Pos(), "cannot use iota outside constant declaration") - goto Error - } - x.val = int64(iota) - } else { - x.val = obj.Val - } - case *TypeName: - x.mode = typexpr - if !cycleOk && underlying(obj.Type) == nil { - check.errorf(obj.spec.Pos(), "illegal cycle in declaration of %s", obj.Name) - x.expr = e - x.typ = Typ[Invalid] - return // don't goto Error - need x.mode == typexpr - } - case *Var: - x.mode = variable - case *Func: - x.mode = value - default: - unreachable() - } - x.typ = obj.GetType() - - case *ast.Ellipsis: - // ellipses are handled explicitly where they are legal - // (array composite literals and parameter lists) - check.errorf(e.Pos(), "invalid use of '...'") - goto Error - - case *ast.BasicLit: - x.setConst(e.Kind, e.Value) - if x.mode == invalid { - check.invalidAST(e.Pos(), "invalid literal %v", e.Value) - goto Error - } - - case *ast.FuncLit: - if sig, ok := check.typ(e.Type, false).(*Signature); ok { - x.mode = value - x.typ = sig - check.later(nil, sig, e.Body) - } else { - check.invalidAST(e.Pos(), "invalid function literal %s", e) - goto Error - } - - case *ast.CompositeLit: - typ := hint - openArray := false - if e.Type != nil { - // [...]T array types may only appear with composite literals. - // Check for them here so we don't have to handle ... in general. - typ = nil - if atyp, _ := e.Type.(*ast.ArrayType); atyp != nil && atyp.Len != nil { - if ellip, _ := atyp.Len.(*ast.Ellipsis); ellip != nil && ellip.Elt == nil { - // We have an "open" [...]T array type. - // Create a new ArrayType with unknown length (-1) - // and finish setting it up after analyzing the literal. - typ = &Array{Len: -1, Elt: check.typ(atyp.Elt, cycleOk)} - openArray = true - } - } - if typ == nil { - typ = check.typ(e.Type, false) - } - } - if typ == nil { - check.errorf(e.Pos(), "missing type in composite literal") - goto Error - } - - switch utyp := underlying(deref(typ)).(type) { - case *Struct: - if len(e.Elts) == 0 { - break - } - fields := utyp.Fields - if _, ok := e.Elts[0].(*ast.KeyValueExpr); ok { - // all elements must have keys - visited := make([]bool, len(fields)) - for _, e := range e.Elts { - kv, _ := e.(*ast.KeyValueExpr) - if kv == nil { - check.errorf(e.Pos(), "mixture of field:value and value elements in struct literal") - continue - } - key, _ := kv.Key.(*ast.Ident) - if key == nil { - check.errorf(kv.Pos(), "invalid field name %s in struct literal", kv.Key) - continue - } - i := utyp.fieldIndex(key.Name) - if i < 0 { - check.errorf(kv.Pos(), "unknown field %s in struct literal", key.Name) - continue - } - // 0 <= i < len(fields) - if visited[i] { - check.errorf(kv.Pos(), "duplicate field name %s in struct literal", key.Name) - continue - } - visited[i] = true - check.expr(x, kv.Value, nil, iota) - etyp := fields[i].Type - if !x.isAssignable(etyp) { - check.errorf(x.pos(), "cannot use %s as %s value in struct literal", x, etyp) - continue - } - } - } else { - // no element must have a key - for i, e := range e.Elts { - if kv, _ := e.(*ast.KeyValueExpr); kv != nil { - check.errorf(kv.Pos(), "mixture of field:value and value elements in struct literal") - continue - } - check.expr(x, e, nil, iota) - if i >= len(fields) { - check.errorf(x.pos(), "too many values in struct literal") - break // cannot continue - } - // i < len(fields) - etyp := fields[i].Type - if !x.isAssignable(etyp) { - check.errorf(x.pos(), "cannot use %s as %s value in struct literal", x, etyp) - continue - } - } - if len(e.Elts) < len(fields) { - check.errorf(e.Rbrace, "too few values in struct literal") - // ok to continue - } - } - - case *Array: - n := check.indexedElts(e.Elts, utyp.Elt, utyp.Len, iota) - // if we have an "open" [...]T array, set the length now that we know it - if openArray { - utyp.Len = n - } - - case *Slice: - check.indexedElts(e.Elts, utyp.Elt, -1, iota) - - case *Map: - visited := make(map[interface{}]bool, len(e.Elts)) - for _, e := range e.Elts { - kv, _ := e.(*ast.KeyValueExpr) - if kv == nil { - check.errorf(e.Pos(), "missing key in map literal") - continue - } - check.compositeLitKey(kv.Key) - check.expr(x, kv.Key, nil, iota) - if !x.isAssignable(utyp.Key) { - check.errorf(x.pos(), "cannot use %s as %s key in map literal", x, utyp.Key) - continue - } - if x.mode == constant { - if visited[x.val] { - check.errorf(x.pos(), "duplicate key %s in map literal", x.val) - continue - } - visited[x.val] = true - } - check.expr(x, kv.Value, utyp.Elt, iota) - if !x.isAssignable(utyp.Elt) { - check.errorf(x.pos(), "cannot use %s as %s value in map literal", x, utyp.Elt) - continue - } - } - - default: - check.errorf(e.Pos(), "%s is not a valid composite literal type", typ) - goto Error - } - - x.mode = value - x.typ = typ - - case *ast.ParenExpr: - check.rawExpr(x, e.X, hint, iota, cycleOk) - - case *ast.SelectorExpr: - sel := e.Sel.Name - // If the identifier refers to a package, handle everything here - // so we don't need a "package" mode for operands: package names - // can only appear in qualified identifiers which are mapped to - // selector expressions. - if ident, ok := e.X.(*ast.Ident); ok { - if pkg, ok := check.lookup(ident).(*Package); ok { - exp := pkg.Scope.Lookup(sel) - if exp == nil { - check.errorf(e.Sel.Pos(), "cannot refer to unexported %s", sel) - goto Error - } - check.register(e.Sel, exp) - // Simplified version of the code for *ast.Idents: - // - imported packages use types.Scope and types.Objects - // - imported objects are always fully initialized - switch exp := exp.(type) { - case *Const: - assert(exp.Val != nil) - x.mode = constant - x.typ = exp.Type - x.val = exp.Val - case *TypeName: - x.mode = typexpr - x.typ = exp.Type - case *Var: - x.mode = variable - x.typ = exp.Type - case *Func: - x.mode = value - x.typ = exp.Type - default: - unreachable() - } - x.expr = e - return - } - } - - check.exprOrType(x, e.X, nil, iota, false) - if x.mode == invalid { - goto Error - } - mode, typ := lookupField(x.typ, QualifiedName{check.pkg, sel}) - if mode == invalid { - check.invalidOp(e.Pos(), "%s has no single field or method %s", x, sel) - goto Error - } - if x.mode == typexpr { - // method expression - sig, ok := typ.(*Signature) - if !ok { - check.invalidOp(e.Pos(), "%s has no method %s", x, sel) - goto Error - } - // the receiver type becomes the type of the first function - // argument of the method expression's function type - // TODO(gri) at the moment, method sets don't correctly track - // pointer vs non-pointer receivers => typechecker is too lenient - x.mode = value - x.typ = &Signature{ - Params: append([]*Var{{Type: x.typ}}, sig.Params...), - Results: sig.Results, - IsVariadic: sig.IsVariadic, - } - } else { - // regular selector - x.mode = mode - x.typ = typ - } - - case *ast.IndexExpr: - check.expr(x, e.X, hint, iota) - - valid := false - length := int64(-1) // valid if >= 0 - switch typ := underlying(x.typ).(type) { - case *Basic: - if isString(typ) { - valid = true - if x.mode == constant { - length = int64(len(x.val.(string))) - } - // an indexed string always yields a byte value - // (not a constant) even if the string and the - // index are constant - x.mode = value - x.typ = Typ[Byte] - } - - case *Array: - valid = true - length = typ.Len - if x.mode != variable { - x.mode = value - } - x.typ = typ.Elt - - case *Pointer: - if typ, _ := underlying(typ.Base).(*Array); typ != nil { - valid = true - length = typ.Len - x.mode = variable - x.typ = typ.Elt - } - - case *Slice: - valid = true - x.mode = variable - x.typ = typ.Elt - - case *Map: - var key operand - check.expr(&key, e.Index, nil, iota) - if key.mode == invalid || !key.isAssignable(typ.Key) { - check.invalidOp(x.pos(), "cannot use %s as map index of type %s", &key, typ.Key) - goto Error - } - x.mode = valueok - x.typ = typ.Elt - x.expr = e - return - } - - if !valid { - check.invalidOp(x.pos(), "cannot index %s", x) - goto Error - } - - if e.Index == nil { - check.invalidAST(e.Pos(), "missing index expression for %s", x) - return - } - - check.index(e.Index, length, iota) - // ok to continue - - case *ast.SliceExpr: - check.expr(x, e.X, hint, iota) - - valid := false - length := int64(-1) // valid if >= 0 - switch typ := underlying(x.typ).(type) { - case *Basic: - if isString(typ) { - valid = true - if x.mode == constant { - length = int64(len(x.val.(string))) + 1 // +1 for slice - } - // a sliced string always yields a string value - // of the same type as the original string (not - // a constant) even if the string and the indices - // are constant - x.mode = value - // x.typ doesn't change - } - - case *Array: - valid = true - length = typ.Len + 1 // +1 for slice - if x.mode != variable { - check.invalidOp(x.pos(), "cannot slice %s (value not addressable)", x) - goto Error - } - x.typ = &Slice{Elt: typ.Elt} - - case *Pointer: - if typ, _ := underlying(typ.Base).(*Array); typ != nil { - valid = true - length = typ.Len + 1 // +1 for slice - x.mode = variable - x.typ = &Slice{Elt: typ.Elt} - } - - case *Slice: - valid = true - x.mode = variable - // x.typ doesn't change - } - - if !valid { - check.invalidOp(x.pos(), "cannot slice %s", x) - goto Error - } - - lo := int64(0) - if e.Low != nil { - lo = check.index(e.Low, length, iota) - } - - hi := int64(-1) - if e.High != nil { - hi = check.index(e.High, length, iota) - } else if length >= 0 { - hi = length - } - - if lo >= 0 && hi >= 0 && lo > hi { - check.errorf(e.Low.Pos(), "inverted slice range: %d > %d", lo, hi) - // ok to continue - } - - case *ast.TypeAssertExpr: - check.expr(x, e.X, hint, iota) - if x.mode == invalid { - goto Error - } - var T *Interface - if T, _ = underlying(x.typ).(*Interface); T == nil { - check.invalidOp(x.pos(), "%s is not an interface", x) - goto Error - } - // x.(type) expressions are handled explicitly in type switches - if e.Type == nil { - check.errorf(e.Pos(), "use of .(type) outside type switch") - goto Error - } - typ := check.typ(e.Type, false) - if typ == Typ[Invalid] { - goto Error - } - if method, wrongType := missingMethod(typ, T); method != nil { - var msg string - if wrongType { - msg = "%s cannot have dynamic type %s (wrong type for method %s)" - } else { - msg = "%s cannot have dynamic type %s (missing method %s)" - } - check.errorf(e.Type.Pos(), msg, x, typ, method.Name) - // ok to continue - } - x.mode = valueok - x.expr = e - x.typ = typ - - case *ast.CallExpr: - check.exprOrType(x, e.Fun, nil, iota, false) - if x.mode == invalid { - goto Error - } else if x.mode == typexpr { - check.conversion(x, e, x.typ, iota) - } else if sig, ok := underlying(x.typ).(*Signature); ok { - // check parameters - - // If we have a trailing ... at the end of the parameter - // list, the last argument must match the parameter type - // []T of a variadic function parameter x ...T. - passSlice := false - if e.Ellipsis.IsValid() { - if sig.IsVariadic { - passSlice = true - } else { - check.errorf(e.Ellipsis, "cannot use ... in call to %s", e.Fun) - // ok to continue - } - } - - // If we have a single argument that is a function call - // we need to handle it separately. Determine if this - // is the case without checking the argument. - var call *ast.CallExpr - if len(e.Args) == 1 { - call, _ = unparen(e.Args[0]).(*ast.CallExpr) - } - - n := 0 // parameter count - if call != nil { - // We have a single argument that is a function call. - check.expr(x, call, nil, -1) - if x.mode == invalid { - goto Error // TODO(gri): we can do better - } - if t, _ := x.typ.(*Result); t != nil { - // multiple result values - n = len(t.Values) - for i, obj := range t.Values { - x.mode = value - x.expr = nil // TODO(gri) can we do better here? (for good error messages) - x.typ = obj.Type - check.argument(sig, i, nil, x, passSlice && i+1 == n) - } - } else { - // single result value - n = 1 - check.argument(sig, 0, nil, x, passSlice) - } - - } else { - // We don't have a single argument or it is not a function call. - n = len(e.Args) - for i, arg := range e.Args { - check.argument(sig, i, arg, x, passSlice && i+1 == n) - } - } - - // determine if we have enough arguments - if sig.IsVariadic { - // a variadic function accepts an "empty" - // last argument: count one extra - n++ - } - if n < len(sig.Params) { - check.errorf(e.Fun.Pos(), "too few arguments in call to %s", e.Fun) - // ok to continue - } - - // determine result - switch len(sig.Results) { - case 0: - x.mode = novalue - case 1: - x.mode = value - x.typ = sig.Results[0].Type - default: - x.mode = value - x.typ = &Result{Values: sig.Results} - } - - } else if bin, ok := x.typ.(*builtin); ok { - check.builtin(x, e, bin, iota) - - } else { - check.invalidOp(x.pos(), "cannot call non-function %s", x) - goto Error - } - - case *ast.StarExpr: - check.exprOrType(x, e.X, hint, iota, true) - switch x.mode { - case invalid: - goto Error - case typexpr: - x.typ = &Pointer{Base: x.typ} - default: - if typ, ok := x.typ.(*Pointer); ok { - x.mode = variable - x.typ = typ.Base - } else { - check.invalidOp(x.pos(), "cannot indirect %s", x) - goto Error - } - } - - case *ast.UnaryExpr: - check.expr(x, e.X, hint, iota) - check.unary(x, e.Op) - - case *ast.BinaryExpr: - var y operand - check.expr(x, e.X, hint, iota) - check.expr(&y, e.Y, hint, iota) - check.binary(x, &y, e.Op, hint) - - case *ast.KeyValueExpr: - // key:value expressions are handled in composite literals - check.invalidAST(e.Pos(), "no key:value expected") - goto Error - - case *ast.ArrayType: - if e.Len != nil { - check.expr(x, e.Len, nil, iota) - if x.mode == invalid { - goto Error - } - if x.mode != constant { - if x.mode != invalid { - check.errorf(x.pos(), "array length %s must be constant", x) - } - goto Error - } - n, ok := x.val.(int64) - if !ok || n < 0 { - check.errorf(x.pos(), "invalid array length %s", x) - goto Error - } - x.typ = &Array{Len: n, Elt: check.typ(e.Elt, cycleOk)} - } else { - x.typ = &Slice{Elt: check.typ(e.Elt, true)} - } - x.mode = typexpr - - case *ast.StructType: - x.mode = typexpr - x.typ = &Struct{Fields: check.collectFields(e.Fields, cycleOk)} - - case *ast.FuncType: - params, isVariadic := check.collectParams(e.Params, true) - results, _ := check.collectParams(e.Results, false) - x.mode = typexpr - x.typ = &Signature{Recv: nil, Params: params, Results: results, IsVariadic: isVariadic} - - case *ast.InterfaceType: - x.mode = typexpr - x.typ = &Interface{Methods: check.collectMethods(e.Methods)} - - case *ast.MapType: - x.mode = typexpr - x.typ = &Map{Key: check.typ(e.Key, true), Elt: check.typ(e.Value, true)} - - case *ast.ChanType: - x.mode = typexpr - x.typ = &Chan{Dir: e.Dir, Elt: check.typ(e.Value, true)} - - default: - check.dump("e = %s", e) - unreachable() - } - - // everything went well - x.expr = e - return - -Error: - x.mode = invalid - x.expr = e -} - -// exprOrType is like rawExpr but reports an error if e doesn't represents a value or type. -func (check *checker) exprOrType(x *operand, e ast.Expr, hint Type, iota int, cycleOk bool) { - check.rawExpr(x, e, hint, iota, cycleOk) - if x.mode == novalue { - check.errorf(x.pos(), "%s used as value or type", x) - x.mode = invalid - } -} - -// expr is like rawExpr but reports an error if e doesn't represents a value. -func (check *checker) expr(x *operand, e ast.Expr, hint Type, iota int) { - check.rawExpr(x, e, hint, iota, false) - switch x.mode { - case novalue: - check.errorf(x.pos(), "%s used as value", x) - x.mode = invalid - case typexpr: - check.errorf(x.pos(), "%s is not an expression", x) - x.mode = invalid - } -} - -func (check *checker) rawTyp(e ast.Expr, cycleOk, nilOk bool) Type { - var x operand - check.rawExpr(&x, e, nil, -1, cycleOk) - switch x.mode { - case invalid: - // ignore - error reported before - case novalue: - check.errorf(x.pos(), "%s used as type", &x) - case typexpr: - return x.typ - case constant: - if nilOk && x.isNil() { - return nil - } - fallthrough - default: - check.errorf(x.pos(), "%s is not a type", &x) - } - return Typ[Invalid] -} - -// typOrNil is like rawExpr but reports an error if e doesn't represents a type or the predeclared value nil. -// It returns e's type, nil, or Typ[Invalid] if an error occurred. -// -func (check *checker) typOrNil(e ast.Expr, cycleOk bool) Type { - return check.rawTyp(e, cycleOk, true) -} - -// typ is like rawExpr but reports an error if e doesn't represents a type. -// It returns e's type, or Typ[Invalid] if an error occurred. -// -func (check *checker) typ(e ast.Expr, cycleOk bool) Type { - return check.rawTyp(e, cycleOk, false) -} diff --git a/gcc-4.8.1/libgo/go/go/types/gcimporter.go b/gcc-4.8.1/libgo/go/go/types/gcimporter.go deleted file mode 100644 index edd3e4dec..000000000 --- a/gcc-4.8.1/libgo/go/go/types/gcimporter.go +++ /dev/null @@ -1,908 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements an Importer for gc-generated object files. - -package types - -import ( - "bufio" - "errors" - "fmt" - "go/ast" - "go/build" - "go/token" - "io" - "math/big" - "os" - "path/filepath" - "strconv" - "strings" - "text/scanner" -) - -var pkgExts = [...]string{".a", ".5", ".6", ".8"} - -// FindPkg returns the filename and unique package id for an import -// path based on package information provided by build.Import (using -// the build.Default build.Context). -// If no file was found, an empty filename is returned. -// -func FindPkg(path, srcDir string) (filename, id string) { - if len(path) == 0 { - return - } - - id = path - var noext string - switch { - default: - // "x" -> "$GOPATH/pkg/$GOOS_$GOARCH/x.ext", "x" - // Don't require the source files to be present. - bp, _ := build.Import(path, srcDir, build.FindOnly|build.AllowBinary) - if bp.PkgObj == "" { - return - } - noext = bp.PkgObj - if strings.HasSuffix(noext, ".a") { - noext = noext[:len(noext)-len(".a")] - } - - case build.IsLocalImport(path): - // "./x" -> "/this/directory/x.ext", "/this/directory/x" - noext = filepath.Join(srcDir, path) - id = noext - - case filepath.IsAbs(path): - // for completeness only - go/build.Import - // does not support absolute imports - // "/x" -> "/x.ext", "/x" - noext = path - } - - // try extensions - for _, ext := range pkgExts { - filename = noext + ext - if f, err := os.Stat(filename); err == nil && !f.IsDir() { - return - } - } - - filename = "" // not found - return -} - -// GcImportData imports a package by reading the gc-generated export data, -// adds the corresponding package object to the imports map indexed by id, -// and returns the object. -// -// The imports map must contains all packages already imported. The data -// reader position must be the beginning of the export data section. The -// filename is only used in error messages. -// -// If imports[id] contains the completely imported package, that package -// can be used directly, and there is no need to call this function (but -// there is also no harm but for extra time used). -// -func GcImportData(imports map[string]*Package, filename, id string, data *bufio.Reader) (pkg *Package, err error) { - // support for gcParser error handling - defer func() { - if r := recover(); r != nil { - err = r.(importError) // will re-panic if r is not an importError - } - }() - - var p gcParser - p.init(filename, id, data, imports) - pkg = p.parseExport() - - return -} - -// GcImport imports a gc-generated package given its import path, adds the -// corresponding package object to the imports map, and returns the object. -// Local import paths are interpreted relative to the current working directory. -// The imports map must contains all packages already imported. -// GcImport satisfies the ast.Importer signature. -// -func GcImport(imports map[string]*Package, path string) (pkg *Package, err error) { - if path == "unsafe" { - return Unsafe, nil - } - - srcDir, err := os.Getwd() - if err != nil { - return - } - filename, id := FindPkg(path, srcDir) - if filename == "" { - err = errors.New("can't find import: " + id) - return - } - - // no need to re-import if the package was imported completely before - if pkg = imports[id]; pkg != nil && pkg.Complete { - return - } - - // open file - f, err := os.Open(filename) - if err != nil { - return - } - defer func() { - f.Close() - if err != nil { - // Add file name to error. - err = fmt.Errorf("reading export data: %s: %v", filename, err) - } - }() - - buf := bufio.NewReader(f) - if err = FindGcExportData(buf); err != nil { - return - } - - pkg, err = GcImportData(imports, filename, id, buf) - - return -} - -// ---------------------------------------------------------------------------- -// gcParser - -// gcParser parses the exports inside a gc compiler-produced -// object/archive file and populates its scope with the results. -type gcParser struct { - scanner scanner.Scanner - tok rune // current token - lit string // literal string; only valid for Ident, Int, String tokens - id string // package id of imported package - imports map[string]*Package // package id -> package object -} - -func (p *gcParser) init(filename, id string, src io.Reader, imports map[string]*Package) { - p.scanner.Init(src) - p.scanner.Error = func(_ *scanner.Scanner, msg string) { p.error(msg) } - p.scanner.Mode = scanner.ScanIdents | scanner.ScanInts | scanner.ScanChars | scanner.ScanStrings | scanner.ScanComments | scanner.SkipComments - p.scanner.Whitespace = 1<<'\t' | 1<<' ' - p.scanner.Filename = filename // for good error messages - p.next() - p.id = id - p.imports = imports -} - -func (p *gcParser) next() { - p.tok = p.scanner.Scan() - switch p.tok { - case scanner.Ident, scanner.Int, scanner.Char, scanner.String, '·': - p.lit = p.scanner.TokenText() - default: - p.lit = "" - } - // leave for debugging - if false { - fmt.Printf("%s: %q -> %q\n", scanner.TokenString(p.tok), p.scanner.TokenText(), p.lit) - } -} - -func declConst(scope *Scope, name string) *Const { - // the constant may have been imported before - if it exists - // already in the respective scope, return that constant - if obj := scope.Lookup(name); obj != nil { - return obj.(*Const) - } - // otherwise create a new constant and insert it into the scope - obj := &Const{Name: name} - scope.Insert(obj) - return obj -} - -func declTypeName(scope *Scope, name string) *TypeName { - if obj := scope.Lookup(name); obj != nil { - return obj.(*TypeName) - } - obj := &TypeName{Name: name} - // a named type may be referred to before the underlying type - // is known - set it up - obj.Type = &NamedType{Obj: obj} - scope.Insert(obj) - return obj -} - -func declVar(scope *Scope, name string) *Var { - if obj := scope.Lookup(name); obj != nil { - return obj.(*Var) - } - obj := &Var{Name: name} - scope.Insert(obj) - return obj -} - -func declFunc(scope *Scope, name string) *Func { - if obj := scope.Lookup(name); obj != nil { - return obj.(*Func) - } - obj := &Func{Name: name} - scope.Insert(obj) - return obj -} - -// ---------------------------------------------------------------------------- -// Error handling - -// Internal errors are boxed as importErrors. -type importError struct { - pos scanner.Position - err error -} - -func (e importError) Error() string { - return fmt.Sprintf("import error %s (byte offset = %d): %s", e.pos, e.pos.Offset, e.err) -} - -func (p *gcParser) error(err interface{}) { - if s, ok := err.(string); ok { - err = errors.New(s) - } - // panic with a runtime.Error if err is not an error - panic(importError{p.scanner.Pos(), err.(error)}) -} - -func (p *gcParser) errorf(format string, args ...interface{}) { - p.error(fmt.Sprintf(format, args...)) -} - -func (p *gcParser) expect(tok rune) string { - lit := p.lit - if p.tok != tok { - p.errorf("expected %s, got %s (%s)", scanner.TokenString(tok), scanner.TokenString(p.tok), lit) - } - p.next() - return lit -} - -func (p *gcParser) expectSpecial(tok string) { - sep := 'x' // not white space - i := 0 - for i < len(tok) && p.tok == rune(tok[i]) && sep > ' ' { - sep = p.scanner.Peek() // if sep <= ' ', there is white space before the next token - p.next() - i++ - } - if i < len(tok) { - p.errorf("expected %q, got %q", tok, tok[0:i]) - } -} - -func (p *gcParser) expectKeyword(keyword string) { - lit := p.expect(scanner.Ident) - if lit != keyword { - p.errorf("expected keyword %s, got %q", keyword, lit) - } -} - -// ---------------------------------------------------------------------------- -// Import declarations - -// ImportPath = string_lit . -// -func (p *gcParser) parsePkgId() *Package { - id, err := strconv.Unquote(p.expect(scanner.String)) - if err != nil { - p.error(err) - } - - switch id { - case "": - // id == "" stands for the imported package id - // (only known at time of package installation) - id = p.id - case "unsafe": - // package unsafe is not in the imports map - handle explicitly - return Unsafe - } - - pkg := p.imports[id] - if pkg == nil { - pkg = &Package{Scope: new(Scope)} - p.imports[id] = pkg - } - - return pkg -} - -// dotIdentifier = ( ident | '·' ) { ident | int | '·' } . -func (p *gcParser) parseDotIdent() string { - ident := "" - if p.tok != scanner.Int { - sep := 'x' // not white space - for (p.tok == scanner.Ident || p.tok == scanner.Int || p.tok == '·') && sep > ' ' { - ident += p.lit - sep = p.scanner.Peek() // if sep <= ' ', there is white space before the next token - p.next() - } - } - if ident == "" { - p.expect(scanner.Ident) // use expect() for error handling - } - return ident -} - -// ExportedName = "@" ImportPath "." dotIdentifier . -// -func (p *gcParser) parseExportedName() (*Package, string) { - p.expect('@') - pkg := p.parsePkgId() - p.expect('.') - name := p.parseDotIdent() - return pkg, name -} - -// ---------------------------------------------------------------------------- -// Types - -// BasicType = identifier . -// -func (p *gcParser) parseBasicType() Type { - id := p.expect(scanner.Ident) - obj := Universe.Lookup(id) - if obj, ok := obj.(*TypeName); ok { - return obj.Type - } - p.errorf("not a basic type: %s", id) - return nil -} - -// ArrayType = "[" int_lit "]" Type . -// -func (p *gcParser) parseArrayType() Type { - // "[" already consumed and lookahead known not to be "]" - lit := p.expect(scanner.Int) - p.expect(']') - elt := p.parseType() - n, err := strconv.ParseInt(lit, 10, 64) - if err != nil { - p.error(err) - } - return &Array{Len: n, Elt: elt} -} - -// MapType = "map" "[" Type "]" Type . -// -func (p *gcParser) parseMapType() Type { - p.expectKeyword("map") - p.expect('[') - key := p.parseType() - p.expect(']') - elt := p.parseType() - return &Map{Key: key, Elt: elt} -} - -// Name = identifier | "?" | ExportedName . -// -func (p *gcParser) parseName() (pkg *Package, name string) { - switch p.tok { - case scanner.Ident: - name = p.lit - p.next() - case '?': - // anonymous - p.next() - case '@': - // exported name prefixed with package path - pkg, name = p.parseExportedName() - default: - p.error("name expected") - } - return -} - -// Field = Name Type [ string_lit ] . -// -func (p *gcParser) parseField() *Field { - var f Field - f.Pkg, f.Name = p.parseName() - f.Type = p.parseType() - if p.tok == scanner.String { - f.Tag = p.expect(scanner.String) - } - if f.Name == "" { - // anonymous field - typ must be T or *T and T must be a type name - if typ, ok := deref(f.Type).(*NamedType); ok && typ.Obj != nil { - f.Name = typ.Obj.GetName() - f.IsAnonymous = true - } else { - p.errorf("anonymous field expected") - } - } - return &f -} - -// StructType = "struct" "{" [ FieldList ] "}" . -// FieldList = Field { ";" Field } . -// -func (p *gcParser) parseStructType() Type { - var fields []*Field - - p.expectKeyword("struct") - p.expect('{') - for p.tok != '}' { - if len(fields) > 0 { - p.expect(';') - } - fields = append(fields, p.parseField()) - } - p.expect('}') - - return &Struct{Fields: fields} -} - -// Parameter = ( identifier | "?" ) [ "..." ] Type [ string_lit ] . -// -func (p *gcParser) parseParameter() (par *Var, isVariadic bool) { - _, name := p.parseName() - if name == "" { - name = "_" // cannot access unnamed identifiers - } - if p.tok == '.' { - p.expectSpecial("...") - isVariadic = true - } - typ := p.parseType() - // ignore argument tag (e.g. "noescape") - if p.tok == scanner.String { - p.next() - } - par = &Var{Name: name, Type: typ} - return -} - -// Parameters = "(" [ ParameterList ] ")" . -// ParameterList = { Parameter "," } Parameter . -// -func (p *gcParser) parseParameters() (list []*Var, isVariadic bool) { - p.expect('(') - for p.tok != ')' { - if len(list) > 0 { - p.expect(',') - } - par, variadic := p.parseParameter() - list = append(list, par) - if variadic { - if isVariadic { - p.error("... not on final argument") - } - isVariadic = true - } - } - p.expect(')') - - return -} - -// Signature = Parameters [ Result ] . -// Result = Type | Parameters . -// -func (p *gcParser) parseSignature() *Signature { - params, isVariadic := p.parseParameters() - - // optional result type - var results []*Var - switch p.tok { - case scanner.Ident, '[', '*', '<', '@': - // single, unnamed result - results = []*Var{{Type: p.parseType()}} - case '(': - // named or multiple result(s) - var variadic bool - results, variadic = p.parseParameters() - if variadic { - p.error("... not permitted on result type") - } - } - - return &Signature{Params: params, Results: results, IsVariadic: isVariadic} -} - -// InterfaceType = "interface" "{" [ MethodList ] "}" . -// MethodList = Method { ";" Method } . -// Method = Name Signature . -// -// The methods of embedded interfaces are always "inlined" -// by the compiler and thus embedded interfaces are never -// visible in the export data. -// -func (p *gcParser) parseInterfaceType() Type { - var methods []*Method - - p.expectKeyword("interface") - p.expect('{') - for p.tok != '}' { - if len(methods) > 0 { - p.expect(';') - } - pkg, name := p.parseName() - typ := p.parseSignature() - methods = append(methods, &Method{QualifiedName{pkg, name}, typ}) - } - p.expect('}') - - return &Interface{Methods: methods} -} - -// ChanType = ( "chan" [ "<-" ] | "<-" "chan" ) Type . -// -func (p *gcParser) parseChanType() Type { - dir := ast.SEND | ast.RECV - if p.tok == scanner.Ident { - p.expectKeyword("chan") - if p.tok == '<' { - p.expectSpecial("<-") - dir = ast.SEND - } - } else { - p.expectSpecial("<-") - p.expectKeyword("chan") - dir = ast.RECV - } - elt := p.parseType() - return &Chan{Dir: dir, Elt: elt} -} - -// Type = -// BasicType | TypeName | ArrayType | SliceType | StructType | -// PointerType | FuncType | InterfaceType | MapType | ChanType | -// "(" Type ")" . -// -// BasicType = ident . -// TypeName = ExportedName . -// SliceType = "[" "]" Type . -// PointerType = "*" Type . -// FuncType = "func" Signature . -// -func (p *gcParser) parseType() Type { - switch p.tok { - case scanner.Ident: - switch p.lit { - default: - return p.parseBasicType() - case "struct": - return p.parseStructType() - case "func": - // FuncType - p.next() - return p.parseSignature() - case "interface": - return p.parseInterfaceType() - case "map": - return p.parseMapType() - case "chan": - return p.parseChanType() - } - case '@': - // TypeName - pkg, name := p.parseExportedName() - return declTypeName(pkg.Scope, name).Type - case '[': - p.next() // look ahead - if p.tok == ']' { - // SliceType - p.next() - return &Slice{Elt: p.parseType()} - } - return p.parseArrayType() - case '*': - // PointerType - p.next() - return &Pointer{Base: p.parseType()} - case '<': - return p.parseChanType() - case '(': - // "(" Type ")" - p.next() - typ := p.parseType() - p.expect(')') - return typ - } - p.errorf("expected type, got %s (%q)", scanner.TokenString(p.tok), p.lit) - return nil -} - -// ---------------------------------------------------------------------------- -// Declarations - -// ImportDecl = "import" identifier string_lit . -// -func (p *gcParser) parseImportDecl() { - p.expectKeyword("import") - // The identifier has no semantic meaning in the import data. - // It exists so that error messages can print the real package - // name: binary.ByteOrder instead of "encoding/binary".ByteOrder. - name := p.expect(scanner.Ident) - pkg := p.parsePkgId() - assert(pkg.Name == "" || pkg.Name == name) - pkg.Name = name -} - -// int_lit = [ "+" | "-" ] { "0" ... "9" } . -// -func (p *gcParser) parseInt() (neg bool, val string) { - switch p.tok { - case '-': - neg = true - fallthrough - case '+': - p.next() - } - val = p.expect(scanner.Int) - return -} - -// number = int_lit [ "p" int_lit ] . -// -func (p *gcParser) parseNumber() (x operand) { - x.mode = constant - - // mantissa - neg, val := p.parseInt() - mant, ok := new(big.Int).SetString(val, 0) - assert(ok) - if neg { - mant.Neg(mant) - } - - if p.lit == "p" { - // exponent (base 2) - p.next() - neg, val = p.parseInt() - exp64, err := strconv.ParseUint(val, 10, 0) - if err != nil { - p.error(err) - } - exp := uint(exp64) - if neg { - denom := big.NewInt(1) - denom.Lsh(denom, exp) - x.typ = Typ[UntypedFloat] - x.val = normalizeRatConst(new(big.Rat).SetFrac(mant, denom)) - return - } - if exp > 0 { - mant.Lsh(mant, exp) - } - x.typ = Typ[UntypedFloat] - x.val = normalizeIntConst(mant) - return - } - - x.typ = Typ[UntypedInt] - x.val = normalizeIntConst(mant) - return -} - -// ConstDecl = "const" ExportedName [ Type ] "=" Literal . -// Literal = bool_lit | int_lit | float_lit | complex_lit | rune_lit | string_lit . -// bool_lit = "true" | "false" . -// complex_lit = "(" float_lit "+" float_lit "i" ")" . -// rune_lit = "(" int_lit "+" int_lit ")" . -// string_lit = `"` { unicode_char } `"` . -// -func (p *gcParser) parseConstDecl() { - p.expectKeyword("const") - pkg, name := p.parseExportedName() - obj := declConst(pkg.Scope, name) - var x operand - if p.tok != '=' { - obj.Type = p.parseType() - } - p.expect('=') - switch p.tok { - case scanner.Ident: - // bool_lit - if p.lit != "true" && p.lit != "false" { - p.error("expected true or false") - } - x.typ = Typ[UntypedBool] - x.val = p.lit == "true" - p.next() - - case '-', scanner.Int: - // int_lit - x = p.parseNumber() - - case '(': - // complex_lit or rune_lit - p.next() - if p.tok == scanner.Char { - p.next() - p.expect('+') - x = p.parseNumber() - x.typ = Typ[UntypedRune] - p.expect(')') - break - } - re := p.parseNumber() - p.expect('+') - im := p.parseNumber() - p.expectKeyword("i") - p.expect(')') - x.typ = Typ[UntypedComplex] - // TODO(gri) fix this - _, _ = re, im - x.val = zeroConst - - case scanner.Char: - // rune_lit - x.setConst(token.CHAR, p.lit) - p.next() - - case scanner.String: - // string_lit - x.setConst(token.STRING, p.lit) - p.next() - - default: - p.errorf("expected literal got %s", scanner.TokenString(p.tok)) - } - if obj.Type == nil { - obj.Type = x.typ - } - assert(x.val != nil) - obj.Val = x.val -} - -// TypeDecl = "type" ExportedName Type . -// -func (p *gcParser) parseTypeDecl() { - p.expectKeyword("type") - pkg, name := p.parseExportedName() - obj := declTypeName(pkg.Scope, name) - - // The type object may have been imported before and thus already - // have a type associated with it. We still need to parse the type - // structure, but throw it away if the object already has a type. - // This ensures that all imports refer to the same type object for - // a given type declaration. - typ := p.parseType() - - if name := obj.Type.(*NamedType); name.Underlying == nil { - name.Underlying = typ - } -} - -// VarDecl = "var" ExportedName Type . -// -func (p *gcParser) parseVarDecl() { - p.expectKeyword("var") - pkg, name := p.parseExportedName() - obj := declVar(pkg.Scope, name) - obj.Type = p.parseType() -} - -// Func = Signature [ Body ] . -// Body = "{" ... "}" . -// -func (p *gcParser) parseFunc() *Signature { - sig := p.parseSignature() - if p.tok == '{' { - p.next() - for i := 1; i > 0; p.next() { - switch p.tok { - case '{': - i++ - case '}': - i-- - } - } - } - return sig -} - -// MethodDecl = "func" Receiver Name Func . -// Receiver = "(" ( identifier | "?" ) [ "*" ] ExportedName ")" . -// -func (p *gcParser) parseMethodDecl() { - // "func" already consumed - p.expect('(') - recv, _ := p.parseParameter() // receiver - p.expect(')') - - // determine receiver base type object - typ := recv.Type - if ptr, ok := typ.(*Pointer); ok { - typ = ptr.Base - } - base := typ.(*NamedType) - - // parse method name, signature, and possibly inlined body - pkg, name := p.parseName() // unexported method names in imports are qualified with their package. - sig := p.parseFunc() - sig.Recv = recv - - // add method to type unless type was imported before - // and method exists already - // TODO(gri) investigate if this can be avoided - for _, m := range base.Methods { - if m.Name == name { - return // method was added before - } - } - base.Methods = append(base.Methods, &Method{QualifiedName{pkg, name}, sig}) -} - -// FuncDecl = "func" ExportedName Func . -// -func (p *gcParser) parseFuncDecl() { - // "func" already consumed - pkg, name := p.parseExportedName() - typ := p.parseFunc() - declFunc(pkg.Scope, name).Type = typ -} - -// Decl = [ ImportDecl | ConstDecl | TypeDecl | VarDecl | FuncDecl | MethodDecl ] "\n" . -// -func (p *gcParser) parseDecl() { - switch p.lit { - case "import": - p.parseImportDecl() - case "const": - p.parseConstDecl() - case "type": - p.parseTypeDecl() - case "var": - p.parseVarDecl() - case "func": - p.next() // look ahead - if p.tok == '(' { - p.parseMethodDecl() - } else { - p.parseFuncDecl() - } - } - p.expect('\n') -} - -// ---------------------------------------------------------------------------- -// Export - -// Export = "PackageClause { Decl } "$$" . -// PackageClause = "package" identifier [ "safe" ] "\n" . -// -func (p *gcParser) parseExport() *Package { - p.expectKeyword("package") - name := p.expect(scanner.Ident) - if p.tok != '\n' { - // A package is safe if it was compiled with the -u flag, - // which disables the unsafe package. - // TODO(gri) remember "safe" package - p.expectKeyword("safe") - } - p.expect('\n') - - pkg := p.imports[p.id] - if pkg == nil { - pkg = &Package{Name: name, Scope: new(Scope)} - p.imports[p.id] = pkg - } - - for p.tok != '$' && p.tok != scanner.EOF { - p.parseDecl() - } - - if ch := p.scanner.Peek(); p.tok != '$' || ch != '$' { - // don't call next()/expect() since reading past the - // export data may cause scanner errors (e.g. NUL chars) - p.errorf("expected '$$', got %s %c", scanner.TokenString(p.tok), ch) - } - - if n := p.scanner.ErrorCount; n != 0 { - p.errorf("expected no scanner errors, got %d", n) - } - - // package was imported completely and without errors - pkg.Complete = true - - return pkg -} diff --git a/gcc-4.8.1/libgo/go/go/types/gcimporter_test.go b/gcc-4.8.1/libgo/go/go/types/gcimporter_test.go deleted file mode 100644 index b793eb4cb..000000000 --- a/gcc-4.8.1/libgo/go/go/types/gcimporter_test.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package types - -import ( - "go/ast" - "go/build" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "testing" - "time" -) - -var gcPath string // Go compiler path - -func init() { - // determine compiler - var gc string - switch runtime.GOARCH { - case "386": - gc = "8g" - case "amd64": - gc = "6g" - case "arm": - gc = "5g" - default: - gcPath = "unknown-GOARCH-compiler" - return - } - gcPath = filepath.Join(build.ToolDir, gc) -} - -func compile(t *testing.T, dirname, filename string) string { - cmd := exec.Command(gcPath, filename) - cmd.Dir = dirname - out, err := cmd.CombinedOutput() - if err != nil { - t.Logf("%s", out) - t.Fatalf("%s %s failed: %s", gcPath, filename, err) - } - archCh, _ := build.ArchChar(runtime.GOARCH) - // filename should end with ".go" - return filepath.Join(dirname, filename[:len(filename)-2]+archCh) -} - -// Use the same global imports map for all tests. The effect is -// as if all tested packages were imported into a single package. -var imports = make(map[string]*Package) - -func testPath(t *testing.T, path string) bool { - t0 := time.Now() - _, err := GcImport(imports, path) - if err != nil { - t.Errorf("testPath(%s): %s", path, err) - return false - } - t.Logf("testPath(%s): %v", path, time.Since(t0)) - return true -} - -const maxTime = 30 * time.Second - -func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) { - dirname := filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_"+runtime.GOARCH, dir) - list, err := ioutil.ReadDir(dirname) - if err != nil { - t.Fatalf("testDir(%s): %s", dirname, err) - } - for _, f := range list { - if time.Now().After(endTime) { - t.Log("testing time used up") - return - } - switch { - case !f.IsDir(): - // try extensions - for _, ext := range pkgExts { - if strings.HasSuffix(f.Name(), ext) { - name := f.Name()[0 : len(f.Name())-len(ext)] // remove extension - if testPath(t, filepath.Join(dir, name)) { - nimports++ - } - } - } - case f.IsDir(): - nimports += testDir(t, filepath.Join(dir, f.Name()), endTime) - } - } - return -} - -func TestGcImport(t *testing.T) { - // On cross-compile builds, the path will not exist. - // Need to use GOHOSTOS, which is not available. - if _, err := os.Stat(gcPath); err != nil { - t.Skipf("skipping test: %v", err) - } - - if outFn := compile(t, "testdata", "exports.go"); outFn != "" { - defer os.Remove(outFn) - } - - nimports := 0 - if testPath(t, "./testdata/exports") { - nimports++ - } - nimports += testDir(t, "", time.Now().Add(maxTime)) // installed packages - t.Logf("tested %d imports", nimports) -} - -var importedObjectTests = []struct { - name string - kind ast.ObjKind - typ string -}{ - {"unsafe.Pointer", ast.Typ, "Pointer"}, - {"math.Pi", ast.Con, "untyped float"}, - {"io.Reader", ast.Typ, "interface{Read(p []byte) (n int, err error)}"}, - {"io.ReadWriter", ast.Typ, "interface{Read(p []byte) (n int, err error); Write(p []byte) (n int, err error)}"}, - {"math.Sin", ast.Fun, "func(x·2 float64) (_ float64)"}, - // TODO(gri) add more tests -} - -func TestGcImportedTypes(t *testing.T) { - // This package does not yet know how to read gccgo export data. - if runtime.Compiler == "gccgo" { - return - } - for _, test := range importedObjectTests { - s := strings.Split(test.name, ".") - if len(s) != 2 { - t.Fatal("inconsistent test data") - } - importPath := s[0] - objName := s[1] - - pkg, err := GcImport(imports, importPath) - if err != nil { - t.Error(err) - continue - } - - obj := pkg.Scope.Lookup(objName) - - // TODO(gri) should define an accessor on Object - var kind ast.ObjKind - var typ Type - switch obj := obj.(type) { - case *Const: - kind = ast.Con - typ = obj.Type - case *TypeName: - kind = ast.Typ - typ = obj.Type - case *Var: - kind = ast.Var - typ = obj.Type - case *Func: - kind = ast.Fun - typ = obj.Type - default: - unreachable() - } - - if kind != test.kind { - t.Errorf("%s: got kind = %q; want %q", test.name, kind, test.kind) - } - - str := typeString(underlying(typ)) - if str != test.typ { - t.Errorf("%s: got type = %q; want %q", test.name, typ, test.typ) - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/types/objects.go b/gcc-4.8.1/libgo/go/go/types/objects.go deleted file mode 100644 index dcd905b41..000000000 --- a/gcc-4.8.1/libgo/go/go/types/objects.go +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package types - -import ( - "go/ast" - "go/token" -) - -// An Object describes a named language entity such as a package, -// constant, type, variable, function (incl. methods), or label. -// All objects implement the Object interface. -// -type Object interface { - GetName() string - GetType() Type - GetPos() token.Pos - - anObject() -} - -// A Package represents the contents (objects) of a Go package. -type Package struct { - Name string - Path string // import path, "" for current (non-imported) package - Scope *Scope // package-level scope - Imports map[string]*Package // map of import paths to imported packages - Complete bool // if set, this package was imported completely - - spec *ast.ImportSpec -} - -// A Const represents a declared constant. -type Const struct { - Name string - Type Type - Val interface{} - - spec *ast.ValueSpec -} - -// A TypeName represents a declared type. -type TypeName struct { - Name string - Type Type // *NamedType or *Basic - - spec *ast.TypeSpec -} - -// A Variable represents a declared variable (including function parameters and results). -type Var struct { - Name string - Type Type - - visited bool // for initialization cycle detection - decl interface{} -} - -// A Func represents a declared function. -type Func struct { - Name string - Type Type // *Signature or *Builtin - - decl *ast.FuncDecl -} - -func (obj *Package) GetName() string { return obj.Name } -func (obj *Const) GetName() string { return obj.Name } -func (obj *TypeName) GetName() string { return obj.Name } -func (obj *Var) GetName() string { return obj.Name } -func (obj *Func) GetName() string { return obj.Name } - -func (obj *Package) GetType() Type { return Typ[Invalid] } -func (obj *Const) GetType() Type { return obj.Type } -func (obj *TypeName) GetType() Type { return obj.Type } -func (obj *Var) GetType() Type { return obj.Type } -func (obj *Func) GetType() Type { return obj.Type } - -func (obj *Package) GetPos() token.Pos { return obj.spec.Pos() } -func (obj *Const) GetPos() token.Pos { - for _, n := range obj.spec.Names { - if n.Name == obj.Name { - return n.Pos() - } - } - return token.NoPos -} -func (obj *TypeName) GetPos() token.Pos { return obj.spec.Pos() } -func (obj *Var) GetPos() token.Pos { - switch d := obj.decl.(type) { - case *ast.Field: - for _, n := range d.Names { - if n.Name == obj.Name { - return n.Pos() - } - } - case *ast.ValueSpec: - for _, n := range d.Names { - if n.Name == obj.Name { - return n.Pos() - } - } - case *ast.AssignStmt: - for _, x := range d.Lhs { - if ident, isIdent := x.(*ast.Ident); isIdent && ident.Name == obj.Name { - return ident.Pos() - } - } - } - return token.NoPos -} -func (obj *Func) GetPos() token.Pos { return obj.decl.Name.Pos() } - -func (*Package) anObject() {} -func (*Const) anObject() {} -func (*TypeName) anObject() {} -func (*Var) anObject() {} -func (*Func) anObject() {} - -// newObj returns a new Object for a given *ast.Object. -// It does not canonicalize them (it always returns a new one). -// For canonicalization, see check.lookup. -// -// TODO(gri) Once we do identifier resolution completely in -// in the typechecker, this functionality can go. -// -func newObj(astObj *ast.Object) Object { - name := astObj.Name - typ, _ := astObj.Type.(Type) - switch astObj.Kind { - case ast.Bad: - // ignore - case ast.Pkg: - unreachable() - case ast.Con: - return &Const{Name: name, Type: typ, Val: astObj.Data, spec: astObj.Decl.(*ast.ValueSpec)} - case ast.Typ: - return &TypeName{Name: name, Type: typ, spec: astObj.Decl.(*ast.TypeSpec)} - case ast.Var: - switch astObj.Decl.(type) { - case *ast.Field, *ast.ValueSpec, *ast.AssignStmt: // these are ok - default: - unreachable() - } - return &Var{Name: name, Type: typ, decl: astObj.Decl} - case ast.Fun: - return &Func{Name: name, Type: typ, decl: astObj.Decl.(*ast.FuncDecl)} - case ast.Lbl: - unreachable() // for now - } - unreachable() - return nil -} diff --git a/gcc-4.8.1/libgo/go/go/types/operand.go b/gcc-4.8.1/libgo/go/go/types/operand.go deleted file mode 100644 index 6c2281027..000000000 --- a/gcc-4.8.1/libgo/go/go/types/operand.go +++ /dev/null @@ -1,393 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file defines operands and associated operations. - -package types - -import ( - "bytes" - "fmt" - "go/ast" - "go/token" -) - -// An operandMode specifies the (addressing) mode of an operand. -type operandMode int - -const ( - invalid operandMode = iota // operand is invalid (due to an earlier error) - ignore - novalue // operand represents no value (result of a function call w/o result) - typexpr // operand is a type - constant // operand is a constant; the operand's typ is a Basic type - variable // operand is an addressable variable - value // operand is a computed value - valueok // like mode == value, but operand may be used in a comma,ok expression -) - -var operandModeString = [...]string{ - invalid: "invalid", - novalue: "no value", - typexpr: "type", - constant: "constant", - variable: "variable", - value: "value", - valueok: "value,ok", -} - -// An operand represents an intermediate value during type checking. -// Operands have an (addressing) mode, the expression evaluating to -// the operand, the operand's type, and for constants a constant value. -// -type operand struct { - mode operandMode - expr ast.Expr - typ Type - val interface{} -} - -// pos returns the position of the expression corresponding to x. -// If x is invalid the position is token.NoPos. -// -func (x *operand) pos() token.Pos { - // x.expr may not be set if x is invalid - if x.expr == nil { - return token.NoPos - } - return x.expr.Pos() -} - -func (x *operand) String() string { - if x.mode == invalid { - return "invalid operand" - } - var buf bytes.Buffer - if x.expr != nil { - buf.WriteString(exprString(x.expr)) - buf.WriteString(" (") - } - buf.WriteString(operandModeString[x.mode]) - if x.mode == constant { - format := " %v" - if isString(x.typ) { - format = " %q" - } - fmt.Fprintf(&buf, format, x.val) - } - if x.mode != novalue && (x.mode != constant || !isUntyped(x.typ)) { - fmt.Fprintf(&buf, " of type %s", typeString(x.typ)) - } - if x.expr != nil { - buf.WriteByte(')') - } - return buf.String() -} - -// setConst sets x to the untyped constant for literal lit. -func (x *operand) setConst(tok token.Token, lit string) { - x.mode = invalid - - var kind BasicKind - var val interface{} - switch tok { - case token.INT: - kind = UntypedInt - val = makeIntConst(lit) - - case token.FLOAT: - kind = UntypedFloat - val = makeFloatConst(lit) - - case token.IMAG: - kind = UntypedComplex - val = makeComplexConst(lit) - - case token.CHAR: - kind = UntypedRune - val = makeRuneConst(lit) - - case token.STRING: - kind = UntypedString - val = makeStringConst(lit) - } - - if val != nil { - x.mode = constant - x.typ = Typ[kind] - x.val = val - } -} - -// isNil reports whether x is the predeclared nil constant. -func (x *operand) isNil() bool { - return x.mode == constant && x.val == nilConst -} - -// TODO(gri) The functions operand.isAssignable, checker.convertUntyped, -// checker.isRepresentable, and checker.assignOperand are -// overlapping in functionality. Need to simplify and clean up. - -// isAssignable reports whether x is assignable to a variable of type T. -func (x *operand) isAssignable(T Type) bool { - if x.mode == invalid || T == Typ[Invalid] { - return true // avoid spurious errors - } - - V := x.typ - - // x's type is identical to T - if IsIdentical(V, T) { - return true - } - - Vu := underlying(V) - Tu := underlying(T) - - // x's type V and T have identical underlying types - // and at least one of V or T is not a named type - if IsIdentical(Vu, Tu) { - return !isNamed(V) || !isNamed(T) - } - - // T is an interface type and x implements T - if Ti, ok := Tu.(*Interface); ok { - if m, _ := missingMethod(x.typ, Ti); m == nil { - return true - } - } - - // x is a bidirectional channel value, T is a channel - // type, x's type V and T have identical element types, - // and at least one of V or T is not a named type - if Vc, ok := Vu.(*Chan); ok && Vc.Dir == ast.SEND|ast.RECV { - if Tc, ok := Tu.(*Chan); ok && IsIdentical(Vc.Elt, Tc.Elt) { - return !isNamed(V) || !isNamed(T) - } - } - - // x is the predeclared identifier nil and T is a pointer, - // function, slice, map, channel, or interface type - if x.isNil() { - switch t := Tu.(type) { - case *Basic: - if t.Kind == UnsafePointer { - return true - } - case *Pointer, *Signature, *Slice, *Map, *Chan, *Interface: - return true - } - return false - } - - // x is an untyped constant representable by a value of type T - // TODO(gri) This is borrowing from checker.convertUntyped and - // checker.isRepresentable. Need to clean up. - if isUntyped(Vu) { - switch t := Tu.(type) { - case *Basic: - if x.mode == constant { - return isRepresentableConst(x.val, t.Kind) - } - // The result of a comparison is an untyped boolean, - // but may not be a constant. - if Vb, _ := Vu.(*Basic); Vb != nil { - return Vb.Kind == UntypedBool && isBoolean(Tu) - } - case *Interface: - return x.isNil() || len(t.Methods) == 0 - case *Pointer, *Signature, *Slice, *Map, *Chan: - return x.isNil() - } - } - - return false -} - -// isInteger reports whether x is a (typed or untyped) integer value. -func (x *operand) isInteger() bool { - return x.mode == invalid || - isInteger(x.typ) || - x.mode == constant && isRepresentableConst(x.val, UntypedInt) -} - -type lookupResult struct { - mode operandMode - typ Type -} - -type embeddedType struct { - typ *NamedType - multiples bool // if set, typ is embedded multiple times at the same level -} - -// lookupFieldBreadthFirst searches all types in list for a single entry (field -// or method) of the given name from the given package. If such a field is found, -// the result describes the field mode and type; otherwise the result mode is invalid. -// (This function is similar in structure to FieldByNameFunc in reflect/type.go) -// -func lookupFieldBreadthFirst(list []embeddedType, name QualifiedName) (res lookupResult) { - // visited records the types that have been searched already. - visited := make(map[*NamedType]bool) - - // embedded types of the next lower level - var next []embeddedType - - // potentialMatch is invoked every time a match is found. - potentialMatch := func(multiples bool, mode operandMode, typ Type) bool { - if multiples || res.mode != invalid { - // name appeared already at this level - annihilate - res.mode = invalid - return false - } - // first appearance of name - res.mode = mode - res.typ = typ - return true - } - - // Search the current level if there is any work to do and collect - // embedded types of the next lower level in the next list. - for len(list) > 0 { - // The res.mode indicates whether we have found a match already - // on this level (mode != invalid), or not (mode == invalid). - assert(res.mode == invalid) - - // start with empty next list (don't waste underlying array) - next = next[:0] - - // look for name in all types at this level - for _, e := range list { - typ := e.typ - if visited[typ] { - continue - } - visited[typ] = true - - // look for a matching attached method - for _, m := range typ.Methods { - if name.IsSame(m.QualifiedName) { - assert(m.Type != nil) - if !potentialMatch(e.multiples, value, m.Type) { - return // name collision - } - } - } - - switch t := typ.Underlying.(type) { - case *Struct: - // look for a matching field and collect embedded types - for _, f := range t.Fields { - if name.IsSame(f.QualifiedName) { - assert(f.Type != nil) - if !potentialMatch(e.multiples, variable, f.Type) { - return // name collision - } - continue - } - // Collect embedded struct fields for searching the next - // lower level, but only if we have not seen a match yet - // (if we have a match it is either the desired field or - // we have a name collision on the same level; in either - // case we don't need to look further). - // Embedded fields are always of the form T or *T where - // T is a named type. If typ appeared multiple times at - // this level, f.Type appears multiple times at the next - // level. - if f.IsAnonymous && res.mode == invalid { - next = append(next, embeddedType{deref(f.Type).(*NamedType), e.multiples}) - } - } - - case *Interface: - // look for a matching method - for _, m := range t.Methods { - if name.IsSame(m.QualifiedName) { - assert(m.Type != nil) - if !potentialMatch(e.multiples, value, m.Type) { - return // name collision - } - } - } - } - } - - if res.mode != invalid { - // we found a single match on this level - return - } - - // No match and no collision so far. - // Compute the list to search for the next level. - list = list[:0] // don't waste underlying array - for _, e := range next { - // Instead of adding the same type multiple times, look for - // it in the list and mark it as multiple if it was added - // before. - // We use a sequential search (instead of a map for next) - // because the lists tend to be small, can easily be reused, - // and explicit search appears to be faster in this case. - if alt := findType(list, e.typ); alt != nil { - alt.multiples = true - } else { - list = append(list, e) - } - } - - } - - return -} - -func findType(list []embeddedType, typ *NamedType) *embeddedType { - for i := range list { - if p := &list[i]; p.typ == typ { - return p - } - } - return nil -} - -func lookupField(typ Type, name QualifiedName) (operandMode, Type) { - typ = deref(typ) - - if t, ok := typ.(*NamedType); ok { - for _, m := range t.Methods { - if name.IsSame(m.QualifiedName) { - assert(m.Type != nil) - return value, m.Type - } - } - typ = t.Underlying - } - - switch t := typ.(type) { - case *Struct: - var next []embeddedType - for _, f := range t.Fields { - if name.IsSame(f.QualifiedName) { - return variable, f.Type - } - if f.IsAnonymous { - // Possible optimization: If the embedded type - // is a pointer to the current type we could - // ignore it. - next = append(next, embeddedType{typ: deref(f.Type).(*NamedType)}) - } - } - if len(next) > 0 { - res := lookupFieldBreadthFirst(next, name) - return res.mode, res.typ - } - - case *Interface: - for _, m := range t.Methods { - if name.IsSame(m.QualifiedName) { - return value, m.Type - } - } - } - - // not found - return invalid, nil -} diff --git a/gcc-4.8.1/libgo/go/go/types/predicates.go b/gcc-4.8.1/libgo/go/go/types/predicates.go deleted file mode 100644 index 3468da5a5..000000000 --- a/gcc-4.8.1/libgo/go/go/types/predicates.go +++ /dev/null @@ -1,303 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements commonly used type predicates. - -package types - -func isNamed(typ Type) bool { - if _, ok := typ.(*Basic); ok { - return ok - } - _, ok := typ.(*NamedType) - return ok -} - -func isBoolean(typ Type) bool { - t, ok := underlying(typ).(*Basic) - return ok && t.Info&IsBoolean != 0 -} - -func isInteger(typ Type) bool { - t, ok := underlying(typ).(*Basic) - return ok && t.Info&IsInteger != 0 -} - -func isUnsigned(typ Type) bool { - t, ok := underlying(typ).(*Basic) - return ok && t.Info&IsUnsigned != 0 -} - -func isFloat(typ Type) bool { - t, ok := underlying(typ).(*Basic) - return ok && t.Info&IsFloat != 0 -} - -func isComplex(typ Type) bool { - t, ok := underlying(typ).(*Basic) - return ok && t.Info&IsComplex != 0 -} - -func isNumeric(typ Type) bool { - t, ok := underlying(typ).(*Basic) - return ok && t.Info&IsNumeric != 0 -} - -func isString(typ Type) bool { - t, ok := underlying(typ).(*Basic) - return ok && t.Info&IsString != 0 -} - -func isUntyped(typ Type) bool { - t, ok := underlying(typ).(*Basic) - return ok && t.Info&IsUntyped != 0 -} - -func isOrdered(typ Type) bool { - t, ok := underlying(typ).(*Basic) - return ok && t.Info&IsOrdered != 0 -} - -func isConstType(typ Type) bool { - t, ok := underlying(typ).(*Basic) - return ok && t.Info&IsConstType != 0 -} - -func isComparable(typ Type) bool { - switch t := underlying(typ).(type) { - case *Basic: - return t.Kind != Invalid && t.Kind != UntypedNil - case *Pointer, *Interface, *Chan: - // assumes types are equal for pointers and channels - return true - case *Struct: - for _, f := range t.Fields { - if !isComparable(f.Type) { - return false - } - } - return true - case *Array: - return isComparable(t.Elt) - } - return false -} - -func hasNil(typ Type) bool { - switch underlying(typ).(type) { - case *Slice, *Pointer, *Signature, *Interface, *Map, *Chan: - return true - } - return false -} - -// IsIdentical returns true if x and y are identical. -func IsIdentical(x, y Type) bool { - if x == y { - return true - } - - switch x := x.(type) { - case *Basic: - // Basic types are singletons except for the rune and byte - // aliases, thus we cannot solely rely on the x == y check - // above. - if y, ok := y.(*Basic); ok { - return x.Kind == y.Kind - } - - case *Array: - // Two array types are identical if they have identical element types - // and the same array length. - if y, ok := y.(*Array); ok { - return x.Len == y.Len && IsIdentical(x.Elt, y.Elt) - } - - case *Slice: - // Two slice types are identical if they have identical element types. - if y, ok := y.(*Slice); ok { - return IsIdentical(x.Elt, y.Elt) - } - - case *Struct: - // Two struct types are identical if they have the same sequence of fields, - // and if corresponding fields have the same names, and identical types, - // and identical tags. Two anonymous fields are considered to have the same - // name. Lower-case field names from different packages are always different. - if y, ok := y.(*Struct); ok { - if len(x.Fields) == len(y.Fields) { - for i, f := range x.Fields { - g := y.Fields[i] - if !f.QualifiedName.IsSame(g.QualifiedName) || - !IsIdentical(f.Type, g.Type) || - f.Tag != g.Tag || - f.IsAnonymous != g.IsAnonymous { - return false - } - } - return true - } - } - - case *Pointer: - // Two pointer types are identical if they have identical base types. - if y, ok := y.(*Pointer); ok { - return IsIdentical(x.Base, y.Base) - } - - case *Signature: - // Two function types are identical if they have the same number of parameters - // and result values, corresponding parameter and result types are identical, - // and either both functions are variadic or neither is. Parameter and result - // names are not required to match. - if y, ok := y.(*Signature); ok { - return identicalTypes(x.Params, y.Params) && - identicalTypes(x.Results, y.Results) && - x.IsVariadic == y.IsVariadic - } - - case *Interface: - // Two interface types are identical if they have the same set of methods with - // the same names and identical function types. Lower-case method names from - // different packages are always different. The order of the methods is irrelevant. - if y, ok := y.(*Interface); ok { - return identicalMethods(x.Methods, y.Methods) // methods are sorted - } - - case *Map: - // Two map types are identical if they have identical key and value types. - if y, ok := y.(*Map); ok { - return IsIdentical(x.Key, y.Key) && IsIdentical(x.Elt, y.Elt) - } - - case *Chan: - // Two channel types are identical if they have identical value types - // and the same direction. - if y, ok := y.(*Chan); ok { - return x.Dir == y.Dir && IsIdentical(x.Elt, y.Elt) - } - - case *NamedType: - // Two named types are identical if their type names originate - // in the same type declaration. - if y, ok := y.(*NamedType); ok { - return x.Obj == y.Obj - } - } - - return false -} - -// identicalTypes returns true if both lists a and b have the -// same length and corresponding objects have identical types. -func identicalTypes(a, b []*Var) bool { - if len(a) != len(b) { - return false - } - for i, x := range a { - y := b[i] - if !IsIdentical(x.Type, y.Type) { - return false - } - } - return true -} - -// identicalMethods returns true if both lists a and b have the -// same length and corresponding methods have identical types. -// TODO(gri) make this more efficient -func identicalMethods(a, b []*Method) bool { - if len(a) != len(b) { - return false - } - m := make(map[QualifiedName]*Method) - for _, x := range a { - assert(m[x.QualifiedName] == nil) // method list must not have duplicate entries - m[x.QualifiedName] = x - } - for _, y := range b { - if x := m[y.QualifiedName]; x == nil || !IsIdentical(x.Type, y.Type) { - return false - } - } - return true -} - -// underlying returns the underlying type of typ. -func underlying(typ Type) Type { - // Basic types are representing themselves directly even though they are named. - if typ, ok := typ.(*NamedType); ok { - return typ.Underlying // underlying types are never NamedTypes - } - return typ -} - -// deref returns a pointer's base type; otherwise it returns typ. -func deref(typ Type) Type { - if typ, ok := underlying(typ).(*Pointer); ok { - return typ.Base - } - return typ -} - -// defaultType returns the default "typed" type for an "untyped" type; -// it returns the incoming type for all other types. If there is no -// corresponding untyped type, the result is Typ[Invalid]. -// -func defaultType(typ Type) Type { - if t, ok := typ.(*Basic); ok { - k := Invalid - switch t.Kind { - // case UntypedNil: - // There is no default type for nil. For a good error message, - // catch this case before calling this function. - case UntypedBool: - k = Bool - case UntypedInt: - k = Int - case UntypedRune: - k = Rune - case UntypedFloat: - k = Float64 - case UntypedComplex: - k = Complex128 - case UntypedString: - k = String - } - typ = Typ[k] - } - return typ -} - -// missingMethod returns (nil, false) if typ implements T, otherwise -// it returns the first missing method required by T and whether it -// is missing or simply has the wrong type. -// -func missingMethod(typ Type, T *Interface) (method *Method, wrongType bool) { - // TODO(gri): this needs to correctly compare method names (taking package into account) - // TODO(gri): distinguish pointer and non-pointer receivers - // an interface type implements T if it has no methods with conflicting signatures - // Note: This is stronger than the current spec. Should the spec require this? - if ityp, _ := underlying(typ).(*Interface); ityp != nil { - for _, m := range T.Methods { - mode, sig := lookupField(ityp, m.QualifiedName) // TODO(gri) no need to go via lookupField - if mode != invalid && !IsIdentical(sig, m.Type) { - return m, true - } - } - return - } - - // a concrete type implements T if it implements all methods of T. - for _, m := range T.Methods { - mode, sig := lookupField(typ, m.QualifiedName) - if mode == invalid { - return m, false - } - if !IsIdentical(sig, m.Type) { - return m, true - } - } - return -} diff --git a/gcc-4.8.1/libgo/go/go/types/resolve.go b/gcc-4.8.1/libgo/go/go/types/resolve.go deleted file mode 100644 index 112818f79..000000000 --- a/gcc-4.8.1/libgo/go/go/types/resolve.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package types - -import ( - "fmt" - "go/ast" - "go/token" - "strconv" -) - -func (check *checker) declareObj(scope, altScope *Scope, obj Object) { - alt := scope.Insert(obj) - if alt == nil && altScope != nil { - // see if there is a conflicting declaration in altScope - alt = altScope.Lookup(obj.GetName()) - } - if alt != nil { - prevDecl := "" - if pos := alt.GetPos(); pos.IsValid() { - prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", check.fset.Position(pos)) - } - check.errorf(obj.GetPos(), fmt.Sprintf("%s redeclared in this block%s", obj.GetName(), prevDecl)) - } -} - -func (check *checker) resolveIdent(scope *Scope, ident *ast.Ident) bool { - for ; scope != nil; scope = scope.Outer { - if obj := scope.Lookup(ident.Name); obj != nil { - check.register(ident, obj) - return true - } - } - return false -} - -func (check *checker) resolve(importer Importer) (pkg *Package, methods []*ast.FuncDecl) { - pkg = &Package{Scope: &Scope{Outer: Universe}, Imports: make(map[string]*Package)} - - // complete package scope - i := 0 - for _, file := range check.files { - // package names must match - switch name := file.Name.Name; { - case pkg.Name == "": - pkg.Name = name - case name != pkg.Name: - check.errorf(file.Package, "package %s; expected %s", name, pkg.Name) - continue // ignore this file - } - - // keep this file - check.files[i] = file - i++ - - // the package identifier denotes the current package - check.register(file.Name, pkg) - - // insert top-level file objects in package scope - // (the parser took care of declaration errors) - for _, decl := range file.Decls { - switch d := decl.(type) { - case *ast.BadDecl: - // ignore - case *ast.GenDecl: - if d.Tok == token.CONST { - check.assocInitvals(d) - } - for _, spec := range d.Specs { - switch s := spec.(type) { - case *ast.ImportSpec: - // handled separately below - case *ast.ValueSpec: - for _, name := range s.Names { - if name.Name == "_" { - continue - } - pkg.Scope.Insert(check.lookup(name)) - } - case *ast.TypeSpec: - if s.Name.Name == "_" { - continue - } - pkg.Scope.Insert(check.lookup(s.Name)) - default: - check.invalidAST(s.Pos(), "unknown ast.Spec node %T", s) - } - } - case *ast.FuncDecl: - if d.Recv != nil { - // collect method - methods = append(methods, d) - continue - } - if d.Name.Name == "_" || d.Name.Name == "init" { - continue // blank (_) and init functions are inaccessible - } - pkg.Scope.Insert(check.lookup(d.Name)) - default: - check.invalidAST(d.Pos(), "unknown ast.Decl node %T", d) - } - } - } - check.files = check.files[0:i] - - // complete file scopes with imports and resolve identifiers - for _, file := range check.files { - // build file scope by processing all imports - importErrors := false - fileScope := &Scope{Outer: pkg.Scope} - for _, spec := range file.Imports { - if importer == nil { - importErrors = true - continue - } - path, _ := strconv.Unquote(spec.Path.Value) - imp, err := importer(pkg.Imports, path) - if err != nil { - check.errorf(spec.Path.Pos(), "could not import %s (%s)", path, err) - importErrors = true - continue - } - // TODO(gri) If a local package name != "." is provided, - // global identifier resolution could proceed even if the - // import failed. Consider adjusting the logic here a bit. - - // local name overrides imported package name - name := imp.Name - if spec.Name != nil { - name = spec.Name.Name - } - - // add import to file scope - if name == "." { - // merge imported scope with file scope - for _, obj := range imp.Scope.Entries { - check.declareObj(fileScope, pkg.Scope, obj) - } - // TODO(gri) consider registering the "." identifier - // if we have Context.Ident callbacks for say blank - // (_) identifiers - // check.register(spec.Name, pkg) - } else if name != "_" { - // declare imported package object in file scope - // (do not re-use imp in the file scope but create - // a new object instead; the Decl field is different - // for different files) - obj := &Package{Name: name, Scope: imp.Scope, spec: spec} - check.declareObj(fileScope, pkg.Scope, obj) - } - } - - // resolve identifiers - if importErrors { - // don't use the universe scope without correct imports - // (objects in the universe may be shadowed by imports; - // with missing imports, identifiers might get resolved - // incorrectly to universe objects) - pkg.Scope.Outer = nil - } - i := 0 - for _, ident := range file.Unresolved { - if !check.resolveIdent(fileScope, ident) { - check.errorf(ident.Pos(), "undeclared name: %s", ident.Name) - file.Unresolved[i] = ident - i++ - } - - } - file.Unresolved = file.Unresolved[0:i] - pkg.Scope.Outer = Universe // reset outer scope (is nil if there were importErrors) - } - - return -} diff --git a/gcc-4.8.1/libgo/go/go/types/resolver_test.go b/gcc-4.8.1/libgo/go/go/types/resolver_test.go deleted file mode 100644 index b3b50a67d..000000000 --- a/gcc-4.8.1/libgo/go/go/types/resolver_test.go +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package types - -import ( - "go/ast" - "go/parser" - "go/token" - "testing" -) - -var sources = []string{ - ` - package p - import "fmt" - import "math" - const pi = math.Pi - func sin(x float64) float64 { - return math.Sin(x) - } - var Println = fmt.Println - `, - ` - package p - import "fmt" - func f() string { - _ = "foo" - return fmt.Sprintf("%d", g()) - } - func g() (x int) { return } - `, - ` - package p - import . "go/parser" - import "sync" - func g() Mode { return ImportsOnly } - var _, x int = 1, 2 - func init() {} - type T struct{ sync.Mutex; a, b, c int} - type I interface{ m() } - var _ = T{a: 1, b: 2, c: 3} - func (_ T) m() {} - `, -} - -var pkgnames = []string{ - "fmt", - "math", -} - -func TestResolveQualifiedIdents(t *testing.T) { - // Does not work with gccgo, because it requires reading gc - // import files. - return - - // parse package files - fset := token.NewFileSet() - var files []*ast.File - for _, src := range sources { - f, err := parser.ParseFile(fset, "", src, parser.DeclarationErrors) - if err != nil { - t.Fatal(err) - } - files = append(files, f) - } - - // resolve and type-check package AST - idents := make(map[*ast.Ident]Object) - ctxt := Default - ctxt.Ident = func(id *ast.Ident, obj Object) { idents[id] = obj } - pkg, err := ctxt.Check(fset, files) - if err != nil { - t.Fatal(err) - } - - // check that all packages were imported - for _, name := range pkgnames { - if pkg.Imports[name] == nil { - t.Errorf("package %s not imported", name) - } - } - - // check that there are no top-level unresolved identifiers - for _, f := range files { - for _, x := range f.Unresolved { - t.Errorf("%s: unresolved global identifier %s", fset.Position(x.Pos()), x.Name) - } - } - - // check that qualified identifiers are resolved - for _, f := range files { - ast.Inspect(f, func(n ast.Node) bool { - if s, ok := n.(*ast.SelectorExpr); ok { - if x, ok := s.X.(*ast.Ident); ok { - obj := idents[x] - if obj == nil { - t.Errorf("%s: unresolved qualified identifier %s", fset.Position(x.Pos()), x.Name) - return false - } - if _, ok := obj.(*Package); ok && idents[s.Sel] == nil { - t.Errorf("%s: unresolved selector %s", fset.Position(s.Sel.Pos()), s.Sel.Name) - return false - } - return false - } - return false - } - return true - }) - } - - // Currently, the Check API doesn't call Ident for fields, methods, and composite literal keys. - // Introduce them artifically so that we can run the check below. - for _, f := range files { - ast.Inspect(f, func(n ast.Node) bool { - switch x := n.(type) { - case *ast.StructType: - for _, list := range x.Fields.List { - for _, f := range list.Names { - assert(idents[f] == nil) - idents[f] = &Var{Name: f.Name} - } - } - case *ast.InterfaceType: - for _, list := range x.Methods.List { - for _, f := range list.Names { - assert(idents[f] == nil) - idents[f] = &Func{Name: f.Name} - } - } - case *ast.CompositeLit: - for _, e := range x.Elts { - if kv, ok := e.(*ast.KeyValueExpr); ok { - if k, ok := kv.Key.(*ast.Ident); ok { - assert(idents[k] == nil) - idents[k] = &Var{Name: k.Name} - } - } - } - } - return true - }) - } - - // check that each identifier in the source is enumerated by the Context.Ident callback - for _, f := range files { - ast.Inspect(f, func(n ast.Node) bool { - if x, ok := n.(*ast.Ident); ok && x.Name != "_" && x.Name != "." { - obj := idents[x] - if obj == nil { - t.Errorf("%s: unresolved identifier %s", fset.Position(x.Pos()), x.Name) - } else { - delete(idents, x) - } - return false - } - return true - }) - } - - // TODO(gri) enable code below - // At the moment, the type checker introduces artifical identifiers which are not - // present in the source. Once it doesn't do that anymore, enable the checks below. - /* - for x := range idents { - t.Errorf("%s: identifier %s not present in source", fset.Position(x.Pos()), x.Name) - } - */ -} diff --git a/gcc-4.8.1/libgo/go/go/types/scope.go b/gcc-4.8.1/libgo/go/go/types/scope.go deleted file mode 100644 index b8d6d0bb2..000000000 --- a/gcc-4.8.1/libgo/go/go/types/scope.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package types - -// A Scope maintains the set of named language entities declared -// in the scope and a link to the immediately surrounding (outer) -// scope. -// -type Scope struct { - Outer *Scope - Entries []Object // scope entries in insertion order - large map[string]Object // for fast lookup - only used for larger scopes -} - -// Lookup returns the object with the given name if it is -// found in scope s, otherwise it returns nil. Outer scopes -// are ignored. -// -func (s *Scope) Lookup(name string) Object { - if s.large != nil { - return s.large[name] - } - for _, obj := range s.Entries { - if obj.GetName() == name { - return obj - } - } - return nil -} - -// Insert attempts to insert an object obj into scope s. -// If s already contains an object with the same name, -// Insert leaves s unchanged and returns that object. -// Otherwise it inserts obj and returns nil. -// -func (s *Scope) Insert(obj Object) Object { - name := obj.GetName() - if alt := s.Lookup(name); alt != nil { - return alt - } - s.Entries = append(s.Entries, obj) - - // If the scope size reaches a threshold, use a map for faster lookups. - const threshold = 20 - if len(s.Entries) > threshold { - if s.large == nil { - m := make(map[string]Object, len(s.Entries)) - for _, obj := range s.Entries { - m[obj.GetName()] = obj - } - s.large = m - } - s.large[name] = obj - } - - return nil -} diff --git a/gcc-4.8.1/libgo/go/go/types/stmt.go b/gcc-4.8.1/libgo/go/go/types/stmt.go deleted file mode 100644 index 11a2e7196..000000000 --- a/gcc-4.8.1/libgo/go/go/types/stmt.go +++ /dev/null @@ -1,721 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements typechecking of statements. - -package types - -import ( - "go/ast" - "go/token" -) - -func (check *checker) assignOperand(z, x *operand) { - if t, ok := x.typ.(*Result); ok { - // TODO(gri) elsewhere we use "assignment count mismatch" (consolidate) - check.errorf(x.pos(), "%d-valued expression %s used as single value", len(t.Values), x) - x.mode = invalid - return - } - - check.convertUntyped(x, z.typ) - - if !x.isAssignable(z.typ) { - check.errorf(x.pos(), "cannot assign %s to %s", x, z) - x.mode = invalid - } -} - -// assign1to1 typechecks a single assignment of the form lhs = rhs (if rhs != nil), -// or lhs = x (if rhs == nil). If decl is set, the lhs operand must be an identifier. -// If its type is not set, it is deduced from the type or value of x. If lhs has a -// type it is used as a hint when evaluating rhs, if present. -// -func (check *checker) assign1to1(lhs, rhs ast.Expr, x *operand, decl bool, iota int) { - ident, _ := lhs.(*ast.Ident) - if x == nil { - assert(rhs != nil) - x = new(operand) - } - - if ident != nil && ident.Name == "_" { - // anything can be assigned to a blank identifier - check rhs only, if present - if rhs != nil { - check.expr(x, rhs, nil, iota) - } - return - } - - if !decl { - // regular assignment - start with lhs to obtain a type hint - var z operand - check.expr(&z, lhs, nil, -1) - if z.mode == invalid { - z.typ = nil // so we can proceed with rhs - } - - if rhs != nil { - check.expr(x, rhs, z.typ, -1) - if x.mode == invalid { - return - } - } - - check.assignOperand(&z, x) - if x.mode != invalid && z.mode == constant { - check.errorf(x.pos(), "cannot assign %s to %s", x, &z) - } - return - } - - // declaration - lhs must be an identifier - if ident == nil { - check.errorf(lhs.Pos(), "cannot declare %s", lhs) - return - } - - // lhs may or may not be typed yet - obj := check.lookup(ident) - var typ Type - if t := obj.GetType(); t != nil { - typ = t - } - - if rhs != nil { - check.expr(x, rhs, typ, iota) - // continue even if x.mode == invalid - } - - if typ == nil { - // determine lhs type from rhs expression; - // for variables, convert untyped types to - // default types - typ = Typ[Invalid] - if x.mode != invalid { - typ = x.typ - if _, ok := obj.(*Var); ok && isUntyped(typ) { - if x.isNil() { - check.errorf(x.pos(), "use of untyped nil") - x.mode = invalid - } else { - typ = defaultType(typ) - } - } - } - switch obj := obj.(type) { - case *Const: - obj.Type = typ - case *Var: - obj.Type = typ - default: - unreachable() - } - } - - if x.mode != invalid { - var z operand - switch obj.(type) { - case *Const: - z.mode = constant - case *Var: - z.mode = variable - default: - unreachable() - } - z.expr = ident - z.typ = typ - check.assignOperand(&z, x) - } - - // for constants, set their value - if obj, ok := obj.(*Const); ok { - assert(obj.Val == nil) - if x.mode != invalid { - if x.mode == constant { - if isConstType(x.typ) { - obj.Val = x.val - } else { - check.errorf(x.pos(), "%s has invalid constant type", x) - } - } else { - check.errorf(x.pos(), "%s is not constant", x) - } - } - if obj.Val == nil { - // set the constant to its type's zero value to reduce spurious errors - switch typ := underlying(obj.Type); { - case typ == Typ[Invalid]: - // ignore - case isBoolean(typ): - obj.Val = false - case isNumeric(typ): - obj.Val = int64(0) - case isString(typ): - obj.Val = "" - case hasNil(typ): - obj.Val = nilConst - default: - // in all other cases just prevent use of the constant - // TODO(gri) re-evaluate this code - obj.Val = nilConst - } - } - } -} - -// assignNtoM typechecks a general assignment. If decl is set, the lhs operands -// must be identifiers. If their types are not set, they are deduced from the -// types of the corresponding rhs expressions. iota >= 0 indicates that the -// "assignment" is part of a constant/variable declaration. -// Precondition: len(lhs) > 0 . -// -func (check *checker) assignNtoM(lhs, rhs []ast.Expr, decl bool, iota int) { - assert(len(lhs) > 0) - - if len(lhs) == len(rhs) { - for i, e := range rhs { - check.assign1to1(lhs[i], e, nil, decl, iota) - } - return - } - - if len(rhs) == 1 { - // len(lhs) > 1, therefore a correct rhs expression - // cannot be a shift and we don't need a type hint; - // ok to evaluate rhs first - var x operand - check.expr(&x, rhs[0], nil, iota) - if x.mode == invalid { - return - } - - if t, ok := x.typ.(*Result); ok && len(lhs) == len(t.Values) { - // function result - x.mode = value - for i, obj := range t.Values { - x.expr = nil // TODO(gri) should do better here - x.typ = obj.Type - check.assign1to1(lhs[i], nil, &x, decl, iota) - } - return - } - - if x.mode == valueok && len(lhs) == 2 { - // comma-ok expression - x.mode = value - check.assign1to1(lhs[0], nil, &x, decl, iota) - - x.mode = value - x.typ = Typ[UntypedBool] - check.assign1to1(lhs[1], nil, &x, decl, iota) - return - } - } - - check.errorf(lhs[0].Pos(), "assignment count mismatch: %d = %d", len(lhs), len(rhs)) - - // avoid checking the same declaration over and over - // again for each lhs identifier that has no type yet - if iota >= 0 { - // declaration - for _, e := range lhs { - if name, ok := e.(*ast.Ident); ok { - switch obj := check.lookup(name).(type) { - case *Const: - obj.Type = Typ[Invalid] - case *Var: - obj.Type = Typ[Invalid] - default: - unreachable() - } - } - } - } -} - -func (check *checker) optionalStmt(s ast.Stmt) { - if s != nil { - check.stmt(s) - } -} - -func (check *checker) stmtList(list []ast.Stmt) { - for _, s := range list { - check.stmt(s) - } -} - -func (check *checker) call(call *ast.CallExpr) { - var x operand - check.rawExpr(&x, call, nil, -1, false) // don't check if value is used - // TODO(gri) If a builtin is called, the builtin must be valid in statement context. -} - -func (check *checker) multipleDefaults(list []ast.Stmt) { - var first ast.Stmt - for _, s := range list { - var d ast.Stmt - switch c := s.(type) { - case *ast.CaseClause: - if len(c.List) == 0 { - d = s - } - case *ast.CommClause: - if c.Comm == nil { - d = s - } - default: - check.invalidAST(s.Pos(), "case/communication clause expected") - } - if d != nil { - if first != nil { - check.errorf(d.Pos(), "multiple defaults (first at %s)", first.Pos()) - } else { - first = d - } - } - } -} - -// stmt typechecks statement s. -func (check *checker) stmt(s ast.Stmt) { - switch s := s.(type) { - case *ast.BadStmt, *ast.EmptyStmt: - // ignore - - case *ast.DeclStmt: - d, _ := s.Decl.(*ast.GenDecl) - if d == nil || (d.Tok != token.CONST && d.Tok != token.TYPE && d.Tok != token.VAR) { - check.invalidAST(token.NoPos, "const, type, or var declaration expected") - return - } - if d.Tok == token.CONST { - check.assocInitvals(d) - } - check.decl(d) - - case *ast.LabeledStmt: - // TODO(gri) anything to do with label itself? - check.stmt(s.Stmt) - - case *ast.ExprStmt: - var x operand - used := false - switch e := unparen(s.X).(type) { - case *ast.CallExpr: - // function calls are permitted - used = true - // but some builtins are excluded - // (Caution: This evaluates e.Fun twice, once here and once - // below as part of s.X. This has consequences for - // check.register. Perhaps this can be avoided.) - check.expr(&x, e.Fun, nil, -1) - if x.mode != invalid { - if b, ok := x.typ.(*builtin); ok && !b.isStatement { - used = false - } - } - case *ast.UnaryExpr: - // receive operations are permitted - if e.Op == token.ARROW { - used = true - } - } - if !used { - check.errorf(s.Pos(), "%s not used", s.X) - // ok to continue - } - check.rawExpr(&x, s.X, nil, -1, false) - if x.mode == typexpr { - check.errorf(x.pos(), "%s is not an expression", &x) - } - - case *ast.SendStmt: - var ch, x operand - check.expr(&ch, s.Chan, nil, -1) - check.expr(&x, s.Value, nil, -1) - if ch.mode == invalid || x.mode == invalid { - return - } - if tch, ok := underlying(ch.typ).(*Chan); !ok || tch.Dir&ast.SEND == 0 || !x.isAssignable(tch.Elt) { - check.invalidOp(ch.pos(), "cannot send %s to channel %s", &x, &ch) - } - - case *ast.IncDecStmt: - var op token.Token - switch s.Tok { - case token.INC: - op = token.ADD - case token.DEC: - op = token.SUB - default: - check.invalidAST(s.TokPos, "unknown inc/dec operation %s", s.Tok) - return - } - var x, y operand - check.expr(&x, s.X, nil, -1) - check.expr(&y, &ast.BasicLit{ValuePos: x.pos(), Kind: token.INT, Value: "1"}, nil, -1) // use x's position - check.binary(&x, &y, op, nil) - check.assign1to1(s.X, nil, &x, false, -1) - - case *ast.AssignStmt: - switch s.Tok { - case token.ASSIGN, token.DEFINE: - if len(s.Lhs) == 0 { - check.invalidAST(s.Pos(), "missing lhs in assignment") - return - } - check.assignNtoM(s.Lhs, s.Rhs, s.Tok == token.DEFINE, -1) - default: - // assignment operations - if len(s.Lhs) != 1 || len(s.Rhs) != 1 { - check.errorf(s.TokPos, "assignment operation %s requires single-valued expressions", s.Tok) - return - } - // TODO(gri) make this conversion more efficient - var op token.Token - switch s.Tok { - case token.ADD_ASSIGN: - op = token.ADD - case token.SUB_ASSIGN: - op = token.SUB - case token.MUL_ASSIGN: - op = token.MUL - case token.QUO_ASSIGN: - op = token.QUO - case token.REM_ASSIGN: - op = token.REM - case token.AND_ASSIGN: - op = token.AND - case token.OR_ASSIGN: - op = token.OR - case token.XOR_ASSIGN: - op = token.XOR - case token.SHL_ASSIGN: - op = token.SHL - case token.SHR_ASSIGN: - op = token.SHR - case token.AND_NOT_ASSIGN: - op = token.AND_NOT - default: - check.invalidAST(s.TokPos, "unknown assignment operation %s", s.Tok) - return - } - var x, y operand - check.expr(&x, s.Lhs[0], nil, -1) - if x.mode == invalid { - return - } - check.expr(&y, s.Rhs[0], nil, -1) - if y.mode == invalid { - return - } - check.binary(&x, &y, op, x.typ) - check.assign1to1(s.Lhs[0], nil, &x, false, -1) - } - - case *ast.GoStmt: - check.call(s.Call) - - case *ast.DeferStmt: - check.call(s.Call) - - case *ast.ReturnStmt: - sig := check.funcsig - if n := len(sig.Results); n > 0 { - // TODO(gri) should not have to compute lhs, named every single time - clean this up - lhs := make([]ast.Expr, n) - named := false // if set, function has named results - for i, res := range sig.Results { - if len(res.Name) > 0 { - // a blank (_) result parameter is a named result - named = true - } - name := ast.NewIdent(res.Name) - name.NamePos = s.Pos() - check.register(name, &Var{Name: res.Name, Type: res.Type}) - lhs[i] = name - } - if len(s.Results) > 0 || !named { - // TODO(gri) assignNtoM should perhaps not require len(lhs) > 0 - check.assignNtoM(lhs, s.Results, false, -1) - } - } else if len(s.Results) > 0 { - check.errorf(s.Pos(), "no result values expected") - } - - case *ast.BranchStmt: - // TODO(gri) implement this - - case *ast.BlockStmt: - check.stmtList(s.List) - - case *ast.IfStmt: - check.optionalStmt(s.Init) - var x operand - check.expr(&x, s.Cond, nil, -1) - if !isBoolean(x.typ) { - check.errorf(s.Cond.Pos(), "non-boolean condition in if statement") - } - check.stmt(s.Body) - check.optionalStmt(s.Else) - - case *ast.SwitchStmt: - check.optionalStmt(s.Init) - var x operand - tag := s.Tag - if tag == nil { - // use fake true tag value and position it at the opening { of the switch - ident := &ast.Ident{NamePos: s.Body.Lbrace, Name: "true"} - check.register(ident, Universe.Lookup("true")) - tag = ident - } - check.expr(&x, tag, nil, -1) - - check.multipleDefaults(s.Body.List) - seen := make(map[interface{}]token.Pos) - for _, s := range s.Body.List { - clause, _ := s.(*ast.CaseClause) - if clause == nil { - continue // error reported before - } - if x.mode != invalid { - for _, expr := range clause.List { - x := x // copy of x (don't modify original) - var y operand - check.expr(&y, expr, nil, -1) - if y.mode == invalid { - continue // error reported before - } - // If we have a constant case value, it must appear only - // once in the switch statement. Determine if there is a - // duplicate entry, but only report an error if there are - // no other errors. - var dupl token.Pos - var yy operand - if y.mode == constant { - // TODO(gri) This code doesn't work correctly for - // large integer, floating point, or - // complex values - the respective struct - // comparisons are shallow. Need to use a - // hash function to index the map. - dupl = seen[y.val] - seen[y.val] = y.pos() - yy = y // remember y - } - // TODO(gri) The convertUntyped call pair below appears in other places. Factor! - // Order matters: By comparing y against x, error positions are at the case values. - check.convertUntyped(&y, x.typ) - if y.mode == invalid { - continue // error reported before - } - check.convertUntyped(&x, y.typ) - if x.mode == invalid { - continue // error reported before - } - check.comparison(&y, &x, token.EQL) - if y.mode != invalid && dupl.IsValid() { - check.errorf(yy.pos(), "%s is duplicate case (previous at %s)", - &yy, check.fset.Position(dupl)) - } - } - } - check.stmtList(clause.Body) - } - - case *ast.TypeSwitchStmt: - check.optionalStmt(s.Init) - - // A type switch guard must be of the form: - // - // TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" . - // - // The parser is checking syntactic correctness; - // remaining syntactic errors are considered AST errors here. - // TODO(gri) better factoring of error handling (invalid ASTs) - // - var lhs *Var // lhs variable or nil - var rhs ast.Expr - switch guard := s.Assign.(type) { - case *ast.ExprStmt: - rhs = guard.X - case *ast.AssignStmt: - if len(guard.Lhs) != 1 || guard.Tok != token.DEFINE || len(guard.Rhs) != 1 { - check.invalidAST(s.Pos(), "incorrect form of type switch guard") - return - } - ident, _ := guard.Lhs[0].(*ast.Ident) - if ident == nil { - check.invalidAST(s.Pos(), "incorrect form of type switch guard") - return - } - lhs = check.lookup(ident).(*Var) - rhs = guard.Rhs[0] - default: - check.invalidAST(s.Pos(), "incorrect form of type switch guard") - return - } - - // rhs must be of the form: expr.(type) and expr must be an interface - expr, _ := rhs.(*ast.TypeAssertExpr) - if expr == nil || expr.Type != nil { - check.invalidAST(s.Pos(), "incorrect form of type switch guard") - return - } - var x operand - check.expr(&x, expr.X, nil, -1) - if x.mode == invalid { - return - } - var T *Interface - if T, _ = underlying(x.typ).(*Interface); T == nil { - check.errorf(x.pos(), "%s is not an interface", &x) - return - } - - check.multipleDefaults(s.Body.List) - for _, s := range s.Body.List { - clause, _ := s.(*ast.CaseClause) - if clause == nil { - continue // error reported before - } - // Check each type in this type switch case. - var typ Type - for _, expr := range clause.List { - typ = check.typOrNil(expr, false) - if typ != nil && typ != Typ[Invalid] { - if method, wrongType := missingMethod(typ, T); method != nil { - var msg string - if wrongType { - msg = "%s cannot have dynamic type %s (wrong type for method %s)" - } else { - msg = "%s cannot have dynamic type %s (missing method %s)" - } - check.errorf(expr.Pos(), msg, &x, typ, method.Name) - // ok to continue - } - } - } - // If lhs exists, set its type for each clause. - if lhs != nil { - // In clauses with a case listing exactly one type, the variable has that type; - // otherwise, the variable has the type of the expression in the TypeSwitchGuard. - if len(clause.List) != 1 || typ == nil { - typ = x.typ - } - lhs.Type = typ - } - check.stmtList(clause.Body) - } - - // There is only one object (lhs) associated with a lhs identifier, but that object - // assumes different types for different clauses. Set it back to the type of the - // TypeSwitchGuard expression so that that variable always has a valid type. - if lhs != nil { - lhs.Type = x.typ - } - - case *ast.SelectStmt: - check.multipleDefaults(s.Body.List) - for _, s := range s.Body.List { - clause, _ := s.(*ast.CommClause) - if clause == nil { - continue // error reported before - } - check.optionalStmt(clause.Comm) // TODO(gri) check correctness of c.Comm (must be Send/RecvStmt) - check.stmtList(clause.Body) - } - - case *ast.ForStmt: - check.optionalStmt(s.Init) - if s.Cond != nil { - var x operand - check.expr(&x, s.Cond, nil, -1) - if !isBoolean(x.typ) { - check.errorf(s.Cond.Pos(), "non-boolean condition in for statement") - } - } - check.optionalStmt(s.Post) - check.stmt(s.Body) - - case *ast.RangeStmt: - // check expression to iterate over - decl := s.Tok == token.DEFINE - var x operand - check.expr(&x, s.X, nil, -1) - if x.mode == invalid { - // if we don't have a declaration, we can still check the loop's body - if !decl { - check.stmt(s.Body) - } - return - } - - // determine key/value types - var key, val Type - switch typ := underlying(x.typ).(type) { - case *Basic: - if isString(typ) { - key = Typ[UntypedInt] - val = Typ[UntypedRune] - } - case *Array: - key = Typ[UntypedInt] - val = typ.Elt - case *Slice: - key = Typ[UntypedInt] - val = typ.Elt - case *Pointer: - if typ, _ := underlying(typ.Base).(*Array); typ != nil { - key = Typ[UntypedInt] - val = typ.Elt - } - case *Map: - key = typ.Key - val = typ.Elt - case *Chan: - key = typ.Elt - if typ.Dir&ast.RECV == 0 { - check.errorf(x.pos(), "cannot range over send-only channel %s", &x) - // ok to continue - } - if s.Value != nil { - check.errorf(s.Value.Pos(), "iteration over %s permits only one iteration variable", &x) - // ok to continue - } - } - - if key == nil { - check.errorf(x.pos(), "cannot range over %s", &x) - // if we don't have a declaration, we can still check the loop's body - if !decl { - check.stmt(s.Body) - } - return - } - - // check assignment to/declaration of iteration variables - // TODO(gri) The error messages/positions are not great here, - // they refer to the expression in the range clause. - // Should give better messages w/o too much code - // duplication (assignment checking). - x.mode = value - if s.Key != nil { - x.typ = key - check.assign1to1(s.Key, nil, &x, decl, -1) - } else { - check.invalidAST(s.Pos(), "range clause requires index iteration variable") - // ok to continue - } - if s.Value != nil { - x.typ = val - check.assign1to1(s.Value, nil, &x, decl, -1) - } - - check.stmt(s.Body) - - default: - check.errorf(s.Pos(), "invalid statement") - } -} diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/builtins.src b/gcc-4.8.1/libgo/go/go/types/testdata/builtins.src deleted file mode 100644 index 6c848fc27..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/builtins.src +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// builtin calls - -package builtins - -import "unsafe" - -func _append() { - var x int - var s []byte - _0 := append /* ERROR "argument" */ () - _1 := append("foo" /* ERROR "not a typed slice" */) - _2 := append(nil /* ERROR "not a typed slice" */, s) - _3 := append(x /* ERROR "not a typed slice" */, s) - _4 := append(s) - append /* ERROR "not used" */ (s) -} - -func _cap() { - var a [10]bool - var p *[20]int - var s []int - var c chan string - _0 := cap /* ERROR "argument" */ () - _1 := cap /* ERROR "argument" */ (1, 2) - _2 := cap(42 /* ERROR "invalid" */) - const _3 = cap(a) - assert(_3 == 10) - const _4 = cap(p) - assert(_4 == 20) - _5 := cap(c) - cap /* ERROR "not used" */ (c) -} - -func _close() { - var c chan int - var r <-chan int - close /* ERROR "argument" */ () - close /* ERROR "argument" */ (1, 2) - close(42 /* ERROR "not a channel" */) - close(r /* ERROR "receive-only channel" */) - close(c) -} - -func _complex() { - var i32 int32 - var f32 float32 - var f64 float64 - var c64 complex64 - _ = complex /* ERROR "argument" */ () - _ = complex /* ERROR "argument" */ (1) - _ = complex(true /* ERROR "invalid argument" */ , 0) - _ = complex(i32 /* ERROR "invalid argument" */ , 0) - _ = complex("foo" /* ERROR "invalid argument" */ , 0) - _ = complex(c64 /* ERROR "invalid argument" */ , 0) - _ = complex(0, true /* ERROR "invalid argument" */ ) - _ = complex(0, i32 /* ERROR "invalid argument" */ ) - _ = complex(0, "foo" /* ERROR "invalid argument" */ ) - _ = complex(0, c64 /* ERROR "invalid argument" */ ) - _ = complex(f32, f32) - _ = complex(f32, 1) - _ = complex(f32, 1.0) - _ = complex(f32, 'a') - _ = complex(f64, f64) - _ = complex(f64, 1) - _ = complex(f64, 1.0) - _ = complex(f64, 'a') - _ = complex(f32 /* ERROR "mismatched types" */, f64) - _ = complex(f64 /* ERROR "mismatched types" */, f32) - _ = complex(1, 1) - _ = complex(1, 1.1) - _ = complex(1, 'a') - complex /* ERROR "not used" */ (1, 2) -} - -func _copy() { - copy /* ERROR "not enough arguments" */ () - copy /* ERROR "not enough arguments" */ ("foo") - copy([ /* ERROR "copy expects slice arguments" */ ...]int{}, []int{}) - copy([ /* ERROR "copy expects slice arguments" */ ]int{}, [...]int{}) - copy([ /* ERROR "different element types" */ ]int8{}, "foo") - - // spec examples - var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7} - var s = make([]int, 6) - var b = make([]byte, 5) - n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5} - n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5} - n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello") -} - -func _delete() { - var m map[string]int - var s string - delete /* ERROR "argument" */ () - delete /* ERROR "argument" */ (1) - delete /* ERROR "argument" */ (1, 2, 3) - delete(m, 0 /* ERROR "not assignable" */) - delete(m, s) -} - -func _imag() { - var f32 float32 - var f64 float64 - var c64 complex64 - var c128 complex128 - _ = imag /* ERROR "argument" */ () - _ = imag /* ERROR "argument" */ (1, 2) - _ = imag(10 /* ERROR "must be a complex number" */) - _ = imag(2.7182818 /* ERROR "must be a complex number" */) - _ = imag("foo" /* ERROR "must be a complex number" */) - const _5 = imag(1 + 2i) - assert(_5 == 2) - f32 = _5 - f64 = _5 - const _6 = imag(0i) - assert(_6 == 0) - f32 = imag(c64) - f64 = imag(c128) - f32 = imag /* ERROR "cannot assign" */ (c128) - f64 = imag /* ERROR "cannot assign" */ (c64) - imag /* ERROR "not used" */ (c64) -} - -func _len() { - const c = "foobar" - var a [10]bool - var p *[20]int - var s []int - var m map[string]complex128 - _ = len /* ERROR "argument" */ () - _ = len /* ERROR "argument" */ (1, 2) - _ = len(42 /* ERROR "invalid" */) - const _3 = len(c) - assert(_3 == 6) - const _4 = len(a) - assert(_4 == 10) - const _5 = len(p) - assert(_5 == 20) - _ = len(m) - len /* ERROR "not used" */ (c) - - // esoteric case - var t string - var hash map[interface{}][]*[10]int - const n = len /* ERROR "not constant" */ (hash[recover()][len(t)]) - assert /* ERROR "failed" */ (n == 10) - var ch <-chan int - const nn = len /* ERROR "not constant" */ (hash[<-ch][len(t)]) - _ = nn // TODO(gri) remove this once unused constants get type-checked -} - -func _make() { - n := 0 - - _ = make /* ERROR "argument" */ () - _ = make(1 /* ERROR "not a type" */) - _ = make(int /* ERROR "cannot make" */) - - // slices - _ = make/* ERROR "arguments" */ ([]int) - _ = make/* ERROR "arguments" */ ([]int, 2, 3, 4) - _ = make([]int, int /* ERROR "not an expression" */) - _ = make([]int, 10, float32 /* ERROR "not an expression" */) - _ = make([]int, "foo" /* ERROR "must be an integer" */) - _ = make([]int, 10, 2.3 /* ERROR "must be an integer" */) - _ = make([]int, 5, 10.0) - _ = make([]int, 0i) - _ = make([]int, - /* ERROR "must not be negative" */ 1, 10) - _ = make([]int, 0, - /* ERROR "must not be negative" */ 1) - _ = make([]int, - /* ERROR "must not be negative" */ 1, - /* ERROR "must not be negative" */ 1) - _ = make([]int, 1<<100, 1<<100) // run-time panic - _ = make([]int, 1 /* ERROR "length and capacity swapped" */ <<100 + 1, 1<<100) - _ = make([]int, 1 /* ERROR "length and capacity swapped" */ <<100, 12345) - - // maps - _ = make /* ERROR "arguments" */ (map[int]string, 10, 20) - _ = make(map[int]float32, int /* ERROR "not an expression" */) - _ = make(map[int]float32, "foo" /* ERROR "must be an integer" */) - _ = make(map[int]float32, 10) - _ = make(map[int]float32, n) - _ = make(map[int]float32, int64(n)) - - // channels - _ = make /* ERROR "arguments" */ (chan int, 10, 20) - _ = make(chan int, int /* ERROR "not an expression" */) - _ = make(chan<- int, "foo" /* ERROR "must be an integer" */) - _ = make(<-chan float64, 10) - _ = make(chan chan int, n) - _ = make(chan string, int64(n)) - - make /* ERROR "not used" */ ([]int, 10) -} - -func _new() { - _ = new /* ERROR "argument" */ () - _ = new /* ERROR "argument" */ (1, 2) - _ = new("foo" /* ERROR "not a type" */) - p := new(float64) - _ = new(struct{ x, y int }) - q := new(*float64) - _ = *p == **q - new /* ERROR "not used" */ (int) -} - -func _real() { - var f32 float32 - var f64 float64 - var c64 complex64 - var c128 complex128 - _ = real /* ERROR "argument" */ () - _ = real /* ERROR "argument" */ (1, 2) - _ = real(10 /* ERROR "must be a complex number" */) - _ = real(2.7182818 /* ERROR "must be a complex number" */) - _ = real("foo" /* ERROR "must be a complex number" */) - const _5 = real(1 + 2i) - assert(_5 == 1) - f32 = _5 - f64 = _5 - const _6 = real(0i) - assert(_6 == 0) - f32 = real(c64) - f64 = real(c128) - f32 = real /* ERROR "cannot assign" */ (c128) - f64 = real /* ERROR "cannot assign" */ (c64) - real /* ERROR "not used" */ (c64) -} - -func _recover() { - _ = recover() - _ = recover /* ERROR "argument" */ (10) - recover() -} - -func _Alignof() { - var x int - _ = unsafe /* ERROR "argument" */ .Alignof() - _ = unsafe /* ERROR "argument" */ .Alignof(1, 2) - _ = unsafe.Alignof(int /* ERROR "not an expression" */) - _ = unsafe.Alignof(42) - _ = unsafe.Alignof(new(struct{})) - unsafe /* ERROR "not used" */ .Alignof(x) -} - -func _Offsetof() { - var x struct{ f int } - _ = unsafe /* ERROR "argument" */ .Offsetof() - _ = unsafe /* ERROR "argument" */ .Offsetof(1, 2) - _ = unsafe.Offsetof(int /* ERROR "not an expression" */) - _ = unsafe.Offsetof(x /* ERROR "not a selector" */) - _ = unsafe.Offsetof(x.f) - _ = unsafe.Offsetof((x.f)) - _ = unsafe.Offsetof((((((((x))).f))))) - unsafe /* ERROR "not used" */ .Offsetof(x.f) -} - -func _Sizeof() { - var x int - _ = unsafe /* ERROR "argument" */ .Sizeof() - _ = unsafe /* ERROR "argument" */ .Sizeof(1, 2) - _ = unsafe.Sizeof(int /* ERROR "not an expression" */) - _ = unsafe.Sizeof(42) - _ = unsafe.Sizeof(new(complex128)) - unsafe /* ERROR "not used" */ .Sizeof(x) - - // basic types have size guarantees - assert(unsafe.Sizeof(byte(0)) == 1) - assert(unsafe.Sizeof(uint8(0)) == 1) - assert(unsafe.Sizeof(int8(0)) == 1) - assert(unsafe.Sizeof(uint16(0)) == 2) - assert(unsafe.Sizeof(int16(0)) == 2) - assert(unsafe.Sizeof(uint32(0)) == 4) - assert(unsafe.Sizeof(int32(0)) == 4) - assert(unsafe.Sizeof(float32(0)) == 4) - assert(unsafe.Sizeof(uint64(0)) == 8) - assert(unsafe.Sizeof(int64(0)) == 8) - assert(unsafe.Sizeof(float64(0)) == 8) - assert(unsafe.Sizeof(complex64(0)) == 8) - assert(unsafe.Sizeof(complex128(0)) == 16) -} - -// self-testing only -func _assert() { - var x int - assert /* ERROR "argument" */ () - assert /* ERROR "argument" */ (1, 2) - assert("foo" /* ERROR "boolean constant" */ ) - assert(x /* ERROR "boolean constant" */) - assert(true) - assert /* ERROR "failed" */ (false) -} - -// self-testing only -func _trace() { - // Uncomment the code below to test trace - will produce console output - // _ = trace /* ERROR "no value" */ () - // _ = trace(1) - // _ = trace(true, 1.2, '\'', "foo", 42i, "foo" <= "bar") -} diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/const0.src b/gcc-4.8.1/libgo/go/go/types/testdata/const0.src deleted file mode 100644 index a2ca344c7..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/const0.src +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// constant declarations - -package const0 - -// constants declarations must be initialized by constants -var x = 0 -const c0 = x /* ERROR "not constant" */ - -// untyped constants -const ( - // boolean values - ub0 = false - ub1 = true - ub2 = 2 < 1 - ub3 = ui1 == uf1 - ub4 = true /* ERROR "cannot convert" */ == 0 - - // integer values - ui0 = 0 - ui1 = 1 - ui2 = 42 - ui3 = 3141592653589793238462643383279502884197169399375105820974944592307816406286 - ui4 = -10 - - ui5 = ui0 + ui1 - ui6 = ui1 - ui1 - ui7 = ui2 * ui1 - ui8 = ui3 / ui3 - ui9 = ui3 % ui3 - - ui10 = 1 / 0 /* ERROR "division by zero" */ - ui11 = ui1 / 0 /* ERROR "division by zero" */ - ui12 = ui3 / ui0 /* ERROR "division by zero" */ - ui13 = 1 % 0 /* ERROR "division by zero" */ - ui14 = ui1 % 0 /* ERROR "division by zero" */ - ui15 = ui3 % ui0 /* ERROR "division by zero" */ - - ui16 = ui2 & ui3 - ui17 = ui2 | ui3 - ui18 = ui2 ^ ui3 - - // floating point values - uf0 = 0. - uf1 = 1. - uf2 = 4.2e1 - uf3 = 3.141592653589793238462643383279502884197169399375105820974944592307816406286 - uf4 = 1e-1 - - uf5 = uf0 + uf1 - uf6 = uf1 - uf1 - uf7 = uf2 * uf1 - uf8 = uf3 / uf3 - uf9 = uf3 /* ERROR "not defined" */ % uf3 - - uf10 = 1 / 0 /* ERROR "division by zero" */ - uf11 = uf1 / 0 /* ERROR "division by zero" */ - uf12 = uf3 / uf0 /* ERROR "division by zero" */ - - uf16 = uf2 /* ERROR "not defined" */ & uf3 - uf17 = uf2 /* ERROR "not defined" */ | uf3 - uf18 = uf2 /* ERROR "not defined" */ ^ uf3 - - // complex values - uc0 = 0.i - uc1 = 1.i - uc2 = 4.2e1i - uc3 = 3.141592653589793238462643383279502884197169399375105820974944592307816406286i - uc4 = 1e-1i - - uc5 = uc0 + uc1 - uc6 = uc1 - uc1 - uc7 = uc2 * uc1 - uc8 = uc3 / uc3 - uc9 = uc3 /* ERROR "not defined" */ % uc3 - - uc10 = 1 / 0 /* ERROR "division by zero" */ - uc11 = uc1 / 0 /* ERROR "division by zero" */ - uc12 = uc3 / uc0 /* ERROR "division by zero" */ - - uc16 = uc2 /* ERROR "not defined" */ & uc3 - uc17 = uc2 /* ERROR "not defined" */ | uc3 - uc18 = uc2 /* ERROR "not defined" */ ^ uc3 -) - -type ( - mybool bool - myint int - myfloat float64 - mycomplex complex128 -) - -// typed constants -const ( - // boolean values - tb0 bool = false - tb1 bool = true - tb2 mybool = 2 < 1 - tb3 mybool = ti1 /* ERROR "cannot compare" */ == tf1 - - // integer values - ti0 int8 = ui0 - ti1 int32 = ui1 - ti2 int64 = ui2 - ti3 myint = ui3 /* ERROR "overflows" */ - ti4 myint = ui4 - - ti5 = ti0 /* ERROR "mismatched types" */ + ti1 - ti6 = ti1 - ti1 - ti7 = ti2 /* ERROR "mismatched types" */ * ti1 - //ti8 = ti3 / ti3 // TODO(gri) enable this - //ti9 = ti3 % ti3 // TODO(gri) enable this - - ti10 = 1 / 0 /* ERROR "division by zero" */ - ti11 = ti1 / 0 /* ERROR "division by zero" */ - ti12 = ti3 /* ERROR "mismatched types" */ / ti0 - ti13 = 1 % 0 /* ERROR "division by zero" */ - ti14 = ti1 % 0 /* ERROR "division by zero" */ - ti15 = ti3 /* ERROR "mismatched types" */ % ti0 - - ti16 = ti2 /* ERROR "mismatched types" */ & ti3 - ti17 = ti2 /* ERROR "mismatched types" */ | ti4 - ti18 = ti2 ^ ti5 // no mismatched types error because the type of ti5 is unknown - - // floating point values - tf0 float32 = 0. - tf1 float32 = 1. - tf2 float64 = 4.2e1 - tf3 myfloat = 3.141592653589793238462643383279502884197169399375105820974944592307816406286 - tf4 myfloat = 1e-1 - - tf5 = tf0 + tf1 - tf6 = tf1 - tf1 - tf7 = tf2 /* ERROR "mismatched types" */ * tf1 - // tf8 = tf3 / tf3 // TODO(gri) enable this - tf9 = tf3 /* ERROR "not defined" */ % tf3 - - tf10 = 1 / 0 /* ERROR "division by zero" */ - tf11 = tf1 / 0 /* ERROR "division by zero" */ - tf12 = tf3 /* ERROR "mismatched types" */ / tf0 - - tf16 = tf2 /* ERROR "mismatched types" */ & tf3 - tf17 = tf2 /* ERROR "mismatched types" */ | tf3 - tf18 = tf2 /* ERROR "mismatched types" */ ^ tf3 - - // complex values - tc0 = 0.i - tc1 = 1.i - tc2 = 4.2e1i - tc3 = 3.141592653589793238462643383279502884197169399375105820974944592307816406286i - tc4 = 1e-1i - - tc5 = tc0 + tc1 - tc6 = tc1 - tc1 - tc7 = tc2 * tc1 - tc8 = tc3 / tc3 - tc9 = tc3 /* ERROR "not defined" */ % tc3 - - tc10 = 1 / 0 /* ERROR "division by zero" */ - tc11 = tc1 / 0 /* ERROR "division by zero" */ - tc12 = tc3 / tc0 /* ERROR "division by zero" */ - - tc16 = tc2 /* ERROR "not defined" */ & tc3 - tc17 = tc2 /* ERROR "not defined" */ | tc3 - tc18 = tc2 /* ERROR "not defined" */ ^ tc3 -) - -// initialization cycles -const ( - a /* ERROR "cycle" */ = a - b /* ERROR "cycle" */ , c /* ERROR "cycle" */, d, e = e, d, c, b // TODO(gri) should only have one cycle error - f float64 = d -) - -// multiple initialization -const ( - a1, a2, a3 = 7, 3.1415926, "foo" - b1, b2, b3 = b3, b1, 42 - _p0 = assert(a1 == 7) - _p1 = assert(a2 == 3.1415926) - _p2 = assert(a3 == "foo") - _p3 = assert(b1 == 42) - _p4 = assert(b2 == 42) - _p5 = assert(b3 == 42) -) - -// iota -const ( - iota0 = iota - iota1 = iota - iota2 = iota*2 - _a0 = assert(iota0 == 0) - _a1 = assert(iota1 == 1) - _a2 = assert(iota2 == 4) - iota6 = iota*3 - - iota7 - iota8 - _a3 = assert(iota7 == 21) - _a4 = assert(iota8 == 24) -) - -const ( - _b0 = iota - _b1 = assert(iota + iota2 == 5) -) - -// special cases -const ( - _n0 = nil /* ERROR "invalid constant type" */ - _n1 = [ /* ERROR "not constant" */ ]int{} -)
\ No newline at end of file diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/conversions.src b/gcc-4.8.1/libgo/go/go/types/testdata/conversions.src deleted file mode 100644 index 1b1518366..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/conversions.src +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// conversions - -package conversions - -// argument count -var ( - _v0 = int /* ERROR "one argument" */ () - _v1 = int /* ERROR "one argument" */ (1, 2) -) - -// -var ( - _v2 = int8(0) -)
\ No newline at end of file diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/decls0.src b/gcc-4.8.1/libgo/go/go/types/testdata/decls0.src deleted file mode 100644 index 33d4b3801..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/decls0.src +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// type declarations - -package decls0 - -import ( - "unsafe" - // we can have multiple blank imports (was bug) - _ "math" - _ "net/rpc" -) - -const pi = 3.1415 - -type ( - N undeclared /* ERROR "undeclared" */ - B bool - I int32 - A [10]P - T struct { - x, y P - } - P *T - R (*R) - F func(A) I - Y interface { - f(A) I - } - S [](((P))) - M map[I]F - C chan<- I - - // blank types must be typechecked - _ pi /* ERROR "not a type" */ - _ struct{} - _ struct{ pi /* ERROR "not a type" */ } -) - - -// invalid array types -type ( - iA0 [... /* ERROR "invalid use of '...'" */ ]byte - iA1 [1 /* ERROR "invalid array length" */ <<100]int - iA2 [- /* ERROR "invalid array length" */ 1]complex128 - iA3 ["foo" /* ERROR "invalid array length" */ ]string -) - - -type ( - p1 pi /* ERROR "no single field or method foo" */ .foo - p2 unsafe.Pointer -) - - -type ( - Pi pi /* ERROR "not a type" */ - - a /* ERROR "illegal cycle" */ a - a /* ERROR "redeclared" */ int - - // where the cycle error appears depends on the - // order in which declarations are processed - // (which depends on the order in which a map - // is iterated through) - b /* ERROR "illegal cycle" */ c - c d - d e - e b - - t *t - - U V - V *W - W U - - P1 *S2 - P2 P1 - - S0 struct { - } - S1 struct { - a, b, c int - u, v, a /* ERROR "redeclared" */ float32 - } - S2 struct { - U // anonymous field - // TODO(gri) recognize double-declaration below - // U /* ERROR "redeclared" */ int - } - S3 struct { - x S2 - } - S4/* ERROR "illegal cycle" */ struct { - S4 - } - S5 /* ERROR "illegal cycle" */ struct { - S6 - } - S6 struct { - field S7 - } - S7 struct { - S5 - } - - L1 []L1 - L2 []int - - A1 [10.0]int - A2 /* ERROR "illegal cycle" */ [10]A2 - A3 /* ERROR "illegal cycle" */ [10]struct { - x A4 - } - A4 [10]A3 - - F1 func() - F2 func(x, y, z float32) - F3 func(x, y, x /* ERROR "redeclared" */ float32) - F4 func() (x, y, x /* ERROR "redeclared" */ float32) - F5 func(x int) (x /* ERROR "redeclared" */ float32) - F6 func(x ...int) - - I1 interface{} - I2 interface { - m1() - } - I3 interface { /* ERROR "multiple methods named m1" */ - m1() - m1 /* ERROR "redeclared" */ () - } - I4 interface { - m1(x, y, x /* ERROR "redeclared" */ float32) - m2() (x, y, x /* ERROR "redeclared" */ float32) - m3(x int) (x /* ERROR "redeclared" */ float32) - } - I5 interface { - m1(I5) - } - I6 interface { - S0 /* ERROR "not an interface" */ - } - I7 interface { - I1 - I1 - } - I8 /* ERROR "illegal cycle" */ interface { - I8 - } - // Use I09 (rather than I9) because it appears lexically before - // I10 so that we get the illegal cycle here rather then in the - // declaration of I10. If the implementation sorts by position - // rather than name, the error message will still be here. - I09 /* ERROR "illegal cycle" */ interface { - I10 - } - I10 interface { - I11 - } - I11 interface { - I09 - } - - C1 chan int - C2 <-chan int - C3 chan<- C3 - C4 chan C5 - C5 chan C6 - C6 chan C4 - - M1 map[Last]string - M2 map[string]M2 - - Last int -) diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/decls1.src b/gcc-4.8.1/libgo/go/go/types/testdata/decls1.src deleted file mode 100644 index dd63ba980..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/decls1.src +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// variable declarations - -package decls1 - -import ( - "math" -) - -// Global variables without initialization -var ( - a, b bool - c byte - d uint8 - r rune - i int - j, k, l int - x, y float32 - xx, yy float64 - u, v complex64 - uu, vv complex128 - s, t string - array []byte - iface interface{} - - blank _ /* ERROR "cannot use _" */ -) - -// Global variables with initialization -var ( - s1 = i + j - s2 = i /* ERROR "mismatched types" */ + x - s3 = c + d - s4 = s + t - s5 = s /* ERROR "invalid operation" */ / t - s6 = array[t1] - s7 = array[x /* ERROR "index" */] - s8 = &a - s10 = &42 /* ERROR "cannot take address" */ - s11 = &v - s12 = -(u + *t11) / *&v - s13 = a /* ERROR "shifted operand" */ << d - s14 = i << j /* ERROR "must be unsigned" */ - s18 = math.Pi * 10.0 - s19 = s1 /* ERROR "cannot call" */ () - s20 = f0 /* ERROR "no value" */ () - s21 = f6(1, s1, i) - s22 = f6(1, s1, uu /* ERROR "cannot assign" */ ) - - t1 int = i + j - t2 int = i /* ERROR "mismatched types" */ + x - t3 int = c /* ERROR "cannot assign" */ + d - t4 string = s + t - t5 string = s /* ERROR "invalid operation" */ / t - t6 byte = array[t1] - t7 byte = array[x /* ERROR "index" */] - t8 *int = & /* ERROR "cannot assign" */ a - t10 *int = &42 /* ERROR "cannot take address" */ - t11 *complex64 = &v - t12 complex64 = -(u + *t11) / *&v - t13 int = a /* ERROR "shifted operand" */ << d - t14 int = i << j /* ERROR "must be unsigned" */ - t15 math /* ERROR "not in selector" */ - t16 math.xxx /* ERROR "unexported" */ - t17 math /* ERROR "not a type" */ .Pi - t18 float64 = math.Pi * 10.0 - t19 int = t1 /* ERROR "cannot call" */ () - t20 int = f0 /* ERROR "no value" */ () -) - -// Various more complex expressions -var ( - u1 = x /* ERROR "not an interface" */ .(int) - u2 = iface.([]int) - u3 = iface.(a /* ERROR "not a type" */ ) - u4, ok = iface.(int) - u5 /* ERROR "assignment count mismatch" */ , ok2, ok3 = iface.(int) -) - -// Constant expression initializations -var ( - v1 = 1 /* ERROR "cannot convert" */ + "foo" - v2 = c + 255 - v3 = c + 256 /* ERROR "overflows" */ - v4 = r + 2147483647 - v5 = r + 2147483648 /* ERROR "overflows" */ - v6 = 42 - v7 = v6 + 2147483647 - v8 = v6 + 2147483648 /* ERROR "overflows" */ - v9 = i + 1 << 10 - v10 byte = 1024 /* ERROR "overflows" */ - v11 = xx/yy*yy - xx - v12 = true && false - v13 = nil /* ERROR "use of untyped nil" */ -) - -// Multiple assignment expressions -var ( - m1a, m1b = 1, 2 - m2a /* ERROR "assignment count mismatch" */ , m2b, m2c = 1, 2 - m3a /* ERROR "assignment count mismatch" */ , m3b = 1, 2, 3 -) - -// Declaration of parameters and results -func f0() {} -func f1(a /* ERROR "not a type" */) {} -func f2(a, b, c d /* ERROR "not a type" */) {} - -func f3() int {} -func f4() a /* ERROR "not a type" */ {} -func f5() (a, b, c d /* ERROR "not a type" */) {} - -func f6(a, b, c int) complex128 { return 0 } - -// Declaration of receivers -type T struct{} - -func (T) m0() {} -func (*T) m1() {} -func (x T) m2() {} -func (x *T) m3() {} - - -// Initialization functions -func init() {} -func /* ERROR "no arguments and no return values" */ init(int) {} -func /* ERROR "no arguments and no return values" */ init() int { return 0 } -func /* ERROR "no arguments and no return values" */ init(int) int {} -func (T) init(int) int { return 0 } diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/decls2a.src b/gcc-4.8.1/libgo/go/go/types/testdata/decls2a.src deleted file mode 100644 index 3867be737..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/decls2a.src +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// method declarations - -package decls2 - -import "time" - -// T1 declared before its methods. -type T1 struct{ - f int -} - -func (T1) m() {} -func (T1) m /* ERROR "redeclared" */ () {} -func (x *T1) f /* ERROR "field and method" */ () {} - -// T2's method declared before the type. -func (*T2) f /* ERROR "field and method" */ () {} - -type T2 struct { - f int -} - -// Methods declared without a declared type. -func (undeclared /* ERROR "undeclared" */) m() {} -func (x *undeclared /* ERROR "undeclared" */) m() {} - -// TODO(gri) try to get rid of double error reporting here -func (pi /* ERROR "not a type" */) m1() {} -func (x pi /* ERROR "not a type" */) m2() {} -func (x *pi /* ERROR "not a type" */ ) m3() {} // TODO(gri) not closing the last /* comment crashes the system - -// Blank types. -type _ struct { m int } -type _ struct { m int } - -// TODO(gri) blank idents not fully checked - disabled for now -// func (_ /* ERROR "cannot use _" */) m() {} -// func (_ /* ERROR "cannot use _" */) m() {} - -// Methods with receiver base type declared in another file. -func (T3) m1() {} -func (*T3) m2() {} -func (x T3) m3() {} -func (x *T3) f /* ERROR "field and method" */ () {} - -// Methods of non-struct type. -type T4 func() - -func (self T4) m() func() { return self } - -// Methods associated with an interface. -type T5 interface { - m() int -} - -func (T5 /* ERROR "invalid receiver" */) m1() {} -func (T5 /* ERROR "invalid receiver" */) m2() {} - -// Methods associated with non-local or unnamed types. -func (int /* ERROR "non-local type" */ ) m() {} -func ([ /* ERROR "expected" */ ]int) m() {} -func (time /* ERROR "expected" */ .Time) m() {} -func (x interface /* ERROR "expected" */ {}) m() {} diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/decls2b.src b/gcc-4.8.1/libgo/go/go/types/testdata/decls2b.src deleted file mode 100644 index c7f9ddf01..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/decls2b.src +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// method declarations - -package decls2 - -const pi = 3.1415 - -func (T1) m /* ERROR "redeclared" */ () {} - -type T3 struct { - f *T3 -} - -type T6 struct { - x int -} - -func (t *T6) m1() int { - return t.x -} - -func f() { - var t *T6 - t.m1() -}
\ No newline at end of file diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/decls3.src b/gcc-4.8.1/libgo/go/go/types/testdata/decls3.src deleted file mode 100644 index 4bc7d4149..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/decls3.src +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// embedded types - -package decls3 - -// fields with the same name at the same level cancel each other out - -func _() { - type ( - T1 struct { X int } - T2 struct { X int } - T3 struct { T1; T2 } // X is embedded twice at the same level via T1->X, T2->X - ) - - var t T3 - _ = t /* ERROR "no single field or method" */ .X -} - -func _() { - type ( - T1 struct { X int } - T2 struct { T1 } - T3 struct { T1 } - T4 struct { T2; T3 } // X is embedded twice at the same level via T2->T1->X, T3->T1->X - ) - - var t T4 - _ = t /* ERROR "no single field or method" */ .X -} - -func issue4355() { - type ( - T1 struct {X int} - T2 struct {T1} - T3 struct {T2} - T4 struct {T2} - T5 struct {T3; T4} // X is embedded twice at the same level via T3->T2->T1->X, T4->T2->T1->X - ) - - var t T5 - _ = t /* ERROR "no single field or method" */ .X -} - -// Borrowed from the FieldByName test cases in reflect/all_test.go. - -type D1 struct { - d int -} -type D2 struct { - d int -} - -type S0 struct { - A, B, C int - D1 - D2 -} - -type S1 struct { - B int - S0 -} - -type S2 struct { - A int - *S1 -} - -type S1x struct { - S1 -} - -type S1y struct { - S1 -} - -type S3 struct { - S1x - S2 - D, E int - *S1y -} - -type S4 struct { - *S4 - A int -} - -// The X in S6 and S7 annihilate, but they also block the X in S8.S9. -type S5 struct { - S6 - S7 - S8 -} - -type S6 struct { - X int -} - -type S7 S6 - -type S8 struct { - S9 -} - -type S9 struct { - X int - Y int -} - -// The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9. -type S10 struct { - S11 - S12 - S13 -} - -type S11 struct { - S6 -} - -type S12 struct { - S6 -} - -type S13 struct { - S8 -} - -func _() { - _ = struct /* ERROR "no single field or method" */ {}{}.Foo - _ = S0{}.A - _ = S0 /* ERROR "no single field or method" */ {}.D - _ = S1{}.A - _ = S1{}.B - _ = S1{}.S0 - _ = S1{}.C - _ = S2{}.A - _ = S2{}.S1 - _ = S2{}.B - _ = S2{}.C - _ = S2 /* ERROR "no single field or method" */ {}.D - _ = S3 /* ERROR "no single field or method" */ {}.S1 - _ = S3{}.A - _ = S3 /* ERROR "no single field or method" */ {}.B - _ = S3{}.D - _ = S3{}.E - _ = S4{}.A - _ = S4 /* ERROR "no single field or method" */ {}.B - _ = S5 /* ERROR "no single field or method" */ {}.X - _ = S5{}.Y - _ = S10 /* ERROR "no single field or method" */ {}.X - _ = S10{}.Y -} - -// Borrowed from the FieldByName benchmark in reflect/all_test.go. - -type R0 struct { - *R1 - *R2 - *R3 - *R4 -} - -type R1 struct { - *R5 - *R6 - *R7 - *R8 -} - -type R2 R1 -type R3 R1 -type R4 R1 - -type R5 struct { - *R9 - *R10 - *R11 - *R12 -} - -type R6 R5 -type R7 R5 -type R8 R5 - -type R9 struct { - *R13 - *R14 - *R15 - *R16 -} - -type R10 R9 -type R11 R9 -type R12 R9 - -type R13 struct { - *R17 - *R18 - *R19 - *R20 -} - -type R14 R13 -type R15 R13 -type R16 R13 - -type R17 struct { - *R21 - *R22 - *R23 - *R24 -} - -type R18 R17 -type R19 R17 -type R20 R17 - -type R21 struct { - X int -} - -type R22 R21 -type R23 R21 -type R24 R21 - -var _ = R0 /* ERROR "no single field or method" */ {}.X
\ No newline at end of file diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/exports.go b/gcc-4.8.1/libgo/go/go/types/testdata/exports.go deleted file mode 100644 index 8ee28b094..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/exports.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file is used to generate an object file which -// serves as test file for gcimporter_test.go. - -package exports - -import ( - "go/ast" -) - -// Issue 3682: Correctly read dotted identifiers from export data. -const init1 = 0 - -func init() {} - -const ( - C0 int = 0 - C1 = 3.14159265 - C2 = 2.718281828i - C3 = -123.456e-789 - C4 = +123.456E+789 - C5 = 1234i - C6 = "foo\n" - C7 = `bar\n` -) - -type ( - T1 int - T2 [10]int - T3 []int - T4 *int - T5 chan int - T6a chan<- int - T6b chan (<-chan int) - T6c chan<- (chan int) - T7 <-chan *ast.File - T8 struct{} - T9 struct { - a int - b, c float32 - d []string `go:"tag"` - } - T10 struct { - T8 - T9 - _ *T10 - } - T11 map[int]string - T12 interface{} - T13 interface { - m1() - m2(int) float32 - } - T14 interface { - T12 - T13 - m3(x ...struct{}) []T9 - } - T15 func() - T16 func(int) - T17 func(x int) - T18 func() float32 - T19 func() (x float32) - T20 func(...interface{}) - T21 struct{ next *T21 } - T22 struct{ link *T23 } - T23 struct{ link *T22 } - T24 *T24 - T25 *T26 - T26 *T27 - T27 *T25 - T28 func(T28) T28 -) - -var ( - V0 int - V1 = -991.0 -) - -func F1() {} -func F2(x int) {} -func F3() int { return 0 } -func F4() float32 { return 0 } -func F5(a, b, c int, u, v, w struct{ x, y T1 }, more ...interface{}) (p, q, r chan<- T10) - -func (p *T1) M1() diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/expr0.src b/gcc-4.8.1/libgo/go/go/types/testdata/expr0.src deleted file mode 100644 index c3233d36f..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/expr0.src +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// unary expressions - -package expr0 - -var ( - // bool - b0 = true - b1 bool = b0 - b2 = !true - b3 = !b1 - b4 bool = !true - b5 bool = !b4 - b6 = +b0 /* ERROR "not defined" */ - b7 = -b0 /* ERROR "not defined" */ - b8 = ^b0 /* ERROR "not defined" */ - b9 = *b0 /* ERROR "cannot indirect" */ - b10 = &true /* ERROR "cannot take address" */ - b11 = &b0 - b12 = <-b0 /* ERROR "cannot receive" */ - - // int - i0 = 1 - i1 int = i0 - i2 = +1 - i3 = +i0 - i4 int = +1 - i5 int = +i4 - i6 = -1 - i7 = -i0 - i8 int = -1 - i9 int = -i4 - i10 = !i0 /* ERROR "not defined" */ - i11 = ^1 - i12 = ^i0 - i13 int = ^1 - i14 int = ^i4 - i15 = *i0 /* ERROR "cannot indirect" */ - i16 = &i0 - i17 = *i16 - i18 = <-i16 /* ERROR "cannot receive" */ - - // uint - u0 = uint(1) - u1 uint = u0 - u2 = +1 - u3 = +u0 - u4 uint = +1 - u5 uint = +u4 - u6 = -1 - u7 = -u0 - u8 uint = - /* ERROR "overflows" */ 1 - u9 uint = -u4 - u10 = !u0 /* ERROR "not defined" */ - u11 = ^1 - u12 = ^i0 - u13 uint = ^ /* ERROR "overflows" */ 1 - u14 uint = ^u4 - u15 = *u0 /* ERROR "cannot indirect" */ - u16 = &u0 - u17 = *u16 - u18 = <-u16 /* ERROR "cannot receive" */ - u19 = ^uint(0) - - // float64 - f0 = float64(1) - f1 float64 = f0 - f2 = +1 - f3 = +f0 - f4 float64 = +1 - f5 float64 = +f4 /* ERROR not defined */ - f6 = -1 - f7 = -f0 - f8 float64 = -1 - f9 float64 = -f4 - f10 = !f0 /* ERROR "not defined" */ - f11 = ^1 - f12 = ^i0 - f13 float64 = ^1 - f14 float64 = ^f4 /* ERROR "not defined" */ - f15 = *f0 /* ERROR "cannot indirect" */ - f16 = &f0 - f17 = *u16 - f18 = <-u16 /* ERROR "cannot receive" */ - - // complex128 - c0 = complex128(1) - c1 complex128 = c0 - c2 = +1 - c3 = +c0 - c4 complex128 = +1 - c5 complex128 = +c4 /* ERROR not defined */ - c6 = -1 - c7 = -c0 - c8 complex128 = -1 - c9 complex128 = -c4 - c10 = !c0 /* ERROR "not defined" */ - c11 = ^1 - c12 = ^i0 - c13 complex128 = ^1 - c14 complex128 = ^c4 /* ERROR "not defined" */ - c15 = *c0 /* ERROR "cannot indirect" */ - c16 = &c0 - c17 = *u16 - c18 = <-u16 /* ERROR "cannot receive" */ - - // string - s0 = "foo" - s1 = +"foo" /* ERROR "not defined" */ - s2 = -s0 /* ERROR "not defined" */ - s3 = !s0 /* ERROR "not defined" */ - s4 = ^s0 /* ERROR "not defined" */ - s5 = *s4 /* ERROR "cannot indirect" */ - s6 = &s4 - s7 = *s6 - s8 = <-s7 /* ERROR "cannot receive" */ - - // channel - ch chan int - rc <-chan float64 - sc chan <- string - ch0 = +ch /* ERROR "not defined" */ - ch1 = -ch /* ERROR "not defined" */ - ch2 = !ch /* ERROR "not defined" */ - ch3 = ^ch /* ERROR "not defined" */ - ch4 = *ch /* ERROR "cannot indirect" */ - ch5 = &ch - ch6 = *ch5 - ch7 = <-ch - ch8 = <-rc - ch9 = <-sc /* ERROR "cannot receive" */ -) - -// address of composite literals -type T struct{x, y int} - -func f() T { return T{} } - -var ( - _ = &T{1, 2} - _ = &[...]int{} - _ = &[]int{} - _ = &[]int{} - _ = &map[string]T{} - _ = &(T{1, 2}) - _ = &((((T{1, 2})))) - _ = &f /* ERROR "cannot take address" */ () -) diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/expr1.src b/gcc-4.8.1/libgo/go/go/types/testdata/expr1.src deleted file mode 100644 index 8ef0aed6d..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/expr1.src +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// binary expressions - -package expr1 diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/expr2.src b/gcc-4.8.1/libgo/go/go/types/testdata/expr2.src deleted file mode 100644 index 674be4005..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/expr2.src +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// comparisons - -package expr2 - -func _bool() { - const t = true == true - const f = true == false - _ = t /* ERROR "cannot compare" */ < f - _ = 0 /* ERROR "cannot convert" */ == t - var b bool - var x, y float32 - b = x < y - _ = struct{b bool}{x < y} -} - -// corner cases -var ( - v0 = nil /* ERROR "cannot compare" */ == nil -)
\ No newline at end of file diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/expr3.src b/gcc-4.8.1/libgo/go/go/types/testdata/expr3.src deleted file mode 100644 index 519e3f567..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/expr3.src +++ /dev/null @@ -1,367 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// various expressions - -package expr3 - -func shifts1() { - var ( - i0 int - u0 uint - ) - - var ( - v0 = 1<<0 - v1 = 1<<i0 /* ERROR "must be unsigned" */ - v2 = 1<<u0 - v3 = 1<<"foo" /* ERROR "must be unsigned" */ - v4 = 1<<- /* ERROR "stupid shift" */ 1 - v5 = 1<<1025 /* ERROR "stupid shift" */ - v6 = 1 /* ERROR "overflows" */ <<100 - - v10 uint = 1 << 0 - v11 uint = 1 << u0 - v12 float32 = 1 /* ERROR "must be integer" */ << u0 - ) -} - -func shifts2() { - // TODO(gri) enable commented out tests below. - var ( - s uint = 33 - i = 1<<s // 1 has type int - j int32 = 1<<s // 1 has type int32; j == 0 - k = uint64(1<<s) // 1 has type uint64; k == 1<<33 - m int = 1.0<<s // 1.0 has type int - // n = 1.0<<s != 0 // 1.0 has type int; n == false if ints are 32bits in size - o = 1<<s == 2<<s // 1 and 2 have type int; o == true if ints are 32bits in size - // p = 1<<s == 1 /* ERROR "overflows" */ <<33 // illegal if ints are 32bits in size: 1 has type int, but 1<<33 overflows int - u = 1.0 /* ERROR "must be integer" */ <<s // illegal: 1.0 has type float64, cannot shift - v float32 = 1 /* ERROR "must be integer" */ <<s // illegal: 1 has type float32, cannot shift - w int64 = 1.0<<33 // 1.0<<33 is a constant shift expression - ) -} - -// TODO(gri) The error messages below depond on adjusting the spec -// to reflect what gc is doing at the moment (the spec -// asks for run-time errors at the moment - see issue 4231). -// -func indexes() { - _ = 1 /* ERROR "cannot index" */ [0] - _ = indexes /* ERROR "cannot index" */ [0] - _ = ( /* ERROR "cannot slice" */ 12 + 3)[1:2] - - var a [10]int - _ = a[true /* ERROR "must be integer" */ ] - _ = a["foo" /* ERROR "must be integer" */ ] - _ = a[1.1 /* ERROR "must be integer" */ ] - _ = a[1.0] - _ = a[- /* ERROR "index .* negative" */ 1] - _ = a[- /* ERROR "index .* negative" */ 1 :] - _ = a[: - /* ERROR "index .* negative" */ 1] - var a0 int - a0 = a[0] - var a1 int32 - a1 = a /* ERROR "cannot assign" */ [1] - _ = a[9] - _ = a[10 /* ERROR "index .* out of bounds" */ ] - _ = a[1 /* ERROR "stupid index" */ <<100] - _ = a[10:] - _ = a[:10] - _ = a[10:10] - _ = a[11 /* ERROR "index .* out of bounds" */ :] - _ = a[: 11 /* ERROR "index .* out of bounds" */ ] - _ = a[: 1 /* ERROR "stupid index" */ <<100] - - pa := &a - _ = pa[9] - _ = pa[10 /* ERROR "index .* out of bounds" */ ] - _ = pa[1 /* ERROR "stupid index" */ <<100] - _ = pa[10:] - _ = pa[:10] - _ = pa[10:10] - _ = pa[11 /* ERROR "index .* out of bounds" */ :] - _ = pa[: 11 /* ERROR "index .* out of bounds" */ ] - _ = pa[: 1 /* ERROR "stupid index" */ <<100] - - var b [0]int - _ = b[0 /* ERROR "index .* out of bounds" */ ] - _ = b[:] - _ = b[0:] - _ = b[:0] - _ = b[0:0] - - var s []int - _ = s[- /* ERROR "index .* negative" */ 1] - _ = s[- /* ERROR "index .* negative" */ 1 :] - _ = s[: - /* ERROR "index .* negative" */ 1] - _ = s[0] - _ = s[1 : 2] - _ = s[2 /* ERROR "inverted slice range" */ : 1] - _ = s[2 :] - _ = s[: 1 /* ERROR "stupid index" */ <<100] - _ = s[1 /* ERROR "stupid index" */ <<100 :] - _ = s[1 /* ERROR "stupid index" */ <<100 : 1 /* ERROR "stupid index" */ <<100] - - var t string - _ = t[- /* ERROR "index .* negative" */ 1] - _ = t[- /* ERROR "index .* negative" */ 1 :] - _ = t[: - /* ERROR "index .* negative" */ 1] - var t0 byte - t0 = t[0] - var t1 rune - t1 = t /* ERROR "cannot assign" */ [2] - _ = ("foo" + "bar")[5] - _ = ("foo" + "bar")[6 /* ERROR "index .* out of bounds" */ ] - - const c = "foo" - _ = c[- /* ERROR "index .* negative" */ 1] - _ = c[- /* ERROR "index .* negative" */ 1 :] - _ = c[: - /* ERROR "index .* negative" */ 1] - var c0 byte - c0 = c[0] - var c2 float32 - c2 = c /* ERROR "cannot assign" */ [2] - _ = c[3 /* ERROR "index .* out of bounds" */ ] - _ = ""[0 /* ERROR "index .* out of bounds" */ ] - - _ = s[1<<30] // no compile-time error here -} - -type T struct { - x int -} - -func (*T) m() {} - -func method_expressions() { - _ = T /* ERROR "no single field or method" */ .a - _ = T /* ERROR "has no method" */ .x - _ = T.m - var f func(*T) = (*T).m - var g func(*T) = ( /* ERROR "cannot assign" */ T).m -} - -func struct_literals() { - type T0 struct { - a, b, c int - } - - type T1 struct { - T0 - a, b int - u float64 - s string - } - - // keyed elements - _ = T1{} - _ = T1{a: 0, 1 /* ERROR "mixture of .* elements" */ } - _ = T1{aa /* ERROR "unknown field" */ : 0} - _ = T1{1 /* ERROR "invalid field name" */ : 0} - _ = T1{a: 0, s: "foo", u: 0, a /* ERROR "duplicate field" */: 10} - _ = T1{a: "foo" /* ERROR "cannot use" */ } - _ = T1{c /* ERROR "unknown field" */ : 0} - _ = T1{T0: { /* ERROR "missing type" */ }} - _ = T1{T0: T0{}} - _ = T1{T0 /* ERROR "invalid field name" */ .a: 0} - - // unkeyed elements - _ = T0{1, 2, 3} - _ = T0{1, b /* ERROR "mixture" */ : 2, 3} - _ = T0{1, 2} /* ERROR "too few values" */ - _ = T0{1, 2, 3, 4 /* ERROR "too many values" */ } - _ = T0{1, "foo" /* ERROR "cannot use" */, 3.4 /* ERROR "cannot use" */} -} - -func array_literals() { - type A0 [0]int - _ = A0{} - _ = A0{0 /* ERROR "index .* out of bounds" */} - _ = A0{0 /* ERROR "index .* out of bounds" */ : 0} - - type A1 [10]int - _ = A1{} - _ = A1{0, 1, 2} - _ = A1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - _ = A1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 /* ERROR "index .* out of bounds" */ } - _ = A1{- /* ERROR "index .* negative" */ 1: 0} - _ = A1{8: 8, 9} - _ = A1{8: 8, 9, 10 /* ERROR "index .* out of bounds" */ } - _ = A1{0, 1, 2, 0 /* ERROR "duplicate index" */ : 0, 3: 3, 4} - _ = A1{5: 5, 6, 7, 3: 3, 4} - _ = A1{5: 5, 6, 7, 3: 3, 4, 5 /* ERROR "duplicate index" */ } - _ = A1{10 /* ERROR "index .* out of bounds" */ : 10, 10 /* ERROR "index .* out of bounds" */ : 10} - _ = A1{5: 5, 6, 7, 3: 3, 1 /* ERROR "stupid index" */ <<100: 4, 5 /* ERROR "duplicate index" */ } - _ = A1{5: 5, 6, 7, 4: 4, 1 /* ERROR "stupid index" */ <<100: 4} - _ = A1{2.0} - _ = A1{2.1 /* ERROR "cannot use" */ } - _ = A1{"foo" /* ERROR "cannot use" */ } - - a0 := [...]int{} - assert(len(a0) == 0) - - a1 := [...]int{0, 1, 2} - assert(len(a1) == 3) - var a13 [3]int - var a14 [4]int - a13 = a1 - a14 = a1 /* ERROR "cannot assign" */ - - a2 := [...]int{- /* ERROR "index .* negative" */ 1: 0} - - a3 := [...]int{0, 1, 2, 0 /* ERROR "duplicate index" */ : 0, 3: 3, 4} - assert(len(a3) == 5) // somewhat arbitrary - - a4 := [...]complex128{0, 1, 2, 1<<10-2: -1i, 1i, 400: 10, 12, 14} - assert(len(a4) == 1024) - - // from the spec - type Point struct { x, y float32 } - _ = [...]Point{Point{1.5, -3.5}, Point{0, 0}} - _ = [...]Point{{1.5, -3.5}, {0, 0}} - _ = [][]int{[]int{1, 2, 3}, []int{4, 5}} - _ = [][]int{{1, 2, 3}, {4, 5}} - _ = [...]*Point{&Point{1.5, -3.5}, &Point{0, 0}} - _ = [...]*Point{{1.5, -3.5}, {0, 0}} -} - -func slice_literals() { - type S0 []int - _ = S0{} - _ = S0{0, 1, 2} - _ = S0{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - _ = S0{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - _ = S0{- /* ERROR "index .* negative" */ 1: 0} - _ = S0{8: 8, 9} - _ = S0{8: 8, 9, 10} - _ = S0{0, 1, 2, 0 /* ERROR "duplicate index" */ : 0, 3: 3, 4} - _ = S0{5: 5, 6, 7, 3: 3, 4} - _ = S0{5: 5, 6, 7, 3: 3, 4, 5 /* ERROR "duplicate index" */ } - _ = S0{10: 10, 10 /* ERROR "duplicate index" */ : 10} - _ = S0{5: 5, 6, 7, 3: 3, 1 /* ERROR "stupid index" */ <<100: 4, 5 /* ERROR "duplicate index" */ } - _ = S0{5: 5, 6, 7, 4: 4, 1 /* ERROR "stupid index" */ <<100: 4} - _ = S0{2.0} - _ = S0{2.1 /* ERROR "cannot use" */ } - _ = S0{"foo" /* ERROR "cannot use" */ } - - // indices must be resolved correctly - // (for details, see comment in go/parser/parser.go, method parseElement) - index1 := 1 - _ = S0{index1: 1} - _ = S0{index2: 2} - _ = S0{index3 /* ERROR "undeclared name" */ : 3} -} - -var index2 int = 2 - -func map_literals() { - type M0 map[string]int - - _ = M0{} - _ = M0{1 /* ERROR "missing key" */ } - _ = M0{1 /* ERROR "cannot use .* as string key" */ : 2} - _ = M0{"foo": "bar" /* ERROR "cannot use .* as int value" */ } - _ = M0{"foo": 1, "bar": 2, "foo" /* ERROR "duplicate key" */ : 3 } - - // map keys must be resolved correctly - // (for detials, see comment in go/parser/parser.go, method parseElement) - key1 := "foo" - _ = M0{key1: 1} - _ = M0{key2: 2} - _ = M0{key3 /* ERROR "undeclared name" */ : 2} -} - -var key2 string = "bar" - -type I interface { - m() -} - -type I2 interface { - m(int) -} - -type T1 struct{} -type T2 struct{} - -func (T2) m(int) {} - -func type_asserts() { - var x int - _ = x /* ERROR "not an interface" */ .(int) - - var e interface{} - var ok bool - x, ok = e.(int) - - var t I - _ = t /* ERROR "use of .* outside type switch" */ .(type) - _ = t.(T) - _ = t.(T1 /* ERROR "missing method m" */ ) - _ = t.(T2 /* ERROR "wrong type for method m" */ ) - _ = t.(I2 /* ERROR "wrong type for method m" */ ) -} - -func f0() {} -func f1(x int) {} -func f2(u float32, s string) {} -func fs(s []byte) {} -func fv(x ...int) {} -func fi(x ... interface{}) {} - -func g0() {} -func g1() int { return 0} -func g2() (u float32, s string) { return } -func gs() []byte { return nil } - -func _calls() { - var x int - var y float32 - var s []int - - f0() - _ = f0 /* ERROR "used as value" */ () - f0(g0 /* ERROR "too many arguments" */ ) - - f1(0) - f1(x) - f1(10.0) - f1 /* ERROR "too few arguments" */ () - f1(x, y /* ERROR "too many arguments" */ ) - f1(s /* ERROR "cannot assign" */ ) - f1(x ... /* ERROR "cannot use ..." */ ) - f1(g0 /* ERROR "used as value" */ ()) - f1(g1()) - // f1(g2()) // TODO(gri) missing position in error message - - f2 /* ERROR "too few arguments" */ () - f2 /* ERROR "too few arguments" */ (3.14) - f2(3.14, "foo") - f2(x /* ERROR "cannot assign" */ , "foo") - f2(g0 /* ERROR "used as value" */ ()) - f2 /* ERROR "too few arguments" */ (g1 /* ERROR "cannot assign" */ ()) - f2(g2()) - - fs /* ERROR "too few arguments" */ () - fs(g0 /* ERROR "used as value" */ ()) - fs(g1 /* ERROR "cannot assign" */ ()) - // fs(g2()) // TODO(gri) missing position in error message - fs(gs()) - - fv() - fv(1, 2.0, x) - fv(s /* ERROR "cannot assign" */ ) - fv(s...) - fv(1, s /* ERROR "can only use ... with matching parameter" */ ...) - fv(gs /* ERROR "cannot assign" */ ()) - fv(gs /* ERROR "cannot assign" */ ()...) - - fi() - fi(1, 2.0, x, 3.14, "foo") - fi(g2()) - fi(0, g2) - fi(0, g2 /* ERROR "2-valued expression" */ ()) -}
\ No newline at end of file diff --git a/gcc-4.8.1/libgo/go/go/types/testdata/stmt0.src b/gcc-4.8.1/libgo/go/go/types/testdata/stmt0.src deleted file mode 100644 index ca36834fd..000000000 --- a/gcc-4.8.1/libgo/go/go/types/testdata/stmt0.src +++ /dev/null @@ -1,274 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// statements - -package stmt0 - -func _() { - b, i, f, c, s := false, 1, 1.0, 1i, "foo" - b = i /* ERROR "cannot assign" */ - i = f /* ERROR "cannot assign" */ - f = c /* ERROR "cannot assign" */ - c = s /* ERROR "cannot assign" */ - s = b /* ERROR "cannot assign" */ - - v0 /* ERROR "mismatch" */, v1, v2 := 1, 2, 3, 4 - - b = true - - i += 1 - i += "foo" /* ERROR "cannot convert.*int" */ - - f -= 1 - f -= "foo" /* ERROR "cannot convert.*float64" */ - - c *= 1 - c /= 0 /* ERROR "division by zero" */ - - s += "bar" - s += 1 /* ERROR "cannot convert.*string" */ -} - -func _incdecs() { - const c = 3.14 - c /* ERROR "cannot assign" */ ++ - s := "foo" - s /* ERROR "cannot convert" */ -- - 3.14 /* ERROR "cannot assign" */ ++ - var ( - x int - y float32 - z complex128 - ) - x++ - y-- - z++ -} - -func _sends() { - var ch chan int - var rch <-chan int - var x int - x /* ERROR "cannot send" */ <- x - rch /* ERROR "cannot send" */ <- x - ch /* ERROR "cannot send" */ <- "foo" - ch <- x -} - -func _selects() { - select {} - var ( - ch chan int - sc chan <- bool - x int - ) - select { - case <-ch: - ch <- x - case t, ok := <-ch: - x = t - case <-sc /* ERROR "cannot receive from send-only channel" */ : - } - select { - default: - default /* ERROR "multiple defaults" */ : - } -} - -func _gos() { - go 1 /* ERROR "expected function/method call" */ - go _gos() - var c chan int - go close(c) - go len(c) // TODO(gri) this should not be legal -} - -func _defers() { - defer 1 /* ERROR "expected function/method call" */ - defer _defers() - var c chan int - defer close(c) - defer len(c) // TODO(gri) this should not be legal -} - -func _switches() { - var x int - - switch x { - default: - default /* ERROR "multiple defaults" */ : - } - - switch { - case 1 /* ERROR "cannot convert" */ : - } - - switch int32(x) { - case 1, 2: - case x /* ERROR "cannot compare" */ : - } - - switch x { - case 1 /* ERROR "overflows int" */ << 100: - } - - switch x { - case 1: - case 1 /* ERROR "duplicate case" */ : - case 2, 3, 4: - case 1 /* ERROR "duplicate case" */ : - } - - // TODO(gri) duplicate 64bit values that don't fit into an int64 are not yet detected - switch uint64(x) { - case 1<<64-1: - case 1<<64-1: - } -} - -type I interface { - m() -} - -type I2 interface { - m(int) -} - -type T struct{} -type T1 struct{} -type T2 struct{} - -func (T) m() {} -func (T2) m(int) {} - -func _typeswitches() { - var i int - var x interface{} - - switch x.(type) {} - switch (x /* ERROR "outside type switch" */ .(type)) {} - - switch x.(type) { - default: - default /* ERROR "multiple defaults" */ : - } - - switch x := x.(type) {} - - switch x := x.(type) { - case int: - var y int = x - } - - switch x := i /* ERROR "not an interface" */ .(type) {} - - switch t := x.(type) { - case nil: - var v bool = t /* ERROR "cannot assign" */ - case int: - var v int = t - case float32, complex64: - var v float32 = t /* ERROR "cannot assign" */ - default: - var v float32 = t /* ERROR "cannot assign" */ - } - - var t I - switch t.(type) { - case T: - case T1 /* ERROR "missing method m" */ : - case T2 /* ERROR "wrong type for method m" */ : - case I2 /* ERROR "wrong type for method m" */ : - } -} - -func _rangeloops() { - var ( - x int - a [10]float32 - b []string - p *[10]complex128 - pp **[10]complex128 - s string - m map[int]bool - c chan int - sc chan<- int - rc <-chan int - ) - - for _ = range x /* ERROR "cannot range over" */ {} - for i := range x /* ERROR "cannot range over" */ {} - - for i := range a { - var ii int - ii = i - } - for i, x := range a { - var ii int - ii = i - var xx float64 - xx = x /* ERROR "cannot assign" */ - } - var ii int - var xx float32 - for ii, xx := range a {} - - for i := range b { - var ii int - ii = i - } - for i, x := range b { - var ii int - ii = i - var xx string - xx = x - } - - for i := range s { - var ii int - ii = i - } - for i, x := range s { - var ii int - ii = i - var xx rune - xx = x - } - - for _, x := range p { - var xx complex128 - xx = x - } - - for _, x := range pp /* ERROR "cannot range over" */ {} - - for k := range m { - var kk int32 - kk = k /* ERROR "cannot assign" */ - } - for k, v := range m { - var kk int - kk = k - if v {} - } - - for _, _ /* ERROR "only one iteration variable" */ = range c {} - for e := range c { - var ee int - ee = e - } - for _ = range sc /* ERROR "cannot range over send-only channel" */ {} - for _ = range rc {} - - // constant strings - const cs = "foo" - for i, x := range cs {} - for i, x := range "" { - var ii int - ii = i - var xx rune - xx = x - } -}
\ No newline at end of file diff --git a/gcc-4.8.1/libgo/go/go/types/types.go b/gcc-4.8.1/libgo/go/go/types/types.go deleted file mode 100644 index 2107a20d1..000000000 --- a/gcc-4.8.1/libgo/go/go/types/types.go +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package types - -import "go/ast" - -// All types implement the Type interface. -type Type interface { - String() string - aType() -} - -// BasicKind describes the kind of basic type. -type BasicKind int - -const ( - Invalid BasicKind = iota // type is invalid - - // predeclared types - Bool - Int - Int8 - Int16 - Int32 - Int64 - Uint - Uint8 - Uint16 - Uint32 - Uint64 - Uintptr - Float32 - Float64 - Complex64 - Complex128 - String - UnsafePointer - - // types for untyped values - UntypedBool - UntypedInt - UntypedRune - UntypedFloat - UntypedComplex - UntypedString - UntypedNil - - // aliases - Byte = Uint8 - Rune = Int32 -) - -// BasicInfo is a set of flags describing properties of a basic type. -type BasicInfo int - -// Properties of basic types. -const ( - IsBoolean BasicInfo = 1 << iota - IsInteger - IsUnsigned - IsFloat - IsComplex - IsString - IsUntyped - - IsOrdered = IsInteger | IsFloat | IsString - IsNumeric = IsInteger | IsFloat | IsComplex - IsConstType = IsBoolean | IsNumeric | IsString -) - -// A Basic represents a basic type. -type Basic struct { - Kind BasicKind - Info BasicInfo - Size int64 - Name string -} - -// An Array represents an array type [Len]Elt. -type Array struct { - Len int64 - Elt Type -} - -// A Slice represents a slice type []Elt. -type Slice struct { - Elt Type -} - -// A QualifiedName is a name qualified with the package that declared the name. -type QualifiedName struct { - Pkg *Package // nil only for predeclared error.Error - Name string // unqualified type name for anonymous fields -} - -// IsSame reports whether p and q are the same. -func (p QualifiedName) IsSame(q QualifiedName) bool { - // spec: - // "Two identifiers are different if they are spelled differently, - // or if they appear in different packages and are not exported. - // Otherwise, they are the same." - if p.Name != q.Name { - return false - } - // p.Name == q.Name - return ast.IsExported(p.Name) || p.Pkg == q.Pkg -} - -// A Field represents a field of a struct. -type Field struct { - QualifiedName - Type Type - Tag string - IsAnonymous bool -} - -// A Struct represents a struct type struct{...}. -type Struct struct { - Fields []*Field -} - -func (typ *Struct) fieldIndex(name string) int { - for i, f := range typ.Fields { - if f.Name == name { - return i - } - } - return -1 -} - -// A Pointer represents a pointer type *Base. -type Pointer struct { - Base Type -} - -// A Result represents a (multi-value) function call result. -type Result struct { - Values []*Var // Signature.Results of the function called -} - -// A Signature represents a user-defined function type func(...) (...). -type Signature struct { - Recv *Var // nil if not a method - Params []*Var // (incoming) parameters from left to right; or nil - Results []*Var // (outgoing) results from left to right; or nil - IsVariadic bool // true if the last parameter's type is of the form ...T -} - -// builtinId is an id of a builtin function. -type builtinId int - -// Predeclared builtin functions. -const ( - // Universe scope - _Append builtinId = iota - _Cap - _Close - _Complex - _Copy - _Delete - _Imag - _Len - _Make - _New - _Panic - _Print - _Println - _Real - _Recover - - // Unsafe package - _Alignof - _Offsetof - _Sizeof - - // Testing support - _Assert - _Trace -) - -// A builtin represents the type of a built-in function. -type builtin struct { - id builtinId - name string - nargs int // number of arguments (minimum if variadic) - isVariadic bool - isStatement bool // true if the built-in is valid as an expression statement -} - -// A Method represents a method. -type Method struct { - QualifiedName - Type *Signature -} - -// An Interface represents an interface type interface{...}. -type Interface struct { - Methods []*Method // TODO(gri) consider keeping them in sorted order -} - -// A Map represents a map type map[Key]Elt. -type Map struct { - Key, Elt Type -} - -// A Chan represents a channel type chan Elt, <-chan Elt, or chan<-Elt. -type Chan struct { - Dir ast.ChanDir - Elt Type -} - -// A NamedType represents a named type as declared in a type declaration. -type NamedType struct { - Obj *TypeName // corresponding declared object - Underlying Type // nil if not fully declared yet; never a *NamedType - Methods []*Method // TODO(gri) consider keeping them in sorted order -} - -func (*Basic) aType() {} -func (*Array) aType() {} -func (*Slice) aType() {} -func (*Struct) aType() {} -func (*Pointer) aType() {} -func (*Result) aType() {} -func (*Signature) aType() {} -func (*builtin) aType() {} -func (*Interface) aType() {} -func (*Map) aType() {} -func (*Chan) aType() {} -func (*NamedType) aType() {} diff --git a/gcc-4.8.1/libgo/go/go/types/types_test.go b/gcc-4.8.1/libgo/go/go/types/types_test.go deleted file mode 100644 index 8e228fa67..000000000 --- a/gcc-4.8.1/libgo/go/go/types/types_test.go +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains tests verifying the types associated with an AST after -// type checking. - -package types - -import ( - "go/ast" - "go/parser" - "testing" -) - -const filename = "<src>" - -func makePkg(t *testing.T, src string) (*Package, error) { - file, err := parser.ParseFile(fset, filename, src, parser.DeclarationErrors) - if err != nil { - return nil, err - } - pkg, err := Check(fset, []*ast.File{file}) - return pkg, err -} - -type testEntry struct { - src, str string -} - -// dup returns a testEntry where both src and str are the same. -func dup(s string) testEntry { - return testEntry{s, s} -} - -var testTypes = []testEntry{ - // basic types - dup("int"), - dup("float32"), - dup("string"), - - // arrays - dup("[10]int"), - - // slices - dup("[]int"), - dup("[][]int"), - - // structs - dup("struct{}"), - dup("struct{x int}"), - {`struct { - x, y int - z float32 "foo" - }`, `struct{x int; y int; z float32 "foo"}`}, - {`struct { - string - elems []T - }`, `struct{string; elems []T}`}, - - // pointers - dup("*int"), - dup("***struct{}"), - dup("*struct{a int; b float32}"), - - // functions - dup("func()"), - dup("func(x int)"), - {"func(x, y int)", "func(x int, y int)"}, - {"func(x, y int, z string)", "func(x int, y int, z string)"}, - dup("func(int)"), - {"func(int, string, byte)", "func(int, string, byte)"}, - - dup("func() int"), - {"func() (string)", "func() string"}, - dup("func() (u int)"), - {"func() (u, v int, w string)", "func() (u int, v int, w string)"}, - - dup("func(int) string"), - dup("func(x int) string"), - dup("func(x int) (u string)"), - {"func(x, y int) (u string)", "func(x int, y int) (u string)"}, - - dup("func(...int) string"), - dup("func(x ...int) string"), - dup("func(x ...int) (u string)"), - {"func(x, y ...int) (u string)", "func(x int, y ...int) (u string)"}, - - // interfaces - dup("interface{}"), - dup("interface{m()}"), - dup(`interface{m(int) float32; String() string}`), - // TODO(gri) add test for interface w/ anonymous field - - // maps - dup("map[string]int"), - {"map[struct{x, y int}][]byte", "map[struct{x int; y int}][]byte"}, - - // channels - dup("chan int"), - dup("chan<- func()"), - dup("<-chan []func() int"), -} - -func TestTypes(t *testing.T) { - for _, test := range testTypes { - src := "package p; type T " + test.src - pkg, err := makePkg(t, src) - if err != nil { - t.Errorf("%s: %s", src, err) - continue - } - typ := underlying(pkg.Scope.Lookup("T").GetType()) - str := typeString(typ) - if str != test.str { - t.Errorf("%s: got %s, want %s", test.src, str, test.str) - } - } -} - -var testExprs = []testEntry{ - // basic type literals - dup("x"), - dup("true"), - dup("42"), - dup("3.1415"), - dup("2.71828i"), - dup(`'a'`), - dup(`"foo"`), - dup("`bar`"), - - // arbitrary expressions - dup("&x"), - dup("*&x"), - dup("(x)"), - dup("x + y"), - dup("x + y * 10"), - dup("t.foo"), - dup("s[0]"), - dup("s[x:y]"), - dup("s[:y]"), - dup("s[x:]"), - dup("s[:]"), - dup("f(1, 2.3)"), - dup("-f(10, 20)"), - dup("f(x + y, +3.1415)"), - {"func(a, b int) {}", "(func literal)"}, - {"func(a, b int) []int {}(1, 2)[x]", "(func literal)(1, 2)[x]"}, - {"[]int{1, 2, 3}", "(composite literal)"}, - {"[]int{1, 2, 3}[x:]", "(composite literal)[x:]"}, - {"i.([]string)", "i.(...)"}, -} - -func TestExprs(t *testing.T) { - for _, test := range testExprs { - src := "package p; var _ = " + test.src + "; var (x, y int; s []string; f func(int, float32) int; i interface{}; t interface { foo() })" - file, err := parser.ParseFile(fset, filename, src, parser.DeclarationErrors) - if err != nil { - t.Errorf("%s: %s", src, err) - continue - } - // TODO(gri) writing the code below w/o the decl variable will - // cause a 386 compiler error (out of fixed registers) - decl := file.Decls[0].(*ast.GenDecl) - expr := decl.Specs[0].(*ast.ValueSpec).Values[0] - str := exprString(expr) - if str != test.str { - t.Errorf("%s: got %s, want %s", test.src, str, test.str) - } - } -} diff --git a/gcc-4.8.1/libgo/go/go/types/universe.go b/gcc-4.8.1/libgo/go/go/types/universe.go deleted file mode 100644 index 8e9f6aaa0..000000000 --- a/gcc-4.8.1/libgo/go/go/types/universe.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements the universe and unsafe package scopes. - -package types - -import ( - "go/ast" - "strings" -) - -var ( - Universe *Scope - Unsafe *Package - universeIota *Const -) - -// Predeclared types, indexed by BasicKind. -var Typ = [...]*Basic{ - Invalid: {Invalid, 0, 0, "invalid type"}, - - Bool: {Bool, IsBoolean, 1, "bool"}, - Int: {Int, IsInteger, 0, "int"}, - Int8: {Int8, IsInteger, 1, "int8"}, - Int16: {Int16, IsInteger, 2, "int16"}, - Int32: {Int32, IsInteger, 4, "int32"}, - Int64: {Int64, IsInteger, 8, "int64"}, - Uint: {Uint, IsInteger | IsUnsigned, 0, "uint"}, - Uint8: {Uint8, IsInteger | IsUnsigned, 1, "uint8"}, - Uint16: {Uint16, IsInteger | IsUnsigned, 2, "uint16"}, - Uint32: {Uint32, IsInteger | IsUnsigned, 4, "uint32"}, - Uint64: {Uint64, IsInteger | IsUnsigned, 8, "uint64"}, - Uintptr: {Uintptr, IsInteger | IsUnsigned, 0, "uintptr"}, - Float32: {Float32, IsFloat, 4, "float32"}, - Float64: {Float64, IsFloat, 8, "float64"}, - Complex64: {Complex64, IsComplex, 8, "complex64"}, - Complex128: {Complex128, IsComplex, 16, "complex128"}, - String: {String, IsString, 0, "string"}, - UnsafePointer: {UnsafePointer, 0, 0, "Pointer"}, - - UntypedBool: {UntypedBool, IsBoolean | IsUntyped, 0, "untyped boolean"}, - UntypedInt: {UntypedInt, IsInteger | IsUntyped, 0, "untyped integer"}, - UntypedRune: {UntypedRune, IsInteger | IsUntyped, 0, "untyped rune"}, - UntypedFloat: {UntypedFloat, IsFloat | IsUntyped, 0, "untyped float"}, - UntypedComplex: {UntypedComplex, IsComplex | IsUntyped, 0, "untyped complex"}, - UntypedString: {UntypedString, IsString | IsUntyped, 0, "untyped string"}, - UntypedNil: {UntypedNil, IsUntyped, 0, "untyped nil"}, -} - -var aliases = [...]*Basic{ - {Byte, IsInteger | IsUnsigned, 1, "byte"}, - {Rune, IsInteger, 4, "rune"}, -} - -var predeclaredConstants = [...]*Const{ - {"true", Typ[UntypedBool], true, nil}, - {"false", Typ[UntypedBool], false, nil}, - {"iota", Typ[UntypedInt], zeroConst, nil}, - {"nil", Typ[UntypedNil], nilConst, nil}, -} - -var predeclaredFunctions = [...]*builtin{ - {_Append, "append", 1, true, false}, - {_Cap, "cap", 1, false, false}, - {_Close, "close", 1, false, true}, - {_Complex, "complex", 2, false, false}, - {_Copy, "copy", 2, false, true}, - {_Delete, "delete", 2, false, true}, - {_Imag, "imag", 1, false, false}, - {_Len, "len", 1, false, false}, - {_Make, "make", 1, true, false}, - {_New, "new", 1, false, false}, - {_Panic, "panic", 1, false, true}, - {_Print, "print", 1, true, true}, - {_Println, "println", 1, true, true}, - {_Real, "real", 1, false, false}, - {_Recover, "recover", 0, false, true}, - - {_Alignof, "Alignof", 1, false, false}, - {_Offsetof, "Offsetof", 1, false, false}, - {_Sizeof, "Sizeof", 1, false, false}, -} - -func init() { - Universe = new(Scope) - Unsafe = &Package{Name: "unsafe", Scope: new(Scope)} - - // predeclared types - for _, t := range Typ { - def(&TypeName{Name: t.Name, Type: t}) - } - for _, t := range aliases { - def(&TypeName{Name: t.Name, Type: t}) - } - - // error type - { - // Error has a nil package in its qualified name since it is in no package - err := &Method{QualifiedName{nil, "Error"}, &Signature{Results: []*Var{{Name: "", Type: Typ[String]}}}} - def(&TypeName{Name: "error", Type: &NamedType{Underlying: &Interface{Methods: []*Method{err}}}}) - } - - for _, c := range predeclaredConstants { - def(c) - } - - for _, f := range predeclaredFunctions { - def(&Func{Name: f.name, Type: f}) - } - - universeIota = Universe.Lookup("iota").(*Const) -} - -// Objects with names containing blanks are internal and not entered into -// a scope. Objects with exported names are inserted in the unsafe package -// scope; other objects are inserted in the universe scope. -// -func def(obj Object) { - name := obj.GetName() - if strings.Index(name, " ") >= 0 { - return // nothing to do - } - // fix Obj link for named types - if typ, ok := obj.GetType().(*NamedType); ok { - typ.Obj = obj.(*TypeName) - } - // exported identifiers go into package unsafe - scope := Universe - if ast.IsExported(name) { - scope = Unsafe.Scope - } - if scope.Insert(obj) != nil { - panic("internal error: double declaration") - } -} |