github.com/4ad/go@v0.0.0-20161219182952-69a12818b605/src/cmd/vet/types.go (about) 1 // Copyright 2010 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 contains the pieces of the tool that use typechecking from the go/types package. 6 7 package main 8 9 import ( 10 "go/ast" 11 "go/importer" 12 "go/token" 13 "go/types" 14 ) 15 16 // stdImporter is the importer we use to import packages. 17 // It is created during initialization so that all packages 18 // are imported by the same importer. 19 var stdImporter = importer.Default() 20 21 var ( 22 errorType *types.Interface 23 stringerType *types.Interface // possibly nil 24 formatterType *types.Interface // possibly nil 25 ) 26 27 func init() { 28 errorType = types.Universe.Lookup("error").Type().Underlying().(*types.Interface) 29 30 if typ := importType("fmt", "Stringer"); typ != nil { 31 stringerType = typ.Underlying().(*types.Interface) 32 } 33 34 if typ := importType("fmt", "Formatter"); typ != nil { 35 formatterType = typ.Underlying().(*types.Interface) 36 } 37 } 38 39 // importType returns the type denoted by the qualified identifier 40 // path.name, and adds the respective package to the imports map 41 // as a side effect. In case of an error, importType returns nil. 42 func importType(path, name string) types.Type { 43 pkg, err := stdImporter.Import(path) 44 if err != nil { 45 // This can happen if the package at path hasn't been compiled yet. 46 warnf("import failed: %v", err) 47 return nil 48 } 49 if obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok { 50 return obj.Type() 51 } 52 warnf("invalid type name %q", name) 53 return nil 54 } 55 56 func (pkg *Package) check(fs *token.FileSet, astFiles []*ast.File) error { 57 pkg.defs = make(map[*ast.Ident]types.Object) 58 pkg.uses = make(map[*ast.Ident]types.Object) 59 pkg.selectors = make(map[*ast.SelectorExpr]*types.Selection) 60 pkg.spans = make(map[types.Object]Span) 61 pkg.types = make(map[ast.Expr]types.TypeAndValue) 62 config := types.Config{ 63 // We use the same importer for all imports to ensure that 64 // everybody sees identical packages for the given paths. 65 Importer: stdImporter, 66 // By providing a Config with our own error function, it will continue 67 // past the first error. There is no need for that function to do anything. 68 Error: func(error) {}, 69 } 70 info := &types.Info{ 71 Selections: pkg.selectors, 72 Types: pkg.types, 73 Defs: pkg.defs, 74 Uses: pkg.uses, 75 } 76 typesPkg, err := config.Check(pkg.path, fs, astFiles, info) 77 pkg.typesPkg = typesPkg 78 // update spans 79 for id, obj := range pkg.defs { 80 pkg.growSpan(id, obj) 81 } 82 for id, obj := range pkg.uses { 83 pkg.growSpan(id, obj) 84 } 85 return err 86 } 87 88 // matchArgType reports an error if printf verb t is not appropriate 89 // for operand arg. 90 // 91 // typ is used only for recursive calls; external callers must supply nil. 92 // 93 // (Recursion arises from the compound types {map,chan,slice} which 94 // may be printed with %d etc. if that is appropriate for their element 95 // types.) 96 func (f *File) matchArgType(t printfArgType, typ types.Type, arg ast.Expr) bool { 97 return f.matchArgTypeInternal(t, typ, arg, make(map[types.Type]bool)) 98 } 99 100 // matchArgTypeInternal is the internal version of matchArgType. It carries a map 101 // remembering what types are in progress so we don't recur when faced with recursive 102 // types or mutually recursive types. 103 func (f *File) matchArgTypeInternal(t printfArgType, typ types.Type, arg ast.Expr, inProgress map[types.Type]bool) bool { 104 // %v, %T accept any argument type. 105 if t == anyType { 106 return true 107 } 108 if typ == nil { 109 // external call 110 typ = f.pkg.types[arg].Type 111 if typ == nil { 112 return true // probably a type check problem 113 } 114 } 115 // If the type implements fmt.Formatter, we have nothing to check. 116 // formatterTyp may be nil - be conservative and check for Format method in that case. 117 if formatterType != nil && types.Implements(typ, formatterType) || f.hasMethod(typ, "Format") { 118 return true 119 } 120 // If we can use a string, might arg (dynamically) implement the Stringer or Error interface? 121 if t&argString != 0 { 122 if types.AssertableTo(errorType, typ) || stringerType != nil && types.AssertableTo(stringerType, typ) { 123 return true 124 } 125 } 126 127 typ = typ.Underlying() 128 if inProgress[typ] { 129 // We're already looking at this type. The call that started it will take care of it. 130 return true 131 } 132 inProgress[typ] = true 133 134 switch typ := typ.(type) { 135 case *types.Signature: 136 return t&argPointer != 0 137 138 case *types.Map: 139 // Recur: map[int]int matches %d. 140 return t&argPointer != 0 || 141 (f.matchArgTypeInternal(t, typ.Key(), arg, inProgress) && f.matchArgTypeInternal(t, typ.Elem(), arg, inProgress)) 142 143 case *types.Chan: 144 return t&argPointer != 0 145 146 case *types.Array: 147 // Same as slice. 148 if types.Identical(typ.Elem().Underlying(), types.Typ[types.Byte]) && t&argString != 0 { 149 return true // %s matches []byte 150 } 151 // Recur: []int matches %d. 152 return t&argPointer != 0 || f.matchArgTypeInternal(t, typ.Elem().Underlying(), arg, inProgress) 153 154 case *types.Slice: 155 // Same as array. 156 if types.Identical(typ.Elem().Underlying(), types.Typ[types.Byte]) && t&argString != 0 { 157 return true // %s matches []byte 158 } 159 // Recur: []int matches %d. But watch out for 160 // type T []T 161 // If the element is a pointer type (type T[]*T), it's handled fine by the Pointer case below. 162 return t&argPointer != 0 || f.matchArgTypeInternal(t, typ.Elem(), arg, inProgress) 163 164 case *types.Pointer: 165 // Ugly, but dealing with an edge case: a known pointer to an invalid type, 166 // probably something from a failed import. 167 if typ.Elem().String() == "invalid type" { 168 if *verbose { 169 f.Warnf(arg.Pos(), "printf argument %v is pointer to invalid or unknown type", f.gofmt(arg)) 170 } 171 return true // special case 172 } 173 // If it's actually a pointer with %p, it prints as one. 174 if t == argPointer { 175 return true 176 } 177 // If it's pointer to struct, that's equivalent in our analysis to whether we can print the struct. 178 if str, ok := typ.Elem().Underlying().(*types.Struct); ok { 179 return f.matchStructArgType(t, str, arg, inProgress) 180 } 181 // The rest can print with %p as pointers, or as integers with %x etc. 182 return t&(argInt|argPointer) != 0 183 184 case *types.Struct: 185 return f.matchStructArgType(t, typ, arg, inProgress) 186 187 case *types.Interface: 188 // If the static type of the argument is empty interface, there's little we can do. 189 // Example: 190 // func f(x interface{}) { fmt.Printf("%s", x) } 191 // Whether x is valid for %s depends on the type of the argument to f. One day 192 // we will be able to do better. For now, we assume that empty interface is OK 193 // but non-empty interfaces, with Stringer and Error handled above, are errors. 194 return typ.NumMethods() == 0 195 196 case *types.Basic: 197 switch typ.Kind() { 198 case types.UntypedBool, 199 types.Bool: 200 return t&argBool != 0 201 202 case types.UntypedInt, 203 types.Int, 204 types.Int8, 205 types.Int16, 206 types.Int32, 207 types.Int64, 208 types.Uint, 209 types.Uint8, 210 types.Uint16, 211 types.Uint32, 212 types.Uint64, 213 types.Uintptr: 214 return t&argInt != 0 215 216 case types.UntypedFloat, 217 types.Float32, 218 types.Float64: 219 return t&argFloat != 0 220 221 case types.UntypedComplex, 222 types.Complex64, 223 types.Complex128: 224 return t&argComplex != 0 225 226 case types.UntypedString, 227 types.String: 228 return t&argString != 0 229 230 case types.UnsafePointer: 231 return t&(argPointer|argInt) != 0 232 233 case types.UntypedRune: 234 return t&(argInt|argRune) != 0 235 236 case types.UntypedNil: 237 return t&argPointer != 0 // TODO? 238 239 case types.Invalid: 240 if *verbose { 241 f.Warnf(arg.Pos(), "printf argument %v has invalid or unknown type", f.gofmt(arg)) 242 } 243 return true // Probably a type check problem. 244 } 245 panic("unreachable") 246 } 247 248 return false 249 } 250 251 // hasBasicType reports whether x's type is a types.Basic with the given kind. 252 func (f *File) hasBasicType(x ast.Expr, kind types.BasicKind) bool { 253 t := f.pkg.types[x].Type 254 if t != nil { 255 t = t.Underlying() 256 } 257 b, ok := t.(*types.Basic) 258 return ok && b.Kind() == kind 259 } 260 261 // matchStructArgType reports whether all the elements of the struct match the expected 262 // type. For instance, with "%d" all the elements must be printable with the "%d" format. 263 func (f *File) matchStructArgType(t printfArgType, typ *types.Struct, arg ast.Expr, inProgress map[types.Type]bool) bool { 264 for i := 0; i < typ.NumFields(); i++ { 265 if !f.matchArgTypeInternal(t, typ.Field(i).Type(), arg, inProgress) { 266 return false 267 } 268 } 269 return true 270 } 271 272 // hasMethod reports whether the type contains a method with the given name. 273 // It is part of the workaround for Formatters and should be deleted when 274 // that workaround is no longer necessary. 275 // TODO: This could be better once issue 6259 is fixed. 276 func (f *File) hasMethod(typ types.Type, name string) bool { 277 // assume we have an addressable variable of type typ 278 obj, _, _ := types.LookupFieldOrMethod(typ, true, f.pkg.typesPkg, name) 279 _, ok := obj.(*types.Func) 280 return ok 281 }