...

Source file src/cmd/compile/internal/types2/compiler_internal.go

Documentation: cmd/compile/internal/types2

     1  // Copyright 2024 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 types2
     6  
     7  import (
     8  	"cmd/compile/internal/syntax"
     9  	"fmt"
    10  )
    11  
    12  // This file should not be copied to go/types.  See go.dev/issue/67477
    13  
    14  // RenameResult takes an array of (result) fields and an index, and if the indexed field
    15  // does not have a name and if the result in the signature also does not have a name,
    16  // then the signature and field are renamed to
    17  //
    18  //	fmt.Sprintf("#rv%d", i+1)`
    19  //
    20  // the newly named object is inserted into the signature's scope,
    21  // and the object and new field name are returned.
    22  //
    23  // The intended use for RenameResult is to allow rangefunc to assign results within a closure.
    24  // This is a hack, as narrowly targeted as possible to discourage abuse.
    25  func (s *Signature) RenameResult(results []*syntax.Field, i int) (*Var, *syntax.Name) {
    26  	a := results[i]
    27  	obj := s.Results().At(i)
    28  
    29  	if !(obj.name == "" || obj.name == "_" && a.Name == nil || a.Name.Value == "_") {
    30  		panic("Cannot change an existing name")
    31  	}
    32  
    33  	pos := a.Pos()
    34  	typ := a.Type.GetTypeInfo().Type
    35  
    36  	name := fmt.Sprintf("#rv%d", i+1)
    37  	obj.name = name
    38  	s.scope.Insert(obj)
    39  	obj.setScopePos(pos)
    40  
    41  	tv := syntax.TypeAndValue{Type: typ}
    42  	tv.SetIsValue()
    43  
    44  	n := syntax.NewName(pos, obj.Name())
    45  	n.SetTypeInfo(tv)
    46  
    47  	a.Name = n
    48  
    49  	return obj, n
    50  }
    51  

View as plain text