1 // Copyright 2012 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.
5 // This file exercises the import parser but also checks that
6 // some low-level packages do not have new dependencies added.
24 // depsRules defines the expected dependencies between packages in
25 // the Go source tree. It is a statement of policy.
27 // DO NOT CHANGE THIS DATA TO FIX BUILDS.
28 // Existing packages should not have their constraints relaxed
29 // without prior discussion.
30 // Negative assertions should almost never be removed.
32 // The general syntax of a rule is:
36 // which means c and d come after a and b in the partial order
37 // (that is, c and d can import a and b),
38 // but doesn't provide a relative order between a vs b or c vs d.
40 // The rules can chain together, as in:
44 // which is equivalent to
49 // Except for the special bottom element "NONE", each name
50 // must appear exactly once on the right-hand side of a rule.
51 // That rule serves as the definition of the allowed dependencies
52 // for that name. The definition must appear before any uses
53 // of the name on the left-hand side of a rule. (That is, the
54 // rules themselves must be ordered according to the partial
55 // order, for easier reading by people.)
57 // Negative assertions double-check the partial order:
61 // means that it must NOT be the case that i < j.
62 // Negative assertions may appear anywhere in the rules,
63 // even before i and j have been defined.
65 // Comments begin with #.
67 // All-caps names are pseudo-names for specific points
68 // in the dependency lattice.
71 # No dependencies allowed for any of these packages.
73 < container/list, container/ring,
74 internal/cfg, internal/cpu, internal/goarch,
75 internal/goexperiment, internal/goos,
76 internal/goversion, internal/nettrace,
77 unicode/utf8, unicode/utf16, unicode,
80 # These packages depend only on internal/goarch and unsafe.
81 internal/goarch, unsafe
84 # RUNTIME is the core runtime group of packages, all of them very light-weight.
85 internal/abi, internal/cpu, internal/goarch,
86 internal/goexperiment, internal/goos, unsafe
89 < internal/unsafeheader
90 < runtime/internal/sys
91 < runtime/internal/atomic
92 < runtime/internal/math
97 < internal/reflectlite
99 < internal/oserror, math/bits
112 RUNTIME, unicode/utf8
117 # SYSCALL is RUNTIME plus the packages necessary for basic system calls.
118 RUNTIME, unicode/utf8, unicode/utf16
119 < internal/syscall/windows/sysdll, syscall/js
121 < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
122 < internal/syscall/execenv
125 # TIME is SYSCALL plus the core packages about time, including context.
135 # MATH is RUNTIME plus the basic math packages.
156 # STR is basic string and buffer manipulation.
157 RUNTIME, io, unicode/utf8, unicode/utf16, unicode
164 # OS is basic OS access, including helpers (path/filepath, os/exec, etc).
165 # OS includes string routines, but those must be layered above package os.
166 # OS does not include reflection.
176 unicode, fmt !< os, os/signal;
180 < io/ioutil, os/exec;
182 io/ioutil, os/exec, os/signal
188 < golang.org/x/sys/cpu;
190 # FMT is OS (which includes string routines) plus reflect and fmt.
191 # It does not include package log, which should be avoided in core packages.
210 # Misc packages needing only FMT.
214 mime/quotedprintable,
215 net/internal/socktest,
223 # core ones do not use fmt.
229 < encoding/base32, encoding/base64;
231 fmt !< encoding/base32, encoding/base64;
233 FMT, encoding/base32, encoding/base64
234 < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
235 encoding/json, encoding/pem, encoding/xml, mime;
240 < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
243 FMT, encoding/binary, math/rand
247 FMT, encoding/binary, hash/adler32, hash/crc32
248 < compress/bzip2, compress/flate, compress/lzw
249 < archive/zip, compress/gzip, compress/zlib;
253 < text/template/parse;
255 net/url, text/template/parse
257 < internal/lazytemplate;
259 encoding/json, html, text/template
266 < internal/lazyregexp;
269 encoding/binary, regexp
273 FMT, encoding/binary, compress/zlib
275 < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
278 # go parser and friends.
283 < go/internal/typeparams
287 < go/build/constraint;
289 go/build/constraint, go/parser, text/tabwriter
293 go/parser, internal/lazyregexp, text/template
299 container/heap, go/constant, go/parser, regexp
302 FMT, internal/goexperiment
305 go/build/constraint, go/doc, go/parser, internal/buildcfg, internal/goroot, internal/goversion
308 DEBUG, go/build, go/types, text/scanner
309 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
314 < database/sql/internal
315 < database/sql/driver
319 FMT, compress/lzw, compress/zlib
321 < image, image/color/palette
322 < image/internal/imageutil
324 < image/gif, image/jpeg, image/png;
326 # cgo, delayed as long as possible.
327 # If you add a dependency on CGO, you must add the package
328 # to cgoPackages in cmd/dist/test.go as well.
333 < runtime/race, runtime/msan;
335 # Bulk of the standard library must not use cgo.
336 # The prohibition stops at net and os/user.
347 < internal/singleflight;
350 < golang.org/x/net/dns/dnsmessage,
351 golang.org/x/net/lif,
352 golang.org/x/net/route;
354 # net is unavoidable when doing any networking,
355 # so large dependencies must be kept out.
356 # This is a long-looking list but most of these
357 # are small with few dependencies.
359 golang.org/x/net/dns/dnsmessage,
360 golang.org/x/net/lif,
361 golang.org/x/net/route,
364 internal/singleflight,
370 math/rand !< net; # net uses runtime instead
372 # NET is net plus net-helper packages.
376 mime, net/textproto, net/url
379 # logging - most packages should not import; http and up is allowed
383 log !< crypto/tls, database/sql, go/importer, testing;
391 NONE < crypto/internal/boring/sig;
392 sync/atomic < crypto/internal/boring/fipstls;
394 encoding/binary, golang.org/x/sys/cpu, hash,
396 CGO, crypto/internal/boring/sig, crypto/internal/boring/fipstls
399 < crypto/internal/subtle
400 < crypto/elliptic/internal/fiat
401 < crypto/ed25519/internal/edwards25519/field
402 < crypto/ed25519/internal/edwards25519
405 < crypto/internal/boring
406 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
407 crypto/sha1, crypto/sha256, crypto/sha512
409 < crypto/internal/randutil
411 < golang.org/x/crypto/cryptobyte/asn1
412 < golang.org/x/crypto/cryptobyte
413 < golang.org/x/crypto/curve25519
414 < crypto/dsa, crypto/elliptic, crypto/rsa
418 net !< CRYPTO-BORING;
420 # TLS, Prince of Dependencies.
421 CRYPTO-BORING, NET, container/list, encoding/hex, encoding/pem
422 < golang.org/x/crypto/internal/subtle
423 < golang.org/x/crypto/chacha20
424 < golang.org/x/crypto/poly1305
425 < golang.org/x/crypto/chacha20poly1305
426 < golang.org/x/crypto/hkdf
427 < crypto/x509/internal/macos
432 crypto/internal/boring/sig, crypto/internal/boring/fipstls
433 < crypto/tls/fipsonly;
435 crypto/internal/boring
438 # crypto-aware packages
440 NET, crypto/rand, mime/quotedprintable
446 # HTTP, King of Dependencies.
449 < golang.org/x/net/http2/hpack
450 < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
452 FMT, NET, container/list, encoding/binary, log
453 < golang.org/x/text/transform
454 < golang.org/x/text/unicode/norm
455 < golang.org/x/text/unicode/bidi
456 < golang.org/x/text/secure/bidirule
457 < golang.org/x/net/idna
458 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
461 < net/http/httptrace;
464 golang.org/x/net/http/httpguts,
465 golang.org/x/net/http/httpproxy,
466 golang.org/x/net/http2/hpack,
468 net/http/internal/ascii,
469 net/http/internal/testcert,
475 # HTTP-aware packages
477 encoding/json, net/http
480 net/http, net/http/internal/ascii
481 < net/http/cookiejar, net/http/httputil;
491 FMT, compress/gzip, encoding/binary, text/tabwriter
494 OS, compress/gzip, regexp
497 html, internal/profile, net/http, runtime/pprof, runtime/trace
501 encoding/gob, encoding/json, go/token, html/template, net/http
517 FMT, flag, runtime/debug, runtime/trace, internal/sysinfo, math/rand
520 internal/testlog, runtime/pprof, regexp
521 < testing/internal/testdeps;
523 OS, flag, testing, internal/cfg
527 < internal/obscuretestdata;
530 < os/signal/internal/pty;
532 NET, testing, math/rand
533 < golang.org/x/net/nettest;
535 FMT, container/heap, math/rand
539 // listStdPkgs returns the same list of packages as "go list std".
540 func listStdPkgs(goroot string) ([]string, error) {
541 // Based on cmd/go's matchPackages function.
544 src := filepath.Join(goroot, "src") + string(filepath.Separator)
545 walkFn := func(path string, d fs.DirEntry, err error) error {
546 if err != nil || !d.IsDir() || path == src {
550 base := filepath.Base(path)
551 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
552 return filepath.SkipDir
555 name := filepath.ToSlash(path[len(src):])
556 if name == "builtin" || name == "cmd" {
557 return filepath.SkipDir
560 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
563 if err := filepath.WalkDir(src, walkFn); err != nil {
569 func TestDependencies(t *testing.T) {
570 if !testenv.HasSrc() {
571 // Tests run in a limited file system and we do not
572 // provide access to every source file.
573 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
577 all, err := listStdPkgs(ctxt.GOROOT)
583 sawImport := map[string]map[string]bool{} // from package => to package => true
584 policy := depsPolicy(t)
586 for _, pkg := range all {
587 imports, err := findImports(pkg)
592 if sawImport[pkg] == nil {
593 sawImport[pkg] = map[string]bool{}
597 for _, imp := range imports {
598 sawImport[pkg][imp] = true
600 bad = append(bad, imp)
604 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
608 // depPath returns the path between the given from and to packages.
609 // It returns the empty string if there's no dependency path.
610 var depPath func(string, string) string
611 depPath = func(from, to string) string {
612 if sawImport[from][to] {
613 return from + " => " + to
615 for pkg := range sawImport[from] {
616 if p := depPath(pkg, to); p != "" {
617 return from + " => " + p
624 var buildIgnore = []byte("\n// +build ignore")
626 func findImports(pkg string) ([]string, error) {
628 if strings.HasPrefix(pkg, "golang.org") {
629 vpkg = "vendor/" + pkg
631 dir := filepath.Join(Default.GOROOT, "src", vpkg)
632 files, err := os.ReadDir(dir)
637 var haveImport = map[string]bool{}
638 fset := token.NewFileSet()
639 for _, file := range files {
641 if name == "slice_go14.go" || name == "slice_go18.go" {
642 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
645 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
649 name: filepath.Join(dir, name),
652 f, err := os.Open(info.name)
656 err = readGoInfo(f, &info)
659 return nil, fmt.Errorf("reading %v: %v", name, err)
661 if bytes.Contains(info.header, buildIgnore) {
664 for _, imp := range info.imports {
666 if !haveImport[path] {
667 haveImport[path] = true
668 imports = append(imports, path)
672 sort.Strings(imports)
676 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
677 func depsPolicy(t *testing.T) map[string]map[string]bool {
678 allowed := map[string]map[string]bool{"NONE": {}}
679 disallowed := [][2][]string{}
681 parseDepsRules(t, func(deps []string, op string, users []string) {
683 disallowed = append(disallowed, [2][]string{deps, users})
686 for _, u := range users {
687 if allowed[u] != nil {
688 t.Errorf("multiple deps lists for %s", u)
690 allowed[u] = make(map[string]bool)
691 for _, d := range deps {
692 if allowed[d] == nil {
693 t.Errorf("use of %s before its deps list", d)
700 // Check for missing deps info.
701 for _, deps := range allowed {
702 for d := range deps {
703 if allowed[d] == nil {
704 t.Errorf("missing deps list for %s", d)
709 // Complete transitive allowed deps.
710 for k := range allowed {
711 for i := range allowed {
712 for j := range allowed {
713 if i != k && k != j && allowed[i][k] && allowed[k][j] {
715 // Can only happen along with a "use of X before deps" error above,
716 // but this error is more specific - it makes clear that reordering the
717 // rules will not be enough to fix the problem.
718 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
726 // Check negative assertions against completed allowed deps.
727 for _, bad := range disallowed {
728 deps, users := bad[0], bad[1]
729 for _, d := range deps {
730 for _, u := range users {
732 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
745 // parseDepsRules parses depsRules, calling save(deps, op, users)
746 // for each deps < users or deps !< users rule
747 // (op is "<" or "!<").
748 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
749 p := &depsParser{t: t, lineno: 1, text: depsRules}
754 list, tok := p.nextList()
759 p.syntaxError("unexpected EOF")
770 if tok != "<" && tok != "!<" {
771 p.syntaxError("missing <")
777 // A depsParser parses the depsRules syntax described above.
778 type depsParser struct {
785 // syntaxError reports a parsing error.
786 func (p *depsParser) syntaxError(msg string) {
787 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
790 // nextList parses and returns a comma-separated list of names.
791 func (p *depsParser) nextList() (list []string, token string) {
800 case ",", "<", "!<", ";":
801 p.syntaxError("bad list syntax")
803 list = append(list, tok)
812 // nextToken returns the next token in the deps rules,
813 // one of ";" "," "<" "!<" or a name.
814 func (p *depsParser) nextToken() string {
826 if len(p.text) < 2 || p.text[1] != '<' {
827 p.syntaxError("unexpected token !")
833 i := strings.Index(p.text, "\n")
848 i := strings.IndexAny(p.text, "!;,<#\n \t")
860 // TestStdlibLowercase tests that all standard library package names are
861 // lowercase. See Issue 40065.
862 func TestStdlibLowercase(t *testing.T) {
863 if !testenv.HasSrc() {
864 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
868 all, err := listStdPkgs(ctxt.GOROOT)
873 for _, pkgname := range all {
874 if strings.ToLower(pkgname) != pkgname {
875 t.Errorf("package %q should not use upper-case path", pkgname)
880 // TestFindImports tests that findImports works. See #43249.
881 func TestFindImports(t *testing.T) {
882 imports, err := findImports("go/build")
886 t.Logf("go/build imports %q", imports)
887 want := []string{"bytes", "os", "path/filepath", "strings"}
889 for _, w := range want {
890 for _, imp := range imports {
895 t.Errorf("expected to find %q in import list", w)