Source file src/go/types/methodset.go

     1  // Copyright 2013 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  // This file implements method sets.
     6  
     7  package types
     8  
     9  import (
    10  	"fmt"
    11  	"sort"
    12  	"strings"
    13  )
    14  
    15  // A MethodSet is an ordered set of concrete or abstract (interface) methods;
    16  // a method is a MethodVal selection, and they are ordered by ascending m.Obj().Id().
    17  // The zero value for a MethodSet is a ready-to-use empty method set.
    18  type MethodSet struct {
    19  	list []*Selection
    20  }
    21  
    22  func (s *MethodSet) String() string {
    23  	if s.Len() == 0 {
    24  		return "MethodSet {}"
    25  	}
    26  
    27  	var buf strings.Builder
    28  	fmt.Fprintln(&buf, "MethodSet {")
    29  	for _, f := range s.list {
    30  		fmt.Fprintf(&buf, "\t%s\n", f)
    31  	}
    32  	fmt.Fprintln(&buf, "}")
    33  	return buf.String()
    34  }
    35  
    36  // Len returns the number of methods in s.
    37  func (s *MethodSet) Len() int { return len(s.list) }
    38  
    39  // At returns the i'th method in s for 0 <= i < s.Len().
    40  func (s *MethodSet) At(i int) *Selection { return s.list[i] }
    41  
    42  // Lookup returns the method with matching package and name, or nil if not found.
    43  func (s *MethodSet) Lookup(pkg *Package, name string) *Selection {
    44  	if s.Len() == 0 {
    45  		return nil
    46  	}
    47  
    48  	key := Id(pkg, name)
    49  	i := sort.Search(len(s.list), func(i int) bool {
    50  		m := s.list[i]
    51  		return m.obj.Id() >= key
    52  	})
    53  	if i < len(s.list) {
    54  		m := s.list[i]
    55  		if m.obj.Id() == key {
    56  			return m
    57  		}
    58  	}
    59  	return nil
    60  }
    61  
    62  // Shared empty method set.
    63  var emptyMethodSet MethodSet
    64  
    65  // Note: NewMethodSet is intended for external use only as it
    66  //       requires interfaces to be complete. It may be used
    67  //       internally if LookupFieldOrMethod completed the same
    68  //       interfaces beforehand.
    69  
    70  // NewMethodSet returns the method set for the given type T.
    71  // It always returns a non-nil method set, even if it is empty.
    72  func NewMethodSet(T Type) *MethodSet {
    73  	// WARNING: The code in this function is extremely subtle - do not modify casually!
    74  	//          This function and lookupFieldOrMethod should be kept in sync.
    75  
    76  	// TODO(rfindley) confirm that this code is in sync with lookupFieldOrMethod
    77  	//                with respect to type params.
    78  
    79  	// method set up to the current depth, allocated lazily
    80  	var base methodSet
    81  
    82  	typ, isPtr := deref(T)
    83  
    84  	// *typ where typ is an interface has no methods.
    85  	if isPtr && IsInterface(typ) {
    86  		return &emptyMethodSet
    87  	}
    88  
    89  	// Start with typ as single entry at shallowest depth.
    90  	current := []embeddedType{{typ, nil, isPtr, false}}
    91  
    92  	// seen tracks named types that we have seen already, allocated lazily.
    93  	// Used to avoid endless searches in case of recursive types.
    94  	//
    95  	// We must use a lookup on identity rather than a simple map[*Named]bool as
    96  	// instantiated types may be identical but not equal.
    97  	var seen instanceLookup
    98  
    99  	// collect methods at current depth
   100  	for len(current) > 0 {
   101  		var next []embeddedType // embedded types found at current depth
   102  
   103  		// field and method sets at current depth, indexed by names (Id's), and allocated lazily
   104  		var fset map[string]bool // we only care about the field names
   105  		var mset methodSet
   106  
   107  		for _, e := range current {
   108  			typ := e.typ
   109  
   110  			// If we have a named type, we may have associated methods.
   111  			// Look for those first.
   112  			if named, _ := typ.(*Named); named != nil {
   113  				if alt := seen.lookup(named); alt != nil {
   114  					// We have seen this type before, at a more shallow depth
   115  					// (note that multiples of this type at the current depth
   116  					// were consolidated before). The type at that depth shadows
   117  					// this same type at the current depth, so we can ignore
   118  					// this one.
   119  					continue
   120  				}
   121  				seen.add(named)
   122  
   123  				for i := 0; i < named.NumMethods(); i++ {
   124  					mset = mset.addOne(named.Method(i), concat(e.index, i), e.indirect, e.multiples)
   125  				}
   126  			}
   127  
   128  			switch t := under(typ).(type) {
   129  			case *Struct:
   130  				for i, f := range t.fields {
   131  					if fset == nil {
   132  						fset = make(map[string]bool)
   133  					}
   134  					fset[f.Id()] = true
   135  
   136  					// Embedded fields are always of the form T or *T where
   137  					// T is a type name. If typ appeared multiple times at
   138  					// this depth, f.Type appears multiple times at the next
   139  					// depth.
   140  					if f.embedded {
   141  						typ, isPtr := deref(f.typ)
   142  						// TODO(gri) optimization: ignore types that can't
   143  						// have fields or methods (only Named, Struct, and
   144  						// Interface types need to be considered).
   145  						next = append(next, embeddedType{typ, concat(e.index, i), e.indirect || isPtr, e.multiples})
   146  					}
   147  				}
   148  
   149  			case *Interface:
   150  				mset = mset.add(t.typeSet().methods, e.index, true, e.multiples)
   151  			}
   152  		}
   153  
   154  		// Add methods and collisions at this depth to base if no entries with matching
   155  		// names exist already.
   156  		for k, m := range mset {
   157  			if _, found := base[k]; !found {
   158  				// Fields collide with methods of the same name at this depth.
   159  				if fset[k] {
   160  					m = nil // collision
   161  				}
   162  				if base == nil {
   163  					base = make(methodSet)
   164  				}
   165  				base[k] = m
   166  			}
   167  		}
   168  
   169  		// Add all (remaining) fields at this depth as collisions (since they will
   170  		// hide any method further down) if no entries with matching names exist already.
   171  		for k := range fset {
   172  			if _, found := base[k]; !found {
   173  				if base == nil {
   174  					base = make(methodSet)
   175  				}
   176  				base[k] = nil // collision
   177  			}
   178  		}
   179  
   180  		current = consolidateMultiples(next)
   181  	}
   182  
   183  	if len(base) == 0 {
   184  		return &emptyMethodSet
   185  	}
   186  
   187  	// collect methods
   188  	var list []*Selection
   189  	for _, m := range base {
   190  		if m != nil {
   191  			m.recv = T
   192  			list = append(list, m)
   193  		}
   194  	}
   195  	// sort by unique name
   196  	sort.Slice(list, func(i, j int) bool {
   197  		return list[i].obj.Id() < list[j].obj.Id()
   198  	})
   199  	return &MethodSet{list}
   200  }
   201  
   202  // A methodSet is a set of methods and name collisions.
   203  // A collision indicates that multiple methods with the
   204  // same unique id, or a field with that id appeared.
   205  type methodSet map[string]*Selection // a nil entry indicates a name collision
   206  
   207  // Add adds all functions in list to the method set s.
   208  // If multiples is set, every function in list appears multiple times
   209  // and is treated as a collision.
   210  func (s methodSet) add(list []*Func, index []int, indirect bool, multiples bool) methodSet {
   211  	if len(list) == 0 {
   212  		return s
   213  	}
   214  	for i, f := range list {
   215  		s = s.addOne(f, concat(index, i), indirect, multiples)
   216  	}
   217  	return s
   218  }
   219  
   220  func (s methodSet) addOne(f *Func, index []int, indirect bool, multiples bool) methodSet {
   221  	if s == nil {
   222  		s = make(methodSet)
   223  	}
   224  	key := f.Id()
   225  	// if f is not in the set, add it
   226  	if !multiples {
   227  		// TODO(gri) A found method may not be added because it's not in the method set
   228  		// (!indirect && f.hasPtrRecv()). A 2nd method on the same level may be in the method
   229  		// set and may not collide with the first one, thus leading to a false positive.
   230  		// Is that possible? Investigate.
   231  		if _, found := s[key]; !found && (indirect || !f.hasPtrRecv()) {
   232  			s[key] = &Selection{MethodVal, nil, f, index, indirect}
   233  			return s
   234  		}
   235  	}
   236  	s[key] = nil // collision
   237  	return s
   238  }
   239  

View as plain text