github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/src/go/doc/reader.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package doc
     6  
     7  import (
     8  	"go/ast"
     9  	"go/token"
    10  	"regexp"
    11  	"sort"
    12  	"strconv"
    13  )
    14  
    15  // ----------------------------------------------------------------------------
    16  // function/method sets
    17  //
    18  // Internally, we treat functions like methods and collect them in method sets.
    19  
    20  // A methodSet describes a set of methods. Entries where Decl == nil are conflict
    21  // entries (more than one method with the same name at the same embedding level).
    22  //
    23  type methodSet map[string]*Func
    24  
    25  // recvString returns a string representation of recv of the
    26  // form "T", "*T", or "BADRECV" (if not a proper receiver type).
    27  //
    28  func recvString(recv ast.Expr) string {
    29  	switch t := recv.(type) {
    30  	case *ast.Ident:
    31  		return t.Name
    32  	case *ast.StarExpr:
    33  		return "*" + recvString(t.X)
    34  	}
    35  	return "BADRECV"
    36  }
    37  
    38  // set creates the corresponding Func for f and adds it to mset.
    39  // If there are multiple f's with the same name, set keeps the first
    40  // one with documentation; conflicts are ignored.
    41  //
    42  func (mset methodSet) set(f *ast.FuncDecl) {
    43  	name := f.Name.Name
    44  	if g := mset[name]; g != nil && g.Doc != "" {
    45  		// A function with the same name has already been registered;
    46  		// since it has documentation, assume f is simply another
    47  		// implementation and ignore it. This does not happen if the
    48  		// caller is using go/build.ScanDir to determine the list of
    49  		// files implementing a package.
    50  		return
    51  	}
    52  	// function doesn't exist or has no documentation; use f
    53  	recv := ""
    54  	if f.Recv != nil {
    55  		var typ ast.Expr
    56  		// be careful in case of incorrect ASTs
    57  		if list := f.Recv.List; len(list) == 1 {
    58  			typ = list[0].Type
    59  		}
    60  		recv = recvString(typ)
    61  	}
    62  	mset[name] = &Func{
    63  		Doc:  f.Doc.Text(),
    64  		Name: name,
    65  		Decl: f,
    66  		Recv: recv,
    67  		Orig: recv,
    68  	}
    69  	f.Doc = nil // doc consumed - remove from AST
    70  }
    71  
    72  // add adds method m to the method set; m is ignored if the method set
    73  // already contains a method with the same name at the same or a higher
    74  // level than m.
    75  //
    76  func (mset methodSet) add(m *Func) {
    77  	old := mset[m.Name]
    78  	if old == nil || m.Level < old.Level {
    79  		mset[m.Name] = m
    80  		return
    81  	}
    82  	if old != nil && m.Level == old.Level {
    83  		// conflict - mark it using a method with nil Decl
    84  		mset[m.Name] = &Func{
    85  			Name:  m.Name,
    86  			Level: m.Level,
    87  		}
    88  	}
    89  }
    90  
    91  // ----------------------------------------------------------------------------
    92  // Named types
    93  
    94  // baseTypeName returns the name of the base type of x (or "")
    95  // and whether the type is imported or not.
    96  //
    97  func baseTypeName(x ast.Expr) (name string, imported bool) {
    98  	switch t := x.(type) {
    99  	case *ast.Ident:
   100  		return t.Name, false
   101  	case *ast.SelectorExpr:
   102  		if _, ok := t.X.(*ast.Ident); ok {
   103  			// only possible for qualified type names;
   104  			// assume type is imported
   105  			return t.Sel.Name, true
   106  		}
   107  	case *ast.StarExpr:
   108  		return baseTypeName(t.X)
   109  	}
   110  	return
   111  }
   112  
   113  // An embeddedSet describes a set of embedded types.
   114  type embeddedSet map[*namedType]bool
   115  
   116  // A namedType represents a named unqualified (package local, or possibly
   117  // predeclared) type. The namedType for a type name is always found via
   118  // reader.lookupType.
   119  //
   120  type namedType struct {
   121  	doc  string       // doc comment for type
   122  	name string       // type name
   123  	decl *ast.GenDecl // nil if declaration hasn't been seen yet
   124  
   125  	isEmbedded bool        // true if this type is embedded
   126  	isStruct   bool        // true if this type is a struct
   127  	embedded   embeddedSet // true if the embedded type is a pointer
   128  
   129  	// associated declarations
   130  	values  []*Value // consts and vars
   131  	funcs   methodSet
   132  	methods methodSet
   133  }
   134  
   135  // ----------------------------------------------------------------------------
   136  // AST reader
   137  
   138  // reader accumulates documentation for a single package.
   139  // It modifies the AST: Comments (declaration documentation)
   140  // that have been collected by the reader are set to nil
   141  // in the respective AST nodes so that they are not printed
   142  // twice (once when printing the documentation and once when
   143  // printing the corresponding AST node).
   144  //
   145  type reader struct {
   146  	mode Mode
   147  
   148  	// package properties
   149  	doc       string // package documentation, if any
   150  	filenames []string
   151  	notes     map[string][]*Note
   152  
   153  	// declarations
   154  	imports   map[string]int
   155  	hasDotImp bool     // if set, package contains a dot import
   156  	values    []*Value // consts and vars
   157  	types     map[string]*namedType
   158  	funcs     methodSet
   159  
   160  	// support for package-local error type declarations
   161  	errorDecl bool                 // if set, type "error" was declared locally
   162  	fixlist   []*ast.InterfaceType // list of interfaces containing anonymous field "error"
   163  }
   164  
   165  func (r *reader) isVisible(name string) bool {
   166  	return r.mode&AllDecls != 0 || ast.IsExported(name)
   167  }
   168  
   169  // lookupType returns the base type with the given name.
   170  // If the base type has not been encountered yet, a new
   171  // type with the given name but no associated declaration
   172  // is added to the type map.
   173  //
   174  func (r *reader) lookupType(name string) *namedType {
   175  	if name == "" || name == "_" {
   176  		return nil // no type docs for anonymous types
   177  	}
   178  	if typ, found := r.types[name]; found {
   179  		return typ
   180  	}
   181  	// type not found - add one without declaration
   182  	typ := &namedType{
   183  		name:     name,
   184  		embedded: make(embeddedSet),
   185  		funcs:    make(methodSet),
   186  		methods:  make(methodSet),
   187  	}
   188  	r.types[name] = typ
   189  	return typ
   190  }
   191  
   192  // recordAnonymousField registers fieldType as the type of an
   193  // anonymous field in the parent type. If the field is imported
   194  // (qualified name) or the parent is nil, the field is ignored.
   195  // The function returns the field name.
   196  //
   197  func (r *reader) recordAnonymousField(parent *namedType, fieldType ast.Expr) (fname string) {
   198  	fname, imp := baseTypeName(fieldType)
   199  	if parent == nil || imp {
   200  		return
   201  	}
   202  	if ftype := r.lookupType(fname); ftype != nil {
   203  		ftype.isEmbedded = true
   204  		_, ptr := fieldType.(*ast.StarExpr)
   205  		parent.embedded[ftype] = ptr
   206  	}
   207  	return
   208  }
   209  
   210  func (r *reader) readDoc(comment *ast.CommentGroup) {
   211  	// By convention there should be only one package comment
   212  	// but collect all of them if there are more than one.
   213  	text := comment.Text()
   214  	if r.doc == "" {
   215  		r.doc = text
   216  		return
   217  	}
   218  	r.doc += "\n" + text
   219  }
   220  
   221  func (r *reader) remember(typ *ast.InterfaceType) {
   222  	r.fixlist = append(r.fixlist, typ)
   223  }
   224  
   225  func specNames(specs []ast.Spec) []string {
   226  	names := make([]string, 0, len(specs)) // reasonable estimate
   227  	for _, s := range specs {
   228  		// s guaranteed to be an *ast.ValueSpec by readValue
   229  		for _, ident := range s.(*ast.ValueSpec).Names {
   230  			names = append(names, ident.Name)
   231  		}
   232  	}
   233  	return names
   234  }
   235  
   236  // readValue processes a const or var declaration.
   237  //
   238  func (r *reader) readValue(decl *ast.GenDecl) {
   239  	// determine if decl should be associated with a type
   240  	// Heuristic: For each typed entry, determine the type name, if any.
   241  	//            If there is exactly one type name that is sufficiently
   242  	//            frequent, associate the decl with the respective type.
   243  	domName := ""
   244  	domFreq := 0
   245  	prev := ""
   246  	n := 0
   247  	for _, spec := range decl.Specs {
   248  		s, ok := spec.(*ast.ValueSpec)
   249  		if !ok {
   250  			continue // should not happen, but be conservative
   251  		}
   252  		name := ""
   253  		switch {
   254  		case s.Type != nil:
   255  			// a type is present; determine its name
   256  			if n, imp := baseTypeName(s.Type); !imp {
   257  				name = n
   258  			}
   259  		case decl.Tok == token.CONST:
   260  			// no type is present but we have a constant declaration;
   261  			// use the previous type name (w/o more type information
   262  			// we cannot handle the case of unnamed variables with
   263  			// initializer expressions except for some trivial cases)
   264  			name = prev
   265  		}
   266  		if name != "" {
   267  			// entry has a named type
   268  			if domName != "" && domName != name {
   269  				// more than one type name - do not associate
   270  				// with any type
   271  				domName = ""
   272  				break
   273  			}
   274  			domName = name
   275  			domFreq++
   276  		}
   277  		prev = name
   278  		n++
   279  	}
   280  
   281  	// nothing to do w/o a legal declaration
   282  	if n == 0 {
   283  		return
   284  	}
   285  
   286  	// determine values list with which to associate the Value for this decl
   287  	values := &r.values
   288  	const threshold = 0.75
   289  	if domName != "" && r.isVisible(domName) && domFreq >= int(float64(len(decl.Specs))*threshold) {
   290  		// typed entries are sufficiently frequent
   291  		if typ := r.lookupType(domName); typ != nil {
   292  			values = &typ.values // associate with that type
   293  		}
   294  	}
   295  
   296  	*values = append(*values, &Value{
   297  		Doc:   decl.Doc.Text(),
   298  		Names: specNames(decl.Specs),
   299  		Decl:  decl,
   300  		order: len(*values),
   301  	})
   302  	decl.Doc = nil // doc consumed - remove from AST
   303  }
   304  
   305  // fields returns a struct's fields or an interface's methods.
   306  //
   307  func fields(typ ast.Expr) (list []*ast.Field, isStruct bool) {
   308  	var fields *ast.FieldList
   309  	switch t := typ.(type) {
   310  	case *ast.StructType:
   311  		fields = t.Fields
   312  		isStruct = true
   313  	case *ast.InterfaceType:
   314  		fields = t.Methods
   315  	}
   316  	if fields != nil {
   317  		list = fields.List
   318  	}
   319  	return
   320  }
   321  
   322  // readType processes a type declaration.
   323  //
   324  func (r *reader) readType(decl *ast.GenDecl, spec *ast.TypeSpec) {
   325  	typ := r.lookupType(spec.Name.Name)
   326  	if typ == nil {
   327  		return // no name or blank name - ignore the type
   328  	}
   329  
   330  	// A type should be added at most once, so typ.decl
   331  	// should be nil - if it is not, simply overwrite it.
   332  	typ.decl = decl
   333  
   334  	// compute documentation
   335  	doc := spec.Doc
   336  	spec.Doc = nil // doc consumed - remove from AST
   337  	if doc == nil {
   338  		// no doc associated with the spec, use the declaration doc, if any
   339  		doc = decl.Doc
   340  	}
   341  	decl.Doc = nil // doc consumed - remove from AST
   342  	typ.doc = doc.Text()
   343  
   344  	// record anonymous fields (they may contribute methods)
   345  	// (some fields may have been recorded already when filtering
   346  	// exports, but that's ok)
   347  	var list []*ast.Field
   348  	list, typ.isStruct = fields(spec.Type)
   349  	for _, field := range list {
   350  		if len(field.Names) == 0 {
   351  			r.recordAnonymousField(typ, field.Type)
   352  		}
   353  	}
   354  }
   355  
   356  // readFunc processes a func or method declaration.
   357  //
   358  func (r *reader) readFunc(fun *ast.FuncDecl) {
   359  	// strip function body
   360  	fun.Body = nil
   361  
   362  	// associate methods with the receiver type, if any
   363  	if fun.Recv != nil {
   364  		// method
   365  		recvTypeName, imp := baseTypeName(fun.Recv.List[0].Type)
   366  		if imp {
   367  			// should not happen (incorrect AST);
   368  			// don't show this method
   369  			return
   370  		}
   371  		if typ := r.lookupType(recvTypeName); typ != nil {
   372  			typ.methods.set(fun)
   373  		}
   374  		// otherwise ignore the method
   375  		// TODO(gri): There may be exported methods of non-exported types
   376  		// that can be called because of exported values (consts, vars, or
   377  		// function results) of that type. Could determine if that is the
   378  		// case and then show those methods in an appropriate section.
   379  		return
   380  	}
   381  
   382  	// associate factory functions with the first visible result type, if any
   383  	if fun.Type.Results.NumFields() >= 1 {
   384  		res := fun.Type.Results.List[0]
   385  		if len(res.Names) <= 1 {
   386  			// exactly one (named or anonymous) result associated
   387  			// with the first type in result signature (there may
   388  			// be more than one result)
   389  			if n, imp := baseTypeName(res.Type); !imp && r.isVisible(n) {
   390  				if typ := r.lookupType(n); typ != nil {
   391  					// associate function with typ
   392  					typ.funcs.set(fun)
   393  					return
   394  				}
   395  			}
   396  		}
   397  	}
   398  
   399  	// just an ordinary function
   400  	r.funcs.set(fun)
   401  }
   402  
   403  var (
   404  	noteMarker    = `([A-Z][A-Z]+)\(([^)]+)\):?`                    // MARKER(uid), MARKER at least 2 chars, uid at least 1 char
   405  	noteMarkerRx  = regexp.MustCompile(`^[ \t]*` + noteMarker)      // MARKER(uid) at text start
   406  	noteCommentRx = regexp.MustCompile(`^/[/*][ \t]*` + noteMarker) // MARKER(uid) at comment start
   407  )
   408  
   409  // readNote collects a single note from a sequence of comments.
   410  //
   411  func (r *reader) readNote(list []*ast.Comment) {
   412  	text := (&ast.CommentGroup{List: list}).Text()
   413  	if m := noteMarkerRx.FindStringSubmatchIndex(text); m != nil {
   414  		// The note body starts after the marker.
   415  		// We remove any formatting so that we don't
   416  		// get spurious line breaks/indentation when
   417  		// showing the TODO body.
   418  		body := clean(text[m[1]:], keepNL)
   419  		if body != "" {
   420  			marker := text[m[2]:m[3]]
   421  			r.notes[marker] = append(r.notes[marker], &Note{
   422  				Pos:  list[0].Pos(),
   423  				End:  list[len(list)-1].End(),
   424  				UID:  text[m[4]:m[5]],
   425  				Body: body,
   426  			})
   427  		}
   428  	}
   429  }
   430  
   431  // readNotes extracts notes from comments.
   432  // A note must start at the beginning of a comment with "MARKER(uid):"
   433  // and is followed by the note body (e.g., "// BUG(gri): fix this").
   434  // The note ends at the end of the comment group or at the start of
   435  // another note in the same comment group, whichever comes first.
   436  //
   437  func (r *reader) readNotes(comments []*ast.CommentGroup) {
   438  	for _, group := range comments {
   439  		i := -1 // comment index of most recent note start, valid if >= 0
   440  		list := group.List
   441  		for j, c := range list {
   442  			if noteCommentRx.MatchString(c.Text) {
   443  				if i >= 0 {
   444  					r.readNote(list[i:j])
   445  				}
   446  				i = j
   447  			}
   448  		}
   449  		if i >= 0 {
   450  			r.readNote(list[i:])
   451  		}
   452  	}
   453  }
   454  
   455  // readFile adds the AST for a source file to the reader.
   456  //
   457  func (r *reader) readFile(src *ast.File) {
   458  	// add package documentation
   459  	if src.Doc != nil {
   460  		r.readDoc(src.Doc)
   461  		src.Doc = nil // doc consumed - remove from AST
   462  	}
   463  
   464  	// add all declarations
   465  	for _, decl := range src.Decls {
   466  		switch d := decl.(type) {
   467  		case *ast.GenDecl:
   468  			switch d.Tok {
   469  			case token.IMPORT:
   470  				// imports are handled individually
   471  				for _, spec := range d.Specs {
   472  					if s, ok := spec.(*ast.ImportSpec); ok {
   473  						if import_, err := strconv.Unquote(s.Path.Value); err == nil {
   474  							r.imports[import_] = 1
   475  							if s.Name != nil && s.Name.Name == "." {
   476  								r.hasDotImp = true
   477  							}
   478  						}
   479  					}
   480  				}
   481  			case token.CONST, token.VAR:
   482  				// constants and variables are always handled as a group
   483  				r.readValue(d)
   484  			case token.TYPE:
   485  				// types are handled individually
   486  				if len(d.Specs) == 1 && !d.Lparen.IsValid() {
   487  					// common case: single declaration w/o parentheses
   488  					// (if a single declaration is parenthesized,
   489  					// create a new fake declaration below, so that
   490  					// go/doc type declarations always appear w/o
   491  					// parentheses)
   492  					if s, ok := d.Specs[0].(*ast.TypeSpec); ok {
   493  						r.readType(d, s)
   494  					}
   495  					break
   496  				}
   497  				for _, spec := range d.Specs {
   498  					if s, ok := spec.(*ast.TypeSpec); ok {
   499  						// use an individual (possibly fake) declaration
   500  						// for each type; this also ensures that each type
   501  						// gets to (re-)use the declaration documentation
   502  						// if there's none associated with the spec itself
   503  						fake := &ast.GenDecl{
   504  							Doc: d.Doc,
   505  							// don't use the existing TokPos because it
   506  							// will lead to the wrong selection range for
   507  							// the fake declaration if there are more
   508  							// than one type in the group (this affects
   509  							// src/cmd/godoc/godoc.go's posLink_urlFunc)
   510  							TokPos: s.Pos(),
   511  							Tok:    token.TYPE,
   512  							Specs:  []ast.Spec{s},
   513  						}
   514  						r.readType(fake, s)
   515  					}
   516  				}
   517  			}
   518  		case *ast.FuncDecl:
   519  			r.readFunc(d)
   520  		}
   521  	}
   522  
   523  	// collect MARKER(...): annotations
   524  	r.readNotes(src.Comments)
   525  	src.Comments = nil // consumed unassociated comments - remove from AST
   526  }
   527  
   528  func (r *reader) readPackage(pkg *ast.Package, mode Mode) {
   529  	// initialize reader
   530  	r.filenames = make([]string, len(pkg.Files))
   531  	r.imports = make(map[string]int)
   532  	r.mode = mode
   533  	r.types = make(map[string]*namedType)
   534  	r.funcs = make(methodSet)
   535  	r.notes = make(map[string][]*Note)
   536  
   537  	// sort package files before reading them so that the
   538  	// result does not depend on map iteration order
   539  	i := 0
   540  	for filename := range pkg.Files {
   541  		r.filenames[i] = filename
   542  		i++
   543  	}
   544  	sort.Strings(r.filenames)
   545  
   546  	// process files in sorted order
   547  	for _, filename := range r.filenames {
   548  		f := pkg.Files[filename]
   549  		if mode&AllDecls == 0 {
   550  			r.fileExports(f)
   551  		}
   552  		r.readFile(f)
   553  	}
   554  }
   555  
   556  // ----------------------------------------------------------------------------
   557  // Types
   558  
   559  func customizeRecv(f *Func, recvTypeName string, embeddedIsPtr bool, level int) *Func {
   560  	if f == nil || f.Decl == nil || f.Decl.Recv == nil || len(f.Decl.Recv.List) != 1 {
   561  		return f // shouldn't happen, but be safe
   562  	}
   563  
   564  	// copy existing receiver field and set new type
   565  	newField := *f.Decl.Recv.List[0]
   566  	origPos := newField.Type.Pos()
   567  	_, origRecvIsPtr := newField.Type.(*ast.StarExpr)
   568  	newIdent := &ast.Ident{NamePos: origPos, Name: recvTypeName}
   569  	var typ ast.Expr = newIdent
   570  	if !embeddedIsPtr && origRecvIsPtr {
   571  		newIdent.NamePos++ // '*' is one character
   572  		typ = &ast.StarExpr{Star: origPos, X: newIdent}
   573  	}
   574  	newField.Type = typ
   575  
   576  	// copy existing receiver field list and set new receiver field
   577  	newFieldList := *f.Decl.Recv
   578  	newFieldList.List = []*ast.Field{&newField}
   579  
   580  	// copy existing function declaration and set new receiver field list
   581  	newFuncDecl := *f.Decl
   582  	newFuncDecl.Recv = &newFieldList
   583  
   584  	// copy existing function documentation and set new declaration
   585  	newF := *f
   586  	newF.Decl = &newFuncDecl
   587  	newF.Recv = recvString(typ)
   588  	// the Orig field never changes
   589  	newF.Level = level
   590  
   591  	return &newF
   592  }
   593  
   594  // collectEmbeddedMethods collects the embedded methods of typ in mset.
   595  //
   596  func (r *reader) collectEmbeddedMethods(mset methodSet, typ *namedType, recvTypeName string, embeddedIsPtr bool, level int, visited embeddedSet) {
   597  	visited[typ] = true
   598  	for embedded, isPtr := range typ.embedded {
   599  		// Once an embedded type is embedded as a pointer type
   600  		// all embedded types in those types are treated like
   601  		// pointer types for the purpose of the receiver type
   602  		// computation; i.e., embeddedIsPtr is sticky for this
   603  		// embedding hierarchy.
   604  		thisEmbeddedIsPtr := embeddedIsPtr || isPtr
   605  		for _, m := range embedded.methods {
   606  			// only top-level methods are embedded
   607  			if m.Level == 0 {
   608  				mset.add(customizeRecv(m, recvTypeName, thisEmbeddedIsPtr, level))
   609  			}
   610  		}
   611  		if !visited[embedded] {
   612  			r.collectEmbeddedMethods(mset, embedded, recvTypeName, thisEmbeddedIsPtr, level+1, visited)
   613  		}
   614  	}
   615  	delete(visited, typ)
   616  }
   617  
   618  // computeMethodSets determines the actual method sets for each type encountered.
   619  //
   620  func (r *reader) computeMethodSets() {
   621  	for _, t := range r.types {
   622  		// collect embedded methods for t
   623  		if t.isStruct {
   624  			// struct
   625  			r.collectEmbeddedMethods(t.methods, t, t.name, false, 1, make(embeddedSet))
   626  		} else {
   627  			// interface
   628  			// TODO(gri) fix this
   629  		}
   630  	}
   631  
   632  	// if error was declared locally, don't treat it as exported field anymore
   633  	if r.errorDecl {
   634  		for _, ityp := range r.fixlist {
   635  			removeErrorField(ityp)
   636  		}
   637  	}
   638  }
   639  
   640  // cleanupTypes removes the association of functions and methods with
   641  // types that have no declaration. Instead, these functions and methods
   642  // are shown at the package level. It also removes types with missing
   643  // declarations or which are not visible.
   644  //
   645  func (r *reader) cleanupTypes() {
   646  	for _, t := range r.types {
   647  		visible := r.isVisible(t.name)
   648  		if t.decl == nil && (predeclaredTypes[t.name] || visible && (t.isEmbedded || r.hasDotImp)) {
   649  			// t.name is a predeclared type (and was not redeclared in this package),
   650  			// or it was embedded somewhere but its declaration is missing (because
   651  			// the AST is incomplete), or we have a dot-import (and all bets are off):
   652  			// move any associated values, funcs, and methods back to the top-level so
   653  			// that they are not lost.
   654  			// 1) move values
   655  			r.values = append(r.values, t.values...)
   656  			// 2) move factory functions
   657  			for name, f := range t.funcs {
   658  				// in a correct AST, package-level function names
   659  				// are all different - no need to check for conflicts
   660  				r.funcs[name] = f
   661  			}
   662  			// 3) move methods
   663  			for name, m := range t.methods {
   664  				// don't overwrite functions with the same name - drop them
   665  				if _, found := r.funcs[name]; !found {
   666  					r.funcs[name] = m
   667  				}
   668  			}
   669  		}
   670  		// remove types w/o declaration or which are not visible
   671  		if t.decl == nil || !visible {
   672  			delete(r.types, t.name)
   673  		}
   674  	}
   675  }
   676  
   677  // ----------------------------------------------------------------------------
   678  // Sorting
   679  
   680  type data struct {
   681  	n    int
   682  	swap func(i, j int)
   683  	less func(i, j int) bool
   684  }
   685  
   686  func (d *data) Len() int           { return d.n }
   687  func (d *data) Swap(i, j int)      { d.swap(i, j) }
   688  func (d *data) Less(i, j int) bool { return d.less(i, j) }
   689  
   690  // sortBy is a helper function for sorting
   691  func sortBy(less func(i, j int) bool, swap func(i, j int), n int) {
   692  	sort.Sort(&data{n, swap, less})
   693  }
   694  
   695  func sortedKeys(m map[string]int) []string {
   696  	list := make([]string, len(m))
   697  	i := 0
   698  	for key := range m {
   699  		list[i] = key
   700  		i++
   701  	}
   702  	sort.Strings(list)
   703  	return list
   704  }
   705  
   706  // sortingName returns the name to use when sorting d into place.
   707  //
   708  func sortingName(d *ast.GenDecl) string {
   709  	if len(d.Specs) == 1 {
   710  		if s, ok := d.Specs[0].(*ast.ValueSpec); ok {
   711  			return s.Names[0].Name
   712  		}
   713  	}
   714  	return ""
   715  }
   716  
   717  func sortedValues(m []*Value, tok token.Token) []*Value {
   718  	list := make([]*Value, len(m)) // big enough in any case
   719  	i := 0
   720  	for _, val := range m {
   721  		if val.Decl.Tok == tok {
   722  			list[i] = val
   723  			i++
   724  		}
   725  	}
   726  	list = list[0:i]
   727  
   728  	sortBy(
   729  		func(i, j int) bool {
   730  			if ni, nj := sortingName(list[i].Decl), sortingName(list[j].Decl); ni != nj {
   731  				return ni < nj
   732  			}
   733  			return list[i].order < list[j].order
   734  		},
   735  		func(i, j int) { list[i], list[j] = list[j], list[i] },
   736  		len(list),
   737  	)
   738  
   739  	return list
   740  }
   741  
   742  func sortedTypes(m map[string]*namedType, allMethods bool) []*Type {
   743  	list := make([]*Type, len(m))
   744  	i := 0
   745  	for _, t := range m {
   746  		list[i] = &Type{
   747  			Doc:     t.doc,
   748  			Name:    t.name,
   749  			Decl:    t.decl,
   750  			Consts:  sortedValues(t.values, token.CONST),
   751  			Vars:    sortedValues(t.values, token.VAR),
   752  			Funcs:   sortedFuncs(t.funcs, true),
   753  			Methods: sortedFuncs(t.methods, allMethods),
   754  		}
   755  		i++
   756  	}
   757  
   758  	sortBy(
   759  		func(i, j int) bool { return list[i].Name < list[j].Name },
   760  		func(i, j int) { list[i], list[j] = list[j], list[i] },
   761  		len(list),
   762  	)
   763  
   764  	return list
   765  }
   766  
   767  func removeStar(s string) string {
   768  	if len(s) > 0 && s[0] == '*' {
   769  		return s[1:]
   770  	}
   771  	return s
   772  }
   773  
   774  func sortedFuncs(m methodSet, allMethods bool) []*Func {
   775  	list := make([]*Func, len(m))
   776  	i := 0
   777  	for _, m := range m {
   778  		// determine which methods to include
   779  		switch {
   780  		case m.Decl == nil:
   781  			// exclude conflict entry
   782  		case allMethods, m.Level == 0, !ast.IsExported(removeStar(m.Orig)):
   783  			// forced inclusion, method not embedded, or method
   784  			// embedded but original receiver type not exported
   785  			list[i] = m
   786  			i++
   787  		}
   788  	}
   789  	list = list[0:i]
   790  	sortBy(
   791  		func(i, j int) bool { return list[i].Name < list[j].Name },
   792  		func(i, j int) { list[i], list[j] = list[j], list[i] },
   793  		len(list),
   794  	)
   795  	return list
   796  }
   797  
   798  // noteBodies returns a list of note body strings given a list of notes.
   799  // This is only used to populate the deprecated Package.Bugs field.
   800  //
   801  func noteBodies(notes []*Note) []string {
   802  	var list []string
   803  	for _, n := range notes {
   804  		list = append(list, n.Body)
   805  	}
   806  	return list
   807  }
   808  
   809  // ----------------------------------------------------------------------------
   810  // Predeclared identifiers
   811  
   812  var predeclaredTypes = map[string]bool{
   813  	"bool":       true,
   814  	"byte":       true,
   815  	"complex64":  true,
   816  	"complex128": true,
   817  	"error":      true,
   818  	"float32":    true,
   819  	"float64":    true,
   820  	"int":        true,
   821  	"int8":       true,
   822  	"int16":      true,
   823  	"int32":      true,
   824  	"int64":      true,
   825  	"rune":       true,
   826  	"string":     true,
   827  	"uint":       true,
   828  	"uint8":      true,
   829  	"uint16":     true,
   830  	"uint32":     true,
   831  	"uint64":     true,
   832  	"uintptr":    true,
   833  }
   834  
   835  var predeclaredFuncs = map[string]bool{
   836  	"append":  true,
   837  	"cap":     true,
   838  	"close":   true,
   839  	"complex": true,
   840  	"copy":    true,
   841  	"delete":  true,
   842  	"imag":    true,
   843  	"len":     true,
   844  	"make":    true,
   845  	"new":     true,
   846  	"panic":   true,
   847  	"print":   true,
   848  	"println": true,
   849  	"real":    true,
   850  	"recover": true,
   851  }
   852  
   853  var predeclaredConstants = map[string]bool{
   854  	"false": true,
   855  	"iota":  true,
   856  	"nil":   true,
   857  	"true":  true,
   858  }