github.com/bir3/gocompiler@v0.3.205/src/go/types/index.go (about) 1 // Copyright 2021 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 typechecking of index/slice expressions. 6 7 package types 8 9 import ( 10 "github.com/bir3/gocompiler/src/go/ast" 11 "github.com/bir3/gocompiler/src/go/constant" 12 "github.com/bir3/gocompiler/src/go/internal/typeparams" 13 . "github.com/bir3/gocompiler/src/internal/types/errors" 14 ) 15 16 // If e is a valid function instantiation, indexExpr returns true. 17 // In that case x represents the uninstantiated function value and 18 // it is the caller's responsibility to instantiate the function. 19 func (check *Checker) indexExpr(x *operand, e *typeparams.IndexExpr) (isFuncInst bool) { 20 check.exprOrType(x, e.X, true) 21 // x may be generic 22 23 switch x.mode { 24 case invalid: 25 check.use(e.Indices...) 26 return false 27 28 case typexpr: 29 // type instantiation 30 x.mode = invalid 31 // TODO(gri) here we re-evaluate e.X - try to avoid this 32 x.typ = check.varType(e.Orig) 33 if x.typ != Typ[Invalid] { 34 x.mode = typexpr 35 } 36 return false 37 38 case value: 39 if sig, _ := under(x.typ).(*Signature); sig != nil && sig.TypeParams().Len() > 0 { 40 // function instantiation 41 return true 42 } 43 } 44 45 // x should not be generic at this point, but be safe and check 46 check.nonGeneric(x) 47 if x.mode == invalid { 48 return false 49 } 50 51 // ordinary index expression 52 valid := false 53 length := int64(-1) // valid if >= 0 54 switch typ := under(x.typ).(type) { 55 case *Basic: 56 if isString(typ) { 57 valid = true 58 if x.mode == constant_ { 59 length = int64(len(constant.StringVal(x.val))) 60 } 61 // an indexed string always yields a byte value 62 // (not a constant) even if the string and the 63 // index are constant 64 x.mode = value 65 x.typ = universeByte // use 'byte' name 66 } 67 68 case *Array: 69 valid = true 70 length = typ.len 71 if x.mode != variable { 72 x.mode = value 73 } 74 x.typ = typ.elem 75 76 case *Pointer: 77 if typ, _ := under(typ.base).(*Array); typ != nil { 78 valid = true 79 length = typ.len 80 x.mode = variable 81 x.typ = typ.elem 82 } 83 84 case *Slice: 85 valid = true 86 x.mode = variable 87 x.typ = typ.elem 88 89 case *Map: 90 index := check.singleIndex(e) 91 if index == nil { 92 x.mode = invalid 93 return false 94 } 95 var key operand 96 check.expr(&key, index) 97 check.assignment(&key, typ.key, "map index") 98 // ok to continue even if indexing failed - map element type is known 99 x.mode = mapindex 100 x.typ = typ.elem 101 x.expr = e.Orig 102 return false 103 104 case *Interface: 105 if !isTypeParam(x.typ) { 106 break 107 } 108 // TODO(gri) report detailed failure cause for better error messages 109 var key, elem Type // key != nil: we must have all maps 110 mode := variable // non-maps result mode 111 // TODO(gri) factor out closure and use it for non-typeparam cases as well 112 if typ.typeSet().underIs(func(u Type) bool { 113 l := int64(-1) // valid if >= 0 114 var k, e Type // k is only set for maps 115 switch t := u.(type) { 116 case *Basic: 117 if isString(t) { 118 e = universeByte 119 mode = value 120 } 121 case *Array: 122 l = t.len 123 e = t.elem 124 if x.mode != variable { 125 mode = value 126 } 127 case *Pointer: 128 if t, _ := under(t.base).(*Array); t != nil { 129 l = t.len 130 e = t.elem 131 } 132 case *Slice: 133 e = t.elem 134 case *Map: 135 k = t.key 136 e = t.elem 137 } 138 if e == nil { 139 return false 140 } 141 if elem == nil { 142 // first type 143 length = l 144 key, elem = k, e 145 return true 146 } 147 // all map keys must be identical (incl. all nil) 148 // (that is, we cannot mix maps with other types) 149 if !Identical(key, k) { 150 return false 151 } 152 // all element types must be identical 153 if !Identical(elem, e) { 154 return false 155 } 156 // track the minimal length for arrays, if any 157 if l >= 0 && l < length { 158 length = l 159 } 160 return true 161 }) { 162 // For maps, the index expression must be assignable to the map key type. 163 if key != nil { 164 index := check.singleIndex(e) 165 if index == nil { 166 x.mode = invalid 167 return false 168 } 169 var k operand 170 check.expr(&k, index) 171 check.assignment(&k, key, "map index") 172 // ok to continue even if indexing failed - map element type is known 173 x.mode = mapindex 174 x.typ = elem 175 x.expr = e 176 return false 177 } 178 179 // no maps 180 valid = true 181 x.mode = mode 182 x.typ = elem 183 } 184 } 185 186 if !valid { 187 // types2 uses the position of '[' for the error 188 check.errorf(x, NonIndexableOperand, invalidOp+"cannot index %s", x) 189 x.mode = invalid 190 return false 191 } 192 193 index := check.singleIndex(e) 194 if index == nil { 195 x.mode = invalid 196 return false 197 } 198 199 // In pathological (invalid) cases (e.g.: type T1 [][[]T1{}[0][0]]T0) 200 // the element type may be accessed before it's set. Make sure we have 201 // a valid type. 202 if x.typ == nil { 203 x.typ = Typ[Invalid] 204 } 205 206 check.index(index, length) 207 return false 208 } 209 210 func (check *Checker) sliceExpr(x *operand, e *ast.SliceExpr) { 211 check.expr(x, e.X) 212 if x.mode == invalid { 213 check.use(e.Low, e.High, e.Max) 214 return 215 } 216 217 valid := false 218 length := int64(-1) // valid if >= 0 219 switch u := coreString(x.typ).(type) { 220 case nil: 221 check.errorf(x, NonSliceableOperand, invalidOp+"cannot slice %s: %s has no core type", x, x.typ) 222 x.mode = invalid 223 return 224 225 case *Basic: 226 if isString(u) { 227 if e.Slice3 { 228 at := e.Max 229 if at == nil { 230 at = e // e.Index[2] should be present but be careful 231 } 232 check.error(at, InvalidSliceExpr, invalidOp+"3-index slice of string") 233 x.mode = invalid 234 return 235 } 236 valid = true 237 if x.mode == constant_ { 238 length = int64(len(constant.StringVal(x.val))) 239 } 240 // spec: "For untyped string operands the result 241 // is a non-constant value of type string." 242 if isUntyped(x.typ) { 243 x.typ = Typ[String] 244 } 245 } 246 247 case *Array: 248 valid = true 249 length = u.len 250 if x.mode != variable { 251 check.errorf(x, NonSliceableOperand, invalidOp+"cannot slice %s (value not addressable)", x) 252 x.mode = invalid 253 return 254 } 255 x.typ = &Slice{elem: u.elem} 256 257 case *Pointer: 258 if u, _ := under(u.base).(*Array); u != nil { 259 valid = true 260 length = u.len 261 x.typ = &Slice{elem: u.elem} 262 } 263 264 case *Slice: 265 valid = true 266 // x.typ doesn't change 267 } 268 269 if !valid { 270 check.errorf(x, NonSliceableOperand, invalidOp+"cannot slice %s", x) 271 x.mode = invalid 272 return 273 } 274 275 x.mode = value 276 277 // spec: "Only the first index may be omitted; it defaults to 0." 278 if e.Slice3 && (e.High == nil || e.Max == nil) { 279 check.error(inNode(e, e.Rbrack), InvalidSyntaxTree, "2nd and 3rd index required in 3-index slice") 280 x.mode = invalid 281 return 282 } 283 284 // check indices 285 var ind [3]int64 286 for i, expr := range []ast.Expr{e.Low, e.High, e.Max} { 287 x := int64(-1) 288 switch { 289 case expr != nil: 290 // The "capacity" is only known statically for strings, arrays, 291 // and pointers to arrays, and it is the same as the length for 292 // those types. 293 max := int64(-1) 294 if length >= 0 { 295 max = length + 1 296 } 297 if _, v := check.index(expr, max); v >= 0 { 298 x = v 299 } 300 case i == 0: 301 // default is 0 for the first index 302 x = 0 303 case length >= 0: 304 // default is length (== capacity) otherwise 305 x = length 306 } 307 ind[i] = x 308 } 309 310 // constant indices must be in range 311 // (check.index already checks that existing indices >= 0) 312 L: 313 for i, x := range ind[:len(ind)-1] { 314 if x > 0 { 315 for j, y := range ind[i+1:] { 316 if y >= 0 && y < x { 317 // The value y corresponds to the expression e.Index[i+1+j]. 318 // Because y >= 0, it must have been set from the expression 319 // when checking indices and thus e.Index[i+1+j] is not nil. 320 at := []ast.Expr{e.Low, e.High, e.Max}[i+1+j] 321 check.errorf(at, SwappedSliceIndices, "invalid slice indices: %d < %d", y, x) 322 break L // only report one error, ok to continue 323 } 324 } 325 } 326 } 327 } 328 329 // singleIndex returns the (single) index from the index expression e. 330 // If the index is missing, or if there are multiple indices, an error 331 // is reported and the result is nil. 332 func (check *Checker) singleIndex(expr *typeparams.IndexExpr) ast.Expr { 333 if len(expr.Indices) == 0 { 334 check.errorf(expr.Orig, InvalidSyntaxTree, "index expression %v with 0 indices", expr) 335 return nil 336 } 337 if len(expr.Indices) > 1 { 338 // TODO(rFindley) should this get a distinct error code? 339 check.error(expr.Indices[1], InvalidIndex, invalidOp+"more than one index") 340 } 341 return expr.Indices[0] 342 } 343 344 // index checks an index expression for validity. 345 // If max >= 0, it is the upper bound for index. 346 // If the result typ is != Typ[Invalid], index is valid and typ is its (possibly named) integer type. 347 // If the result val >= 0, index is valid and val is its constant int value. 348 func (check *Checker) index(index ast.Expr, max int64) (typ Type, val int64) { 349 typ = Typ[Invalid] 350 val = -1 351 352 var x operand 353 check.expr(&x, index) 354 if !check.isValidIndex(&x, InvalidIndex, "index", false) { 355 return 356 } 357 358 if x.mode != constant_ { 359 return x.typ, -1 360 } 361 362 if x.val.Kind() == constant.Unknown { 363 return 364 } 365 366 v, ok := constant.Int64Val(x.val) 367 assert(ok) 368 if max >= 0 && v >= max { 369 check.errorf(&x, InvalidIndex, invalidArg+"index %s out of bounds [0:%d]", x.val.String(), max) 370 return 371 } 372 373 // 0 <= v [ && v < max ] 374 return x.typ, v 375 } 376 377 func (check *Checker) isValidIndex(x *operand, code Code, what string, allowNegative bool) bool { 378 if x.mode == invalid { 379 return false 380 } 381 382 // spec: "a constant index that is untyped is given type int" 383 check.convertUntyped(x, Typ[Int]) 384 if x.mode == invalid { 385 return false 386 } 387 388 // spec: "the index x must be of integer type or an untyped constant" 389 if !allInteger(x.typ) { 390 check.errorf(x, code, invalidArg+"%s %s must be integer", what, x) 391 return false 392 } 393 394 if x.mode == constant_ { 395 // spec: "a constant index must be non-negative ..." 396 if !allowNegative && constant.Sign(x.val) < 0 { 397 check.errorf(x, code, invalidArg+"%s %s must not be negative", what, x) 398 return false 399 } 400 401 // spec: "... and representable by a value of type int" 402 if !representableConst(x.val, check, Typ[Int], &x.val) { 403 check.errorf(x, code, invalidArg+"%s %s overflows int", what, x) 404 return false 405 } 406 } 407 408 return true 409 } 410 411 // indexElts checks the elements (elts) of an array or slice composite literal 412 // against the literal's element type (typ), and the element indices against 413 // the literal length if known (length >= 0). It returns the length of the 414 // literal (maximum index value + 1). 415 func (check *Checker) indexedElts(elts []ast.Expr, typ Type, length int64) int64 { 416 visited := make(map[int64]bool, len(elts)) 417 var index, max int64 418 for _, e := range elts { 419 // determine and check index 420 validIndex := false 421 eval := e 422 if kv, _ := e.(*ast.KeyValueExpr); kv != nil { 423 if typ, i := check.index(kv.Key, length); typ != Typ[Invalid] { 424 if i >= 0 { 425 index = i 426 validIndex = true 427 } else { 428 check.errorf(e, InvalidLitIndex, "index %s must be integer constant", kv.Key) 429 } 430 } 431 eval = kv.Value 432 } else if length >= 0 && index >= length { 433 check.errorf(e, OversizeArrayLit, "index %d is out of bounds (>= %d)", index, length) 434 } else { 435 validIndex = true 436 } 437 438 // if we have a valid index, check for duplicate entries 439 if validIndex { 440 if visited[index] { 441 check.errorf(e, DuplicateLitKey, "duplicate index %d in array or slice literal", index) 442 } 443 visited[index] = true 444 } 445 index++ 446 if index > max { 447 max = index 448 } 449 450 // check element against composite literal element type 451 var x operand 452 check.exprWithHint(&x, eval, typ) 453 check.assignment(&x, typ, "array or slice literal") 454 } 455 return max 456 }