]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/cmd/compile/internal/types2/typestring.go
go/types, types2: introduce _Alias type node
[gostls13.git] / src / cmd / compile / internal / types2 / typestring.go
index 3b9981089e178f48cce1f29cf4c6228e706c74f2..3c2150273ee85c54276cea8d1af37c9b710afb35 100644 (file)
@@ -9,6 +9,9 @@ package types2
 import (
        "bytes"
        "fmt"
+       "sort"
+       "strconv"
+       "strings"
        "unicode/utf8"
 )
 
@@ -22,7 +25,6 @@ import (
 //
 // Using a nil Qualifier is equivalent to using (*Package).Path: the
 // object is qualified by the import path, e.g., "encoding/json.Marshal".
-//
 type Qualifier func(*Package) string
 
 // RelativeTo returns a Qualifier that fully qualifies members of
@@ -55,26 +57,61 @@ func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier) {
        newTypeWriter(buf, qf).typ(typ)
 }
 
-// instanceMarker is the prefix for an instantiated type in unexpanded form.
-const instanceMarker = '#'
+// WriteSignature writes the representation of the signature sig to buf,
+// without a leading "func" keyword. The Qualifier controls the printing
+// of package-level objects, and may be nil.
+func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
+       newTypeWriter(buf, qf).signature(sig)
+}
 
 type typeWriter struct {
-       buf  *bytes.Buffer
-       seen map[Type]bool
-       qf   Qualifier
+       buf          *bytes.Buffer
+       seen         map[Type]bool
+       qf           Qualifier
+       ctxt         *Context       // if non-nil, we are type hashing
+       tparams      *TypeParamList // local type parameters
+       paramNames   bool           // if set, write function parameter names, otherwise, write types only
+       tpSubscripts bool           // if set, write type parameter indices as subscripts
+       pkgInfo      bool           // package-annotate first unexported-type field to avoid confusing type description
 }
 
 func newTypeWriter(buf *bytes.Buffer, qf Qualifier) *typeWriter {
-       return &typeWriter{buf, make(map[Type]bool), qf}
+       return &typeWriter{buf, make(map[Type]bool), qf, nil, nil, true, false, false}
 }
 
-func (w *typeWriter) byte(b byte)                               { w.buf.WriteByte(b) }
-func (w *typeWriter) string(s string)                           { w.buf.WriteString(s) }
-func (w *typeWriter) writef(format string, args ...interface{}) { fmt.Fprintf(w.buf, format, args...) }
+func newTypeHasher(buf *bytes.Buffer, ctxt *Context) *typeWriter {
+       assert(ctxt != nil)
+       return &typeWriter{buf, make(map[Type]bool), nil, ctxt, nil, false, false, false}
+}
+
+func (w *typeWriter) byte(b byte) {
+       if w.ctxt != nil {
+               if b == ' ' {
+                       b = '#'
+               }
+               w.buf.WriteByte(b)
+               return
+       }
+       w.buf.WriteByte(b)
+       if b == ',' || b == ';' {
+               w.buf.WriteByte(' ')
+       }
+}
+
+func (w *typeWriter) string(s string) {
+       w.buf.WriteString(s)
+}
+
+func (w *typeWriter) error(msg string) {
+       if w.ctxt != nil {
+               panic(msg)
+       }
+       w.buf.WriteString("<" + msg + ">")
+}
 
 func (w *typeWriter) typ(typ Type) {
        if w.seen[typ] {
-               w.writef("○%T", goTypeName(typ)) // cycle to typ
+               w.error("cycle to " + goTypeName(typ))
                return
        }
        w.seen[typ] = true
@@ -82,7 +119,7 @@ func (w *typeWriter) typ(typ Type) {
 
        switch t := typ.(type) {
        case nil:
-               w.string("<nil>")
+               w.error("nil")
 
        case *Basic:
                // exported basic types go into package unsafe
@@ -96,7 +133,9 @@ func (w *typeWriter) typ(typ Type) {
                w.string(t.name)
 
        case *Array:
-               w.writef("[%d]", t.len)
+               w.byte('[')
+               w.string(strconv.FormatInt(t.len, 10))
+               w.byte(']')
                w.typ(t.elem)
 
        case *Slice:
@@ -107,18 +146,37 @@ func (w *typeWriter) typ(typ Type) {
                w.string("struct{")
                for i, f := range t.fields {
                        if i > 0 {
-                               w.string("; ")
+                               w.byte(';')
+                       }
+
+                       // If disambiguating one struct for another, look for the first unexported field.
+                       // Do this first in case of nested structs; tag the first-outermost field.
+                       pkgAnnotate := false
+                       if w.qf == nil && w.pkgInfo && !isExported(f.name) {
+                               // note for embedded types, type name is field name, and "string" etc are lower case hence unexported.
+                               pkgAnnotate = true
+                               w.pkgInfo = false // only tag once
                        }
+
                        // This doesn't do the right thing for embedded type
                        // aliases where we should print the alias name, not
-                       // the aliased type (see issue #44410).
+                       // the aliased type (see go.dev/issue/44410).
                        if !f.embedded {
                                w.string(f.name)
                                w.byte(' ')
                        }
                        w.typ(f.typ)
+                       if pkgAnnotate {
+                               w.string(" /* package ")
+                               w.string(f.pkg.Path())
+                               w.string(" */ ")
+                       }
                        if tag := t.Tag(i); tag != "" {
-                               w.writef(" %q", tag)
+                               w.byte(' ')
+                               // TODO(gri) If tag contains blanks, replacing them with '#'
+                               //           in Context.TypeHash may produce another tag
+                               //           accidentally.
+                               w.string(strconv.Quote(tag))
                        }
                }
                w.byte('}')
@@ -138,11 +196,12 @@ func (w *typeWriter) typ(typ Type) {
                // Unions only appear as (syntactic) embedded elements
                // in interfaces and syntactically cannot be empty.
                if t.Len() == 0 {
-                       panic("empty union")
+                       w.error("empty union")
+                       break
                }
                for i, t := range t.terms {
                        if i > 0 {
-                               w.byte('|')
+                               w.string(termSep)
                        }
                        if t.tilde {
                                w.byte('~')
@@ -151,22 +210,48 @@ func (w *typeWriter) typ(typ Type) {
                }
 
        case *Interface:
+               if w.ctxt == nil {
+                       if t == universeAny.Type() {
+                               // When not hashing, we can try to improve type strings by writing "any"
+                               // for a type that is pointer-identical to universeAny. This logic should
+                               // be deprecated by more robust handling for aliases.
+                               w.string("any")
+                               break
+                       }
+                       if t == asNamed(universeComparable.Type()).underlying {
+                               w.string("interface{comparable}")
+                               break
+                       }
+               }
+               if t.implicit {
+                       if len(t.methods) == 0 && len(t.embeddeds) == 1 {
+                               w.typ(t.embeddeds[0])
+                               break
+                       }
+                       // Something's wrong with the implicit interface.
+                       // Print it as such and continue.
+                       w.string("/* implicit */ ")
+               }
                w.string("interface{")
                first := true
-               for _, m := range t.methods {
-                       if !first {
-                               w.string("; ")
+               if w.ctxt != nil {
+                       w.typeSet(t.typeSet())
+               } else {
+                       for _, m := range t.methods {
+                               if !first {
+                                       w.byte(';')
+                               }
+                               first = false
+                               w.string(m.name)
+                               w.signature(m.typ.(*Signature))
                        }
-                       first = false
-                       w.string(m.name)
-                       w.signature(m.typ.(*Signature))
-               }
-               for _, typ := range t.embeddeds {
-                       if !first {
-                               w.string("; ")
+                       for _, typ := range t.embeddeds {
+                               if !first {
+                                       w.byte(';')
+                               }
+                               first = false
+                               w.typ(typ)
                        }
-                       first = false
-                       w.typ(typ)
                }
                w.byte('}')
 
@@ -191,7 +276,7 @@ func (w *typeWriter) typ(typ Type) {
                case RecvOnly:
                        s = "<-chan "
                default:
-                       unreachable()
+                       w.error("unknown channel direction")
                }
                w.string(s)
                if parens {
@@ -203,38 +288,52 @@ func (w *typeWriter) typ(typ Type) {
                }
 
        case *Named:
-               // Instance markers indicate unexpanded instantiated
-               // types. Write them to aid debugging, but don't write
-               // them when we need an instance hash: whether a type
-               // is fully expanded or not doesn't matter for identity.
-               if instanceHashing == 0 && t.instPos != nil {
-                       w.byte(instanceMarker)
+               // If hashing, write a unique prefix for t to represent its identity, since
+               // named type identity is pointer identity.
+               if w.ctxt != nil {
+                       w.string(strconv.Itoa(w.ctxt.getID(t)))
                }
-               w.typeName(t.obj)
-               if t.targs != nil {
+               w.typeName(t.obj) // when hashing written for readability of the hash only
+               if t.inst != nil {
                        // instantiated type
-                       w.typeList(t.targs.list())
-               } else if t.TParams().Len() != 0 {
+                       w.typeList(t.inst.targs.list())
+               } else if w.ctxt == nil && t.TypeParams().Len() != 0 { // For type hashing, don't need to format the TypeParams
                        // parameterized type
-                       w.tParamList(t.TParams().list())
+                       w.tParamList(t.TypeParams().list())
                }
 
        case *TypeParam:
-               s := "?"
-               if t.obj != nil {
-                       // Optionally write out package for typeparams (like Named).
-                       // TODO(danscales): this is required for import/export, so
-                       // we maybe need a separate function that won't be changed
-                       // for debugging purposes.
-                       if t.obj.pkg != nil {
-                               writePackage(w.buf, t.obj.pkg, w.qf)
+               if t.obj == nil {
+                       w.error("unnamed type parameter")
+                       break
+               }
+               if i := tparamIndex(w.tparams.list(), t); i >= 0 {
+                       // The names of type parameters that are declared by the type being
+                       // hashed are not part of the type identity. Replace them with a
+                       // placeholder indicating their index.
+                       w.string(fmt.Sprintf("$%d", i))
+               } else {
+                       w.string(t.obj.name)
+                       if w.tpSubscripts || w.ctxt != nil {
+                               w.string(subscript(t.id))
+                       }
+                       // If the type parameter name is the same as a predeclared object
+                       // (say int), point out where it is declared to avoid confusing
+                       // error messages. This doesn't need to be super-elegant; we just
+                       // need a clear indication that this is not a predeclared name.
+                       if w.ctxt == nil && Universe.Lookup(t.obj.name) != nil {
+                               w.string(fmt.Sprintf(" /* with %s declared at %s */", t.obj.name, t.obj.Pos()))
                        }
-                       s = t.obj.name
                }
-               w.string(s + subscript(t.id))
 
-       case *top:
-               w.string("⊤")
+       case *_Alias:
+               w.typeName(t.obj)
+               if w.ctxt != nil {
+                       // TODO(gri) do we need to print the alias type name, too?
+                       w.typ(_Unalias(t.obj.typ))
+               } else {
+                       w.string(fmt.Sprintf(" /* = %s */", _Unalias(t.obj.typ)))
+               }
 
        default:
                // For externally defined implementations of Type.
@@ -243,11 +342,47 @@ func (w *typeWriter) typ(typ Type) {
        }
 }
 
+// typeSet writes a canonical hash for an interface type set.
+func (w *typeWriter) typeSet(s *_TypeSet) {
+       assert(w.ctxt != nil)
+       first := true
+       for _, m := range s.methods {
+               if !first {
+                       w.byte(';')
+               }
+               first = false
+               w.string(m.name)
+               w.signature(m.typ.(*Signature))
+       }
+       switch {
+       case s.terms.isAll():
+               // nothing to do
+       case s.terms.isEmpty():
+               w.string(s.terms.String())
+       default:
+               var termHashes []string
+               for _, term := range s.terms {
+                       // terms are not canonically sorted, so we sort their hashes instead.
+                       var buf bytes.Buffer
+                       if term.tilde {
+                               buf.WriteByte('~')
+                       }
+                       newTypeHasher(&buf, w.ctxt).typ(term.typ)
+                       termHashes = append(termHashes, buf.String())
+               }
+               sort.Strings(termHashes)
+               if !first {
+                       w.byte(';')
+               }
+               w.string(strings.Join(termHashes, "|"))
+       }
+}
+
 func (w *typeWriter) typeList(list []Type) {
        w.byte('[')
        for i, typ := range list {
                if i > 0 {
-                       w.string(", ")
+                       w.byte(',')
                }
                w.typ(typ)
        }
@@ -261,26 +396,20 @@ func (w *typeWriter) tParamList(list []*TypeParam) {
                // Determine the type parameter and its constraint.
                // list is expected to hold type parameter names,
                // but don't crash if that's not the case.
-               var bound Type
-               if tpar != nil {
-                       bound = tpar.bound // should not be nil but we want to see it if it is
+               if tpar == nil {
+                       w.error("nil type parameter")
+                       continue
                }
-
                if i > 0 {
-                       if bound != prev {
+                       if tpar.bound != prev {
                                // bound changed - write previous one before advancing
                                w.byte(' ')
                                w.typ(prev)
                        }
-                       w.string(", ")
-               }
-               prev = bound
-
-               if tpar != nil {
-                       w.typ(tpar)
-               } else {
-                       w.string(tpar.obj.name)
+                       w.byte(',')
                }
+               prev = tpar.bound
+               w.typ(tpar)
        }
        if prev != nil {
                w.byte(' ')
@@ -290,39 +419,8 @@ func (w *typeWriter) tParamList(list []*TypeParam) {
 }
 
 func (w *typeWriter) typeName(obj *TypeName) {
-       if obj == nil {
-               assert(instanceHashing == 0) // we need an object for instance hashing
-               w.string("<Named w/o object>")
-               return
-       }
-       if obj.pkg != nil {
-               writePackage(w.buf, obj.pkg, w.qf)
-       }
+       w.string(packagePrefix(obj.pkg, w.qf))
        w.string(obj.name)
-
-       if instanceHashing != 0 {
-               // For local defined types, use the (original!) TypeName's scope
-               // numbers to disambiguate.
-               typ := obj.typ.(*Named)
-               // TODO(gri) Figure out why typ.orig != typ.orig.orig sometimes
-               //           and whether the loop can iterate more than twice.
-               //           (It seems somehow connected to instance types.)
-               for typ.orig != typ {
-                       typ = typ.orig
-               }
-               w.writeScopeNumbers(typ.obj.parent)
-       }
-}
-
-// writeScopeNumbers writes the number sequence for this scope to buf
-// in the form ".i.j.k" where i, j, k, etc. stand for scope numbers.
-// If a scope is nil or has no parent (such as a package scope), nothing
-// is written.
-func (w *typeWriter) writeScopeNumbers(s *Scope) {
-       if s != nil && s.number > 0 {
-               w.writeScopeNumbers(s.parent)
-               w.writef(".%d", s.number)
-       }
 }
 
 func (w *typeWriter) tuple(tup *Tuple, variadic bool) {
@@ -330,9 +428,10 @@ func (w *typeWriter) tuple(tup *Tuple, variadic bool) {
        if tup != nil {
                for i, v := range tup.vars {
                        if i > 0 {
-                               w.string(", ")
+                               w.byte(',')
                        }
-                       if v.name != "" {
+                       // parameter names are ignored for type identity and thus type hashes
+                       if w.ctxt == nil && v.name != "" && w.paramNames {
                                w.string(v.name)
                                w.byte(' ')
                        }
@@ -344,8 +443,9 @@ func (w *typeWriter) tuple(tup *Tuple, variadic bool) {
                                } else {
                                        // special case:
                                        // append(s, "foo"...) leads to signature func([]byte, string...)
-                                       if t := asBasic(typ); t == nil || t.kind != String {
-                                               panic("expected string type")
+                                       if t, _ := under(typ).(*Basic); t == nil || t.kind != String {
+                                               w.error("expected string type")
+                                               continue
                                        }
                                        w.typ(typ)
                                        w.string("...")
@@ -358,17 +458,16 @@ func (w *typeWriter) tuple(tup *Tuple, variadic bool) {
        w.byte(')')
 }
 
-// WriteSignature writes the representation of the signature sig to buf,
-// without a leading "func" keyword.
-// The Qualifier controls the printing of
-// package-level objects, and may be nil.
-func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
-       newTypeWriter(buf, qf).signature(sig)
-}
-
 func (w *typeWriter) signature(sig *Signature) {
-       if sig.TParams().Len() != 0 {
-               w.tParamList(sig.TParams().list())
+       if sig.TypeParams().Len() != 0 {
+               if w.ctxt != nil {
+                       assert(w.tparams == nil)
+                       w.tparams = sig.TypeParams()
+                       defer func() {
+                               w.tparams = nil
+                       }()
+               }
+               w.tParamList(sig.TypeParams().list())
        }
 
        w.tuple(sig.params, sig.variadic)
@@ -380,8 +479,8 @@ func (w *typeWriter) signature(sig *Signature) {
        }
 
        w.byte(' ')
-       if n == 1 && sig.results.vars[0].name == "" {
-               // single unnamed result
+       if n == 1 && (w.ctxt != nil || sig.results.vars[0].name == "") {
+               // single unnamed result (if type hashing, name must be ignored)
                w.typ(sig.results.vars[0].typ)
                return
        }