Source file 
src/go/types/signature.go
     1  
     2  
     3  
     4  
     5  package types
     6  
     7  import (
     8  	"fmt"
     9  	"go/ast"
    10  	"go/token"
    11  	. "internal/types/errors"
    12  	"path/filepath"
    13  	"strings"
    14  )
    15  
    16  
    17  
    18  
    19  
    20  
    21  type Signature struct {
    22  	
    23  	
    24  	
    25  	
    26  	rparams  *TypeParamList 
    27  	tparams  *TypeParamList 
    28  	scope    *Scope         
    29  	recv     *Var           
    30  	params   *Tuple         
    31  	results  *Tuple         
    32  	variadic bool           
    33  }
    34  
    35  
    36  
    37  
    38  
    39  
    40  
    41  
    42  
    43  func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
    44  	return NewSignatureType(recv, nil, nil, params, results, variadic)
    45  }
    46  
    47  
    48  
    49  
    50  
    51  
    52  
    53  
    54  
    55  
    56  
    57  func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
    58  	if variadic {
    59  		n := params.Len()
    60  		if n == 0 {
    61  			panic("variadic function must have at least one parameter")
    62  		}
    63  		last := params.At(n - 1).typ
    64  		var S *Slice
    65  		for t := range typeset(last) {
    66  			var s *Slice
    67  			if isString(t) {
    68  				s = NewSlice(universeByte)
    69  			} else {
    70  				s, _ = Unalias(t).(*Slice) 
    71  			}
    72  			if S == nil {
    73  				S = s
    74  			} else if !Identical(S, s) {
    75  				S = nil
    76  				break
    77  			}
    78  		}
    79  		if S == nil {
    80  			panic(fmt.Sprintf("got %s, want variadic parameter of unnamed slice or string type", last))
    81  		}
    82  	}
    83  	sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
    84  	if len(recvTypeParams) != 0 {
    85  		if recv == nil {
    86  			panic("function with receiver type parameters must have a receiver")
    87  		}
    88  		sig.rparams = bindTParams(recvTypeParams)
    89  	}
    90  	if len(typeParams) != 0 {
    91  		if recv != nil {
    92  			panic("function with type parameters cannot have a receiver")
    93  		}
    94  		sig.tparams = bindTParams(typeParams)
    95  	}
    96  	return sig
    97  }
    98  
    99  
   100  
   101  
   102  
   103  
   104  
   105  func (s *Signature) Recv() *Var { return s.recv }
   106  
   107  
   108  func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
   109  
   110  
   111  func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
   112  
   113  
   114  func (s *Signature) Params() *Tuple { return s.params }
   115  
   116  
   117  func (s *Signature) Results() *Tuple { return s.results }
   118  
   119  
   120  func (s *Signature) Variadic() bool { return s.variadic }
   121  
   122  func (s *Signature) Underlying() Type { return s }
   123  func (s *Signature) String() string   { return TypeString(s, nil) }
   124  
   125  
   126  
   127  
   128  
   129  func (check *Checker) funcType(sig *Signature, recvPar *ast.FieldList, ftyp *ast.FuncType) {
   130  	check.openScope(ftyp, "function")
   131  	check.scope.isFunc = true
   132  	check.recordScope(ftyp, check.scope)
   133  	sig.scope = check.scope
   134  	defer check.closeScope()
   135  
   136  	
   137  	var recv *Var
   138  	var rparams *TypeParamList
   139  	if recvPar != nil && recvPar.NumFields() > 0 {
   140  		
   141  		if n := len(recvPar.List); n > 1 {
   142  			check.error(recvPar.List[n-1], InvalidRecv, "method has multiple receivers")
   143  			
   144  		}
   145  		
   146  		scopePos := ftyp.Pos()
   147  		recv, rparams = check.collectRecv(recvPar.List[0], scopePos)
   148  	}
   149  
   150  	
   151  	if ftyp.TypeParams != nil {
   152  		
   153  		
   154  		
   155  		if recvPar != nil {
   156  			check.error(ftyp.TypeParams, InvalidMethodTypeParams, "methods cannot have type parameters")
   157  		}
   158  		check.collectTypeParams(&sig.tparams, ftyp.TypeParams)
   159  	}
   160  
   161  	
   162  	pnames, params, variadic := check.collectParams(ParamVar, ftyp.Params)
   163  	rnames, results, _ := check.collectParams(ResultVar, ftyp.Results)
   164  
   165  	
   166  	scopePos := ftyp.End() 
   167  	if recv != nil && recv.name != "" {
   168  		check.declare(check.scope, recvPar.List[0].Names[0], recv, scopePos)
   169  	}
   170  	check.declareParams(pnames, params, scopePos)
   171  	check.declareParams(rnames, results, scopePos)
   172  
   173  	sig.recv = recv
   174  	sig.rparams = rparams
   175  	sig.params = NewTuple(params...)
   176  	sig.results = NewTuple(results...)
   177  	sig.variadic = variadic
   178  }
   179  
   180  
   181  
   182  
   183  func (check *Checker) collectRecv(rparam *ast.Field, scopePos token.Pos) (*Var, *TypeParamList) {
   184  	
   185  	
   186  	
   187  	
   188  	
   189  	
   190  	rptr, rbase, rtparams := check.unpackRecv(rparam.Type, true)
   191  
   192  	
   193  	var recvType Type = Typ[Invalid]
   194  	var recvTParamsList *TypeParamList
   195  	if rtparams == nil {
   196  		
   197  		
   198  		
   199  		
   200  		
   201  		recvType = check.varType(rparam.Type)
   202  		
   203  		
   204  		
   205  		
   206  		a, _ := unpointer(recvType).(*Alias) 
   207  		for a != nil {
   208  			baseType := unpointer(a.fromRHS)
   209  			if g, _ := baseType.(genericType); g != nil && g.TypeParams() != nil {
   210  				check.errorf(rbase, InvalidRecv, "cannot define new methods on instantiated type %s", g)
   211  				recvType = Typ[Invalid] 
   212  				break
   213  			}
   214  			a, _ = baseType.(*Alias)
   215  		}
   216  	} else {
   217  		
   218  		
   219  		
   220  		var baseType *Named 
   221  		var cause string
   222  		if t := check.genericType(rbase, &cause); isValid(t) {
   223  			switch t := t.(type) {
   224  			case *Named:
   225  				baseType = t
   226  			case *Alias:
   227  				
   228  				
   229  				if isValid(t) {
   230  					check.errorf(rbase, InvalidRecv, "cannot define new methods on generic alias type %s", t)
   231  				}
   232  				
   233  				
   234  			default:
   235  				panic("unreachable")
   236  			}
   237  		} else {
   238  			if cause != "" {
   239  				check.errorf(rbase, InvalidRecv, "%s", cause)
   240  			}
   241  			
   242  		}
   243  
   244  		
   245  		
   246  		
   247  		
   248  		recvTParams := make([]*TypeParam, len(rtparams))
   249  		for i, rparam := range rtparams {
   250  			tpar := check.declareTypeParam(rparam, scopePos)
   251  			recvTParams[i] = tpar
   252  			
   253  			
   254  			
   255  			check.recordUse(rparam, tpar.obj)
   256  			check.recordTypeAndValue(rparam, typexpr, tpar, nil)
   257  		}
   258  		recvTParamsList = bindTParams(recvTParams)
   259  
   260  		
   261  		
   262  		if baseType != nil {
   263  			baseTParams := baseType.TypeParams().list()
   264  			if len(recvTParams) == len(baseTParams) {
   265  				smap := makeRenameMap(baseTParams, recvTParams)
   266  				for i, recvTPar := range recvTParams {
   267  					baseTPar := baseTParams[i]
   268  					check.mono.recordCanon(recvTPar, baseTPar)
   269  					
   270  					
   271  					
   272  					recvTPar.bound = check.subst(recvTPar.obj.pos, baseTPar.bound, smap, nil, check.context())
   273  				}
   274  			} else {
   275  				got := measure(len(recvTParams), "type parameter")
   276  				check.errorf(rbase, BadRecv, "receiver declares %s, but receiver base type declares %d", got, len(baseTParams))
   277  			}
   278  
   279  			
   280  			
   281  			check.verifyVersionf(rbase, go1_18, "type instantiation")
   282  			targs := make([]Type, len(recvTParams))
   283  			for i, targ := range recvTParams {
   284  				targs[i] = targ
   285  			}
   286  			recvType = check.instance(rparam.Type.Pos(), baseType, targs, nil, check.context())
   287  			check.recordInstance(rbase, targs, recvType)
   288  
   289  			
   290  			if rptr && isValid(recvType) {
   291  				recvType = NewPointer(recvType)
   292  			}
   293  
   294  			check.recordParenthesizedRecvTypes(rparam.Type, recvType)
   295  		}
   296  	}
   297  
   298  	
   299  	var rname *ast.Ident
   300  	if n := len(rparam.Names); n >= 1 {
   301  		if n > 1 {
   302  			check.error(rparam.Names[n-1], InvalidRecv, "method has multiple receivers")
   303  		}
   304  		rname = rparam.Names[0]
   305  	}
   306  
   307  	
   308  	
   309  	var recv *Var
   310  	if rname != nil && rname.Name != "" {
   311  		
   312  		recv = newVar(RecvVar, rname.Pos(), check.pkg, rname.Name, recvType)
   313  		
   314  		
   315  		
   316  	} else {
   317  		
   318  		recv = newVar(RecvVar, rparam.Pos(), check.pkg, "", recvType)
   319  		check.recordImplicit(rparam, recv)
   320  	}
   321  
   322  	
   323  	
   324  	check.later(func() {
   325  		check.validRecv(rbase, recv)
   326  	}).describef(recv, "validRecv(%s)", recv)
   327  
   328  	return recv, recvTParamsList
   329  }
   330  
   331  func unpointer(t Type) Type {
   332  	for {
   333  		p, _ := t.(*Pointer)
   334  		if p == nil {
   335  			return t
   336  		}
   337  		t = p.base
   338  	}
   339  }
   340  
   341  
   342  
   343  
   344  
   345  
   346  
   347  
   348  
   349  
   350  
   351  func (check *Checker) recordParenthesizedRecvTypes(expr ast.Expr, typ Type) {
   352  	for {
   353  		check.recordTypeAndValue(expr, typexpr, typ, nil)
   354  		switch e := expr.(type) {
   355  		case *ast.ParenExpr:
   356  			expr = e.X
   357  		case *ast.StarExpr:
   358  			expr = e.X
   359  			
   360  			
   361  			ptr, _ := typ.(*Pointer)
   362  			if ptr == nil {
   363  				return 
   364  			}
   365  			typ = ptr.base
   366  		default:
   367  			return 
   368  		}
   369  	}
   370  }
   371  
   372  
   373  
   374  
   375  
   376  func (check *Checker) collectParams(kind VarKind, list *ast.FieldList) (names []*ast.Ident, params []*Var, variadic bool) {
   377  	if list == nil {
   378  		return
   379  	}
   380  
   381  	var named, anonymous bool
   382  	for i, field := range list.List {
   383  		ftype := field.Type
   384  		if t, _ := ftype.(*ast.Ellipsis); t != nil {
   385  			ftype = t.Elt
   386  			if kind == ParamVar && i == len(list.List)-1 && len(field.Names) <= 1 {
   387  				variadic = true
   388  			} else {
   389  				check.softErrorf(t, InvalidSyntaxTree, "invalid use of ...")
   390  				
   391  			}
   392  		}
   393  		typ := check.varType(ftype)
   394  		
   395  		
   396  		if len(field.Names) > 0 {
   397  			
   398  			for _, name := range field.Names {
   399  				if name.Name == "" {
   400  					check.error(name, InvalidSyntaxTree, "anonymous parameter")
   401  					
   402  				}
   403  				par := newVar(kind, name.Pos(), check.pkg, name.Name, typ)
   404  				
   405  				names = append(names, name)
   406  				params = append(params, par)
   407  			}
   408  			named = true
   409  		} else {
   410  			
   411  			par := newVar(kind, ftype.Pos(), check.pkg, "", typ)
   412  			check.recordImplicit(field, par)
   413  			names = append(names, nil)
   414  			params = append(params, par)
   415  			anonymous = true
   416  		}
   417  	}
   418  
   419  	if named && anonymous {
   420  		check.error(list, InvalidSyntaxTree, "list contains both named and anonymous parameters")
   421  		
   422  	}
   423  
   424  	
   425  	
   426  	
   427  	if variadic {
   428  		last := params[len(params)-1]
   429  		last.typ = &Slice{elem: last.typ}
   430  		check.recordTypeAndValue(list.List[len(list.List)-1].Type, typexpr, last.typ, nil)
   431  	}
   432  
   433  	return
   434  }
   435  
   436  
   437  func (check *Checker) declareParams(names []*ast.Ident, params []*Var, scopePos token.Pos) {
   438  	for i, name := range names {
   439  		if name != nil && name.Name != "" {
   440  			check.declare(check.scope, name, params[i], scopePos)
   441  		}
   442  	}
   443  }
   444  
   445  
   446  
   447  func (check *Checker) validRecv(pos positioner, recv *Var) {
   448  	
   449  	rtyp, _ := deref(recv.typ)
   450  	atyp := Unalias(rtyp)
   451  	if !isValid(atyp) {
   452  		return 
   453  	}
   454  	
   455  	
   456  	
   457  	switch T := atyp.(type) {
   458  	case *Named:
   459  		if T.obj.pkg != check.pkg || isCGoTypeObj(check.fset, T.obj) {
   460  			check.errorf(pos, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
   461  			break
   462  		}
   463  		var cause string
   464  		switch u := T.Underlying().(type) {
   465  		case *Basic:
   466  			
   467  			if u.kind == UnsafePointer {
   468  				cause = "unsafe.Pointer"
   469  			}
   470  		case *Pointer, *Interface:
   471  			cause = "pointer or interface type"
   472  		case *TypeParam:
   473  			
   474  			
   475  			panic("unreachable")
   476  		}
   477  		if cause != "" {
   478  			check.errorf(pos, InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause)
   479  		}
   480  	case *Basic:
   481  		check.errorf(pos, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
   482  	default:
   483  		check.errorf(pos, InvalidRecv, "invalid receiver type %s", recv.typ)
   484  	}
   485  }
   486  
   487  
   488  func isCGoTypeObj(fset *token.FileSet, obj *TypeName) bool {
   489  	return strings.HasPrefix(obj.name, "_Ctype_") ||
   490  		strings.HasPrefix(filepath.Base(fset.File(obj.pos).Name()), "_cgo_")
   491  }
   492  
View as plain text