@@ -301,6 +301,20 @@ func (p *pass) loadPackageNames(imports []*ImportInfo) error {
301
301
return nil
302
302
}
303
303
304
+ // if there is a trailing major version, remove it
305
+ func withoutVersion (nm string ) string {
306
+ if v := path .Base (nm ); len (v ) > 0 && v [0 ] == 'v' {
307
+ if _ , err := strconv .Atoi (v [1 :]); err == nil {
308
+ // this is, for instance, called with rand/v2 and returns rand
309
+ if len (v ) < len (nm ) {
310
+ xnm := nm [:len (nm )- len (v )- 1 ]
311
+ return path .Base (xnm )
312
+ }
313
+ }
314
+ }
315
+ return nm
316
+ }
317
+
304
318
// importIdentifier returns the identifier that imp will introduce. It will
305
319
// guess if the package name has not been loaded, e.g. because the source
306
320
// is not available.
@@ -310,7 +324,7 @@ func (p *pass) importIdentifier(imp *ImportInfo) string {
310
324
}
311
325
known := p .knownPackages [imp .ImportPath ]
312
326
if known != nil && known .name != "" {
313
- return known .name
327
+ return withoutVersion ( known .name )
314
328
}
315
329
return ImportPathToAssumedName (imp .ImportPath )
316
330
}
@@ -1059,6 +1073,18 @@ func addStdlibCandidates(pass *pass, refs references) error {
1059
1073
if err != nil {
1060
1074
return err
1061
1075
}
1076
+ localbase := func (nm string ) string {
1077
+ ans := path .Base (nm )
1078
+ if ans [0 ] == 'v' {
1079
+ // this is called, for instance, with math/rand/v2 and returns rand/v2
1080
+ if _ , err := strconv .Atoi (ans [1 :]); err == nil {
1081
+ ix := strings .LastIndex (nm , ans )
1082
+ more := path .Base (nm [:ix ])
1083
+ ans = path .Join (more , ans )
1084
+ }
1085
+ }
1086
+ return ans
1087
+ }
1062
1088
add := func (pkg string ) {
1063
1089
// Prevent self-imports.
1064
1090
if path .Base (pkg ) == pass .f .Name .Name && filepath .Join (goenv ["GOROOT" ], "src" , pkg ) == pass .srcDir {
@@ -1067,13 +1093,17 @@ func addStdlibCandidates(pass *pass, refs references) error {
1067
1093
exports := symbolNameSet (stdlib .PackageSymbols [pkg ])
1068
1094
pass .addCandidate (
1069
1095
& ImportInfo {ImportPath : pkg },
1070
- & packageInfo {name : path . Base (pkg ), exports : exports })
1096
+ & packageInfo {name : localbase (pkg ), exports : exports })
1071
1097
}
1072
1098
for left := range refs {
1073
1099
if left == "rand" {
1074
- // Make sure we try crypto/rand before math/rand.
1100
+ // Make sure we try crypto/rand before any version of math/rand as both have Int()
1101
+ // and our policy is to recommend crypto
1075
1102
add ("crypto/rand" )
1076
- add ("math/rand" )
1103
+ // if the user's no later than go1.21, this should be "math/rand"
1104
+ // but we have no way of figuring out what the user is using
1105
+ // TODO: investigate using the toolchain version to disambiguate in the stdlib
1106
+ add ("math/rand/v2" )
1077
1107
continue
1078
1108
}
1079
1109
for importPath := range stdlib .PackageSymbols {
0 commit comments