package structure import ( "go/ast" "go/token" "slices" ) // ruleFolderIDs is checkFolderIDs' name, as its failures start. const ruleFolderIDs = "folder-ids" // folderIDOperand is whether e reads like a folder's identity // (platform.FolderID) or its volume: a field named Folder or GitID, as .git // protection's record holds them, a call of a VM state's Folder or // FolderVolume, or of FolderID, folderID or FolderDevice, or a name in // locals, a function's own names that one of those was assigned to. The // check reads no types, so any field or method by those names counts. func folderIDOperand(e ast.Expr, locals map[string]bool) bool { switch e := e.(type) { case *ast.Ident: return locals[e.Name] case *ast.SelectorExpr: return e.Sel.Name == "Folder" || e.Sel.Name == "GitID" case *ast.CallExpr: switch fun := e.Fun.(type) { case *ast.SelectorExpr: return slices.Contains([]string{"Folder", "FolderVolume", "FolderID", "FolderDevice"}, fun.Sel.Name) case *ast.Ident: return fun.Name == "FolderID" || fun.Name == "folderID" } } return false } // folderIDLocals are the names in body that a folder's identity is assigned // to (folderIDOperand), by := or =, or declared with, or one of those // names, however many assignments on, so a comparison of one, which reads // like any string's, is still found. func folderIDLocals(body *ast.BlockStmt) map[string]bool { locals := map[string]bool{} for grew := true; grew; { grew = false ast.Inspect(body, func(n ast.Node) bool { var lhs, rhs []ast.Expr switch n := n.(type) { case *ast.AssignStmt: lhs, rhs = n.Lhs, n.Rhs case *ast.ValueSpec: for _, id := range n.Names { lhs = append(lhs, id) } rhs = n.Values default: return true } for i, l := range lhs { id, ok := l.(*ast.Ident) switch { case !ok || locals[id.Name]: case len(lhs) == len(rhs) && folderIDOperand(rhs[i], locals), // id, err := FolderID(dir): the call's first result. i == 0 && len(rhs) == 1 && folderIDOperand(rhs[0], locals): locals[id.Name], grew = true, true } } return true }) } return locals } // comparesOne is how n compares a folder's identity (folderIDOperand, with // locals), but with "": == or !=, a switch on one, strings.EqualFold, // strings.Compare, slices.Contains or slices.Index with one, or a map // keyed by one, indexed or in a literal (where a key that's a bare name // counts only in a map's, its type written out or one of named, the named // map types: elsewhere it's a struct's field); "" for none. func comparesOne(n ast.Node, locals map[string]bool, named namedMaps) string { is := func(e ast.Expr) bool { return folderIDOperand(e, locals) } switch n := n.(type) { case *ast.IndexExpr: if is(n.Index) { return "keys a map by a folder's identity" } case *ast.CompositeLit: if keysBy(n.Elts, named.is(n.Type), is) || elidedKeys(n.Elts, elemOf(n.Type), named, is) { return "keys a map by a folder's identity" } case *ast.BinaryExpr: if n.Op != token.EQL && n.Op != token.NEQ || emptyString(n.X) || emptyString(n.Y) { return "" } if is(n.X) || is(n.Y) { return "compares a folder's identity with " + n.Op.String() } case *ast.SwitchStmt: if n.Tag != nil && is(n.Tag) { return "switches on a folder's identity" } case *ast.CallExpr: sel, ok := n.Fun.(*ast.SelectorExpr) cmp := false if ok { x, xok := sel.X.(*ast.Ident) cmp = xok && (x.Name == "strings" && (sel.Sel.Name == "EqualFold" || sel.Sel.Name == "Compare") || x.Name == "slices" && (sel.Sel.Name == "Contains" || sel.Sel.Name == "Index")) } if cmp && slices.ContainsFunc(n.Args, is) { return "compares a folder's identity with " + sel.Sel.Name } } return "" } // keysBy reports whether a literal's elements, elts, have a key that is a // folder's identity (is): any such key in a map's (isMap), and elsewhere // one that isn't a bare name, which is a struct's field. func keysBy(elts []ast.Expr, isMap bool, is func(ast.Expr) bool) bool { for _, el := range elts { if kv, ok := el.(*ast.KeyValueExpr); ok && is(kv.Key) { if _, name := kv.Key.(*ast.Ident); isMap || !name { return true } } } return false } // elemOf is the type of a map's values or of a slice's or an array's // elements, through a pointer's, nil for any other type. func elemOf(t ast.Expr) ast.Expr { if star, ok := t.(*ast.StarExpr); ok { t = star.X } switch t := t.(type) { case *ast.MapType: return t.Value case *ast.ArrayType: return t.Elt } return nil } // elidedKeys reports whether a literal's elements, elts, of the type elem, // hold literals whose types are elided, at any depth, that key a map by a // folder's identity (keysBy), elem being a map's type (named.is) or a // pointer to one. func elidedKeys(elts []ast.Expr, elem ast.Expr, named namedMaps, is func(ast.Expr) bool) bool { if elem == nil { return false } t := elem if star, ok := t.(*ast.StarExpr); ok { t = star.X } for _, el := range elts { if kv, ok := el.(*ast.KeyValueExpr); ok { el = kv.Value } lit, ok := el.(*ast.CompositeLit) if !ok || lit.Type != nil { continue } if keysBy(lit.Elts, named.is(t), is) || elidedKeys(lit.Elts, elemOf(t), named, is) { return true } } return false } // emptyString is whether e is the literal "". func emptyString(e ast.Expr) bool { lit, ok := e.(*ast.BasicLit) return ok && lit.Kind == token.STRING && (lit.Value == `""` || lit.Value == "``") } // namedMaps are the names of a module's types whose type is a map's, by // name alone, from every package, as the check reads no types: a type of // that name anywhere counts. type namedMaps map[string]bool // mapTypes are m's named map types. func mapTypes(m *module) namedMaps { named := namedMaps{} for _, f := range m.files { ast.Inspect(f.ast, func(n ast.Node) bool { if ts, ok := n.(*ast.TypeSpec); ok { if _, isMap := ts.Type.(*ast.MapType); isMap { named[ts.Name.Name] = true } } return true }) } return named } // is reports whether t, a composite literal's type, is a map's: written // out, or one of named by its name, in this package or another's. func (named namedMaps) is(t ast.Expr) bool { switch t := t.(type) { case *ast.MapType: return true case *ast.Ident: return named[t.Name] case *ast.SelectorExpr: return named[t.Sel.Name] case *ast.IndexExpr: // a generic named type, M[K] return named.is(t.X) case *ast.IndexListExpr: // M[K, V] return named.is(t.X) } return false } // comparesFolderIDs are f's functions, by siteName, that compare a // folder's identity (comparesOne), each with its first such comparison; // none in owner, the package folder that compares them. func comparesFolderIDs(owner string, named namedMaps) func(srcFile) map[string]drop { return func(f srcFile) map[string]drop { if f.dir == owner { return nil } return sitesWhereIn(f, func(fd *ast.FuncDecl) func(ast.Node) string { locals := folderIDLocals(fd.Body) return func(n ast.Node) string { return comparesOne(n, locals, named) } }) } } // checkFolderIDs: outside tests and the owner (folderIDOwner), no // function compares a folder's identity with == or !=, as a boot can // number an unchanged folder's device anew (platform.SameFolder), unless // exactFolderIDs lists it with why; a listed function that has none // fails. An empty owner checks none. func checkFolderIDs(m *module, r rules) []violation { if r.folderIDOwner == "" { return nil } return siteRule{ruleFolderIDs, "exactFolderIDs", r.exactFolderIDs, comparesFolderIDs(r.folderIDOwner, mapTypes(m)), "compare with platform.SameFolder or SameOpenFolder", "no comparison of a folder's identity"}.check(m) } // folderIDCases break and keep folder-ids. func folderIDCases() []ruleCase { file := func(body string) map[string]string { return map[string]string{"a/a.go": "package a\n\nimport \"example.com/m/p\"\n\n" + "type VM struct{ Dir, Folder string }\n\ntype Repo struct{ GitID string }\n\n" + body} } owner := rules{folderIDOwner: "p"} withExact := func(listed map[string]string) rules { return rules{folderIDOwner: "p", exactFolderIDs: listed} } return []ruleCase{ { name: "a VM's folder compared with ==", files: file("func same(st VM, dir string) bool { id, _ := p.FolderID(dir); return st.Folder == id }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: same in exactFolderIDs"}, }, { name: "a .git's identity compared with != in a method", files: file("func (r Repo) moved(id string) bool { return id != r.GitID }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: Repo.moved in exactFolderIDs"}, }, { name: "a call of FolderID compared", files: file("func here(dir, was string) bool { return p.FolderID(dir) == was }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: here in exactFolderIDs"}, }, { name: "a state's Folder() compared", files: file("type S struct{}\n\nfunc (S) Folder() string { return \"\" }\n\nfunc moved(st S, id string) bool { return st.Folder() != id }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: moved in exactFolderIDs"}, }, { name: "a state's FolderVolume() compared", files: file("type S struct{}\n\nfunc (S) FolderVolume() string { return \"\" }\n\nfunc moved(st S, v string) bool { return v == st.FolderVolume() }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: moved in exactFolderIDs"}, }, { name: "a local an identity was assigned to, compared", files: file("func moved(dir, want string) bool { id := p.FolderID(dir); return id != want }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: moved in exactFolderIDs"}, }, { name: "a local assigned from such a local, compared", files: file("func moved(dir, want string) bool { id := p.FolderID(dir); was := id; var again = was; return again != want }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: moved in exactFolderIDs"}, }, { name: "a map keyed by one", files: file("func seen(st VM, m map[string]bool) bool { return m[st.Folder] }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: seen in exactFolderIDs"}, }, { name: "a map keyed by a local", files: file("func seen(dir string, m map[string]bool) { id, _ := p.FolderID(dir); m[id] = true }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: seen in exactFolderIDs"}, }, { name: "a map literal keyed by one", files: file("func byID(st VM) map[string]VM { return map[string]VM{st.Folder: st} }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: byID in exactFolderIDs"}, }, { name: "a map literal keyed by a local", files: file("func byID(dir string, st VM) map[string]VM { id, _ := p.FolderID(dir); return map[string]VM{id: st} }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: byID in exactFolderIDs"}, }, { name: "a struct literal's field named as a local, and a slice indexed by a number", files: file("type T struct{ id string }\n\nfunc mk(dir string, ids []string) (T, string) { id := p.FolderID(dir); n := 0; return T{id: id}, ids[n] }\n"), r: owner, }, { name: "a switch on a device", files: file("func dev(id string) bool { switch p.FolderDevice(id) { case \"1\": return true }; return false }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: dev in exactFolderIDs"}, }, { name: "strings.EqualFold on one", files: file("func same(st VM, id string) bool { return strings.EqualFold(st.Folder, id) }\n"), r: owner, want: &want{ruleFolderIDs, "list a/a.go: same in exactFolderIDs"}, }, { name: "compared with the owner's", files: file("func same(st VM, dir, id string) bool { return p.SameFolder(st.Dir, st.Folder, dir, id) }\n"), r: owner, }, { name: "compared with \"\"", files: file("func none(st VM) bool { return st.Folder == \"\" }\n"), r: owner, }, { name: "in the owner", files: map[string]string{"p/p.go": "package p\n\nfunc FolderID(string) string { return \"\" }\n\nfunc Same(was, dir string) bool { return FolderID(dir) == was }\n"}, r: owner, }, { name: "a listed comparison", files: file("func same(st VM, id string) bool { return st.Folder == id }\n"), r: withExact(map[string]string{"a/a.go: same": "the record unchanged since it was read"}), }, { name: "a listed function comparing none", files: file("func same(st VM, id string) bool { return p.SameFolder(st.Dir, st.Folder, st.Dir, id) }\n"), r: withExact(map[string]string{"a/a.go: same": "the record unchanged since it was read"}), want: &want{ruleFolderIDs, "a/a.go: same has no comparison of a folder's identity: take it out"}, }, { name: "a comparison in a test", files: map[string]string{"a/a_test.go": "package a\n\ntype VM struct{ Folder string }\n\nfunc same(st VM, id string) bool { return st.Folder == id }\n"}, r: owner, }, } } // folderIDMapCases break and keep folder-ids with literals of named map // types, written out or elided. func folderIDMapCases() []ruleCase { file := func(body string) map[string]string { return map[string]string{"a/a.go": "package a\n\nimport \"example.com/m/p\"\n\ntype VM struct{ Dir, Folder string }\n\n" + body} } owner := rules{folderIDOwner: "p"} want := &want{ruleFolderIDs, "list a/a.go: byID in exactFolderIDs"} return []ruleCase{ { name: "a literal of a named map type keyed by a local", files: file("type IDs map[string]VM\n\nfunc byID(dir string, st VM) IDs { id, _ := p.FolderID(dir); return IDs{id: st} }\n"), r: owner, want: want, }, { name: "a literal of another package's named map type keyed by a local", files: map[string]string{ "p/p.go": "package p\n\ntype IDs map[string]bool\n\nfunc FolderID(string) (string, error) { return \"\", nil }\n", "a/a.go": "package a\n\nimport \"example.com/m/p\"\n\nfunc byID(dir string) p.IDs { id, _ := p.FolderID(dir); return p.IDs{id: true} }\n", }, r: owner, want: want, }, { name: "a literal of a generic named map type keyed by a local", files: file("type IDs[V any] map[string]V\n\nfunc byID(dir string, st VM) IDs[VM] { id, _ := p.FolderID(dir); return IDs[VM]{id: st} }\n"), r: owner, want: want, }, { name: "a map's elided literal of a named map type keyed by a local", files: file("type IDs map[string]VM\n\nfunc byID(dir string, st VM) map[string]IDs { id, _ := p.FolderID(dir); return map[string]IDs{\"a\": {id: st}} }\n"), r: owner, want: want, }, { name: "elided two levels down, a map of slices of a named map type", files: file("type IDs map[string]VM\n\nfunc byID(dir string, st VM) map[string][]IDs { id, _ := p.FolderID(dir); return map[string][]IDs{\"a\": {{id: st}}} }\n"), r: owner, want: want, }, { name: "elided pointers to a named map type", files: file("type IDs map[string]VM\n\nfunc byID(dir string, st VM) []*IDs { id, _ := p.FolderID(dir); return []*IDs{{id: st}} }\n"), r: owner, want: want, }, { name: "a slice's elided struct literals with a field named as a local", files: file("type T struct{ id string }\n\nfunc byID(dir string) []T { id := p.FolderID(dir); return []T{{id: id}} }\n"), r: owner, }, } }