1 // Copyright 2022 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.
25 // depsRules defines the expected dependencies between packages in
26 // the Go source tree. It is a statement of policy.
28 // DO NOT CHANGE THIS DATA TO FIX BUILDS.
29 // Existing packages should not have their constraints relaxed
30 // without prior discussion.
31 // Negative assertions should almost never be removed.
33 // "a < b" means package b can import package a.
35 // See `go doc internal/dag' for the full syntax.
37 // All-caps names are pseudo-names for specific points
38 // in the dependency lattice.
40 # No dependencies allowed for any of these packages.
42 < constraints, container/list, container/ring,
43 internal/cfg, internal/coverage, internal/coverage/rtcov,
44 internal/coverage/uleb128, internal/coverage/calloc,
45 internal/cpu, internal/goarch,
46 internal/goexperiment, internal/goos,
47 internal/goversion, internal/nettrace, internal/platform,
48 maps, slices, unicode/utf8, unicode/utf16, unicode,
51 # These packages depend only on internal/goarch and unsafe.
52 internal/goarch, unsafe
55 # RUNTIME is the core runtime group of packages, all of them very light-weight.
56 internal/abi, internal/cpu, internal/goarch,
57 internal/coverage/rtcov, internal/goexperiment,
61 < internal/unsafeheader
62 < runtime/internal/sys
63 < runtime/internal/syscall
64 < runtime/internal/atomic
65 < runtime/internal/math
71 < internal/reflectlite
73 < internal/oserror, math/bits
94 # SYSCALL is RUNTIME plus the packages necessary for basic system calls.
95 RUNTIME, unicode/utf8, unicode/utf16
96 < internal/syscall/windows/sysdll, syscall/js
98 < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
99 < internal/syscall/execenv
102 # TIME is SYSCALL plus the core packages about time, including context.
112 # MATH is RUNTIME plus the basic math packages.
133 # STR is basic string and buffer manipulation.
134 RUNTIME, io, unicode/utf8, unicode/utf16, unicode
141 # OS is basic OS access, including helpers (path/filepath, os/exec, etc).
142 # OS includes string routines, but those must be layered above package os.
143 # OS does not include reflection.
147 < internal/safefilepath
154 unicode, fmt !< net, os, os/signal;
160 path/filepath, internal/godebug < os/exec;
162 io/ioutil, os/exec, os/signal
168 < golang.org/x/sys/cpu;
170 # FMT is OS (which includes string routines) plus reflect and fmt.
171 # It does not include package log, which should be avoided in core packages.
172 arena, strconv, unicode
184 # Misc packages needing only FMT.
189 internal/types/errors,
190 mime/quotedprintable,
191 net/internal/socktest,
201 # core ones do not use fmt.
207 < encoding/base32, encoding/base64;
209 FMT, encoding < flag;
211 fmt !< encoding/base32, encoding/base64;
213 FMT, encoding/base32, encoding/base64, internal/saferio
214 < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
215 encoding/json, encoding/pem, encoding/xml, mime;
220 < hash/adler32, hash/crc32, hash/crc64, hash/fnv;
223 FMT, encoding/binary, math/rand
227 FMT, encoding/binary, hash/adler32, hash/crc32
228 < compress/bzip2, compress/flate, compress/lzw
229 < archive/zip, compress/gzip, compress/zlib;
233 < text/template/parse;
235 net/url, text/template/parse
237 < internal/lazytemplate;
239 encoding/json, html, text/template
246 < internal/lazyregexp;
249 encoding/binary, regexp
253 FMT, encoding/binary, compress/zlib, internal/saferio
256 < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
260 # go parser and friends.
265 < go/internal/typeparams
269 < go/build/constraint, go/doc/comment;
271 go/build/constraint, go/doc/comment, go/parser, text/tabwriter
275 go/doc/comment, go/parser, internal/lazyregexp, text/template
281 container/heap, go/constant, go/parser, internal/types/errors, internal/lazyregexp
284 FMT, internal/goexperiment
287 go/build/constraint, go/doc, go/parser, internal/buildcfg, internal/goroot, internal/goversion
292 < database/sql/internal
293 < database/sql/driver
297 FMT, compress/lzw, compress/zlib
299 < image, image/color/palette
300 < image/internal/imageutil
302 < image/gif, image/jpeg, image/png;
304 # cgo, delayed as long as possible.
305 # If you add a dependency on CGO, you must add the package
306 # to cgoPackages in cmd/dist/test.go as well.
311 < runtime/msan, runtime/asan;
314 NONE < runtime/race/internal/amd64v1;
315 NONE < runtime/race/internal/amd64v3;
316 CGO, runtime/race/internal/amd64v1, runtime/race/internal/amd64v3 < runtime/race;
318 # Bulk of the standard library must not use cgo.
319 # The prohibition stops at net and os/user.
320 C !< fmt, go/types, CRYPTO-MATH, log/slog;
330 < internal/singleflight;
333 < golang.org/x/net/dns/dnsmessage,
334 golang.org/x/net/lif,
335 golang.org/x/net/route;
337 os, runtime, strconv, sync, unsafe,
341 internal/bytealg, internal/intern, internal/itoa, math/bits, sort, strconv
344 # net is unavoidable when doing any networking,
345 # so large dependencies must be kept out.
346 # This is a long-looking list but most of these
347 # are small with few dependencies.
349 golang.org/x/net/dns/dnsmessage,
350 golang.org/x/net/lif,
351 golang.org/x/net/route,
355 internal/singleflight,
362 math/rand !< net; # net uses runtime instead
364 # NET is net plus net-helper packages.
368 mime, net/textproto, net/url
371 # logging - most packages should not import; http and up is allowed
375 log, log/slog !< crypto/tls, database/sql, go/importer, testing;
381 < log/slog/internal, log/slog/internal/buffer;
384 encoding, encoding/json,
386 log/slog/internal, log/slog/internal/buffer,
389 < log/slog/internal/testutil;
394 NONE < crypto/internal/boring/sig, crypto/internal/boring/syso;
395 sync/atomic < crypto/internal/boring/bcache, crypto/internal/boring/fipstls;
396 crypto/internal/boring/sig, crypto/internal/boring/fipstls < crypto/tls/fipsonly;
398 # CRYPTO is core crypto algorithms - no cgo, fmt, net.
399 # Unfortunately, stuck with reflect via encoding/binary.
400 crypto/internal/boring/sig,
401 crypto/internal/boring/syso,
403 golang.org/x/sys/cpu,
407 < crypto/internal/alias
411 crypto/internal/boring/bcache
412 < crypto/internal/boring
415 crypto/internal/alias
416 < crypto/internal/randutil
417 < crypto/internal/nistec/fiat
418 < crypto/internal/nistec
419 < crypto/internal/edwards25519/field
420 < crypto/internal/edwards25519;
423 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
424 crypto/sha1, crypto/sha256, crypto/sha512;
426 crypto/boring, crypto/internal/edwards25519/field
433 crypto/internal/edwards25519,
441 CGO, fmt, net !< CRYPTO;
443 # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
444 CRYPTO, FMT, math/big
445 < crypto/internal/boring/bbig
449 < golang.org/x/crypto/cryptobyte/asn1
450 < golang.org/x/crypto/cryptobyte
451 < crypto/internal/bigmod
452 < crypto/dsa, crypto/elliptic, crypto/rsa
456 CGO, net !< CRYPTO-MATH;
458 # TLS, Prince of Dependencies.
459 CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
460 < golang.org/x/crypto/internal/alias
461 < golang.org/x/crypto/internal/subtle
462 < golang.org/x/crypto/chacha20
463 < golang.org/x/crypto/internal/poly1305
464 < golang.org/x/crypto/chacha20poly1305
465 < golang.org/x/crypto/hkdf
466 < crypto/x509/internal/macos
469 crypto/internal/boring/fipstls, crypto/x509/pkix
473 # crypto-aware packages
475 DEBUG, go/build, go/types, text/scanner, crypto/md5
477 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
480 NET, crypto/rand, mime/quotedprintable
487 < hash/maphash; # for purego implementation
489 # HTTP, King of Dependencies.
492 < golang.org/x/net/http2/hpack
493 < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
495 FMT, NET, container/list, encoding/binary, log
496 < golang.org/x/text/transform
497 < golang.org/x/text/unicode/norm
498 < golang.org/x/text/unicode/bidi
499 < golang.org/x/text/secure/bidirule
500 < golang.org/x/net/idna
501 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
504 < net/http/httptrace;
507 golang.org/x/net/http/httpguts,
508 golang.org/x/net/http/httpproxy,
509 golang.org/x/net/http2/hpack,
511 net/http/internal/ascii,
512 net/http/internal/testcert,
518 # HTTP-aware packages
520 encoding/json, net/http
523 net/http, net/http/internal/ascii
524 < net/http/cookiejar, net/http/httputil;
534 FMT, compress/gzip, encoding/binary, text/tabwriter
537 OS, compress/gzip, internal/lazyregexp
540 html, internal/profile, net/http, runtime/pprof, runtime/trace
544 encoding/gob, encoding/json, go/token, html/template, net/http
560 FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
563 FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
564 internal/godebug, math/rand, encoding/hex, crypto/sha256
567 internal/fuzz, internal/testlog, runtime/pprof, regexp
568 < testing/internal/testdeps;
570 OS, flag, testing, internal/cfg, internal/platform, internal/goroot
574 < internal/obscuretestdata;
579 NET, testing, math/rand
580 < golang.org/x/net/nettest;
583 < os/exec/internal/fdtest;
585 FMT, container/heap, math/rand
589 < internal/diff, internal/txtar;
591 FMT, crypto/md5, encoding/binary, regexp, sort, text/tabwriter, unsafe,
592 internal/coverage, internal/coverage/uleb128
593 < internal/coverage/cmerge,
594 internal/coverage/pods,
595 internal/coverage/slicereader,
596 internal/coverage/slicewriter;
598 internal/coverage/slicereader, internal/coverage/slicewriter
599 < internal/coverage/stringtab
600 < internal/coverage/decodecounter, internal/coverage/decodemeta,
601 internal/coverage/encodecounter, internal/coverage/encodemeta;
603 internal/coverage/cmerge
604 < internal/coverage/cformat;
607 internal/coverage/calloc,
608 internal/coverage/cformat,
609 internal/coverage/decodecounter, internal/coverage/decodemeta,
610 internal/coverage/encodecounter, internal/coverage/encodemeta,
611 internal/coverage/pods
615 // listStdPkgs returns the same list of packages as "go list std".
616 func listStdPkgs(goroot string) ([]string, error) {
617 // Based on cmd/go's matchPackages function.
620 src := filepath.Join(goroot, "src") + string(filepath.Separator)
621 walkFn := func(path string, d fs.DirEntry, err error) error {
622 if err != nil || !d.IsDir() || path == src {
626 base := filepath.Base(path)
627 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
628 return filepath.SkipDir
631 name := filepath.ToSlash(path[len(src):])
632 if name == "builtin" || name == "cmd" {
633 return filepath.SkipDir
636 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
639 if err := filepath.WalkDir(src, walkFn); err != nil {
645 func TestDependencies(t *testing.T) {
646 if !testenv.HasSrc() {
647 // Tests run in a limited file system and we do not
648 // provide access to every source file.
649 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
653 all, err := listStdPkgs(ctxt.GOROOT)
659 sawImport := map[string]map[string]bool{} // from package => to package => true
660 policy := depsPolicy(t)
662 for _, pkg := range all {
663 imports, err := findImports(pkg)
668 if sawImport[pkg] == nil {
669 sawImport[pkg] = map[string]bool{}
672 for _, imp := range imports {
673 sawImport[pkg][imp] = true
674 if !policy.HasEdge(pkg, imp) {
675 bad = append(bad, imp)
679 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
684 var buildIgnore = []byte("\n//go:build ignore")
686 func findImports(pkg string) ([]string, error) {
688 if strings.HasPrefix(pkg, "golang.org") {
689 vpkg = "vendor/" + pkg
691 dir := filepath.Join(Default.GOROOT, "src", vpkg)
692 files, err := os.ReadDir(dir)
697 var haveImport = map[string]bool{}
698 if pkg == "crypto/internal/boring" {
699 haveImport["C"] = true // kludge: prevent C from appearing in crypto/internal/boring imports
701 fset := token.NewFileSet()
702 for _, file := range files {
704 if name == "slice_go14.go" || name == "slice_go18.go" {
705 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
708 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
712 name: filepath.Join(dir, name),
715 f, err := os.Open(info.name)
719 err = readGoInfo(f, &info)
722 return nil, fmt.Errorf("reading %v: %v", name, err)
724 if info.parsed.Name.Name == "main" {
727 if bytes.Contains(info.header, buildIgnore) {
730 for _, imp := range info.imports {
732 if !haveImport[path] {
733 haveImport[path] = true
734 imports = append(imports, path)
738 sort.Strings(imports)
742 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
743 func depsPolicy(t *testing.T) *dag.Graph {
744 g, err := dag.Parse(depsRules)
751 // TestStdlibLowercase tests that all standard library package names are
752 // lowercase. See Issue 40065.
753 func TestStdlibLowercase(t *testing.T) {
754 if !testenv.HasSrc() {
755 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
759 all, err := listStdPkgs(ctxt.GOROOT)
764 for _, pkgname := range all {
765 if strings.ToLower(pkgname) != pkgname {
766 t.Errorf("package %q should not use upper-case path", pkgname)
771 // TestFindImports tests that findImports works. See #43249.
772 func TestFindImports(t *testing.T) {
773 imports, err := findImports("go/build")
777 t.Logf("go/build imports %q", imports)
778 want := []string{"bytes", "os", "path/filepath", "strings"}
780 for _, w := range want {
781 for _, imp := range imports {
786 t.Errorf("expected to find %q in import list", w)