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 < constraints, 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 !< net, os, os/signal;
180 < io/ioutil, os/exec;
182 io/ioutil, os/exec, os/signal
188 < golang.org/x/sys/cpu;
190 os < internal/godebug;
192 # FMT is OS (which includes string routines) plus reflect and fmt.
193 # It does not include package log, which should be avoided in core packages.
212 # Misc packages needing only FMT.
216 mime/quotedprintable,
217 net/internal/socktest,
224 # core ones do not use fmt.
230 < encoding/base32, encoding/base64;
232 fmt !< encoding/base32, encoding/base64;
234 FMT, encoding/base32, encoding/base64
235 < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
236 encoding/json, encoding/pem, encoding/xml, mime;
241 < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
244 FMT, encoding/binary, math/rand
248 FMT, encoding/binary, hash/adler32, hash/crc32
249 < compress/bzip2, compress/flate, compress/lzw
250 < archive/zip, compress/gzip, compress/zlib;
254 < text/template/parse;
256 net/url, text/template/parse
258 < internal/lazytemplate;
260 encoding/json, html, text/template
267 < internal/lazyregexp;
270 encoding/binary, regexp
274 FMT, encoding/binary, compress/zlib
277 < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
281 # go parser and friends.
286 < go/internal/typeparams
290 < go/build/constraint;
292 go/build/constraint, go/parser, text/tabwriter
296 go/parser, internal/lazyregexp, text/template
302 container/heap, go/constant, go/parser, regexp
305 FMT, internal/goexperiment
308 go/build/constraint, go/doc, go/parser, internal/buildcfg, internal/goroot, internal/goversion
311 DEBUG, go/build, go/types, text/scanner
312 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
317 < database/sql/internal
318 < database/sql/driver
322 FMT, compress/lzw, compress/zlib
324 < image, image/color/palette
325 < image/internal/imageutil
327 < image/gif, image/jpeg, image/png;
329 # cgo, delayed as long as possible.
330 # If you add a dependency on CGO, you must add the package
331 # to cgoPackages in cmd/dist/test.go as well.
336 < runtime/race, runtime/msan, runtime/asan;
338 # Bulk of the standard library must not use cgo.
339 # The prohibition stops at net and os/user.
340 C !< fmt, go/types, CRYPTO-MATH;
350 < internal/singleflight;
353 < golang.org/x/net/dns/dnsmessage,
354 golang.org/x/net/lif,
355 golang.org/x/net/route;
357 os, runtime, strconv, sync, unsafe,
361 internal/bytealg, internal/intern, internal/itoa, math/bits, sort, strconv
364 # net is unavoidable when doing any networking,
365 # so large dependencies must be kept out.
366 # This is a long-looking list but most of these
367 # are small with few dependencies.
369 golang.org/x/net/dns/dnsmessage,
370 golang.org/x/net/lif,
371 golang.org/x/net/route,
375 internal/singleflight,
382 math/rand !< net; # net uses runtime instead
384 # NET is net plus net-helper packages.
388 mime, net/textproto, net/url
391 # logging - most packages should not import; http and up is allowed
395 log !< crypto/tls, database/sql, go/importer, testing;
403 # CRYPTO is core crypto algorithms - no cgo, fmt, net.
404 # Unfortunately, stuck with reflect via encoding/binary.
405 encoding/binary, golang.org/x/sys/cpu, hash
408 < crypto/internal/subtle
409 < crypto/elliptic/internal/fiat
410 < crypto/elliptic/internal/nistec
411 < crypto/ed25519/internal/edwards25519/field, golang.org/x/crypto/curve25519/internal/field
412 < crypto/ed25519/internal/edwards25519
414 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
415 crypto/sha1, crypto/sha256, crypto/sha512
418 CGO, fmt, net !< CRYPTO;
420 # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
421 CRYPTO, FMT, math/big
423 < crypto/internal/randutil
426 < golang.org/x/crypto/cryptobyte/asn1
427 < golang.org/x/crypto/cryptobyte
428 < golang.org/x/crypto/curve25519
429 < crypto/dsa, crypto/elliptic, crypto/rsa
433 CGO, net !< CRYPTO-MATH;
435 # TLS, Prince of Dependencies.
436 CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
437 < golang.org/x/crypto/internal/subtle
438 < golang.org/x/crypto/chacha20
439 < golang.org/x/crypto/poly1305
440 < golang.org/x/crypto/chacha20poly1305
441 < golang.org/x/crypto/hkdf
442 < crypto/x509/internal/macos
447 # crypto-aware packages
449 NET, crypto/rand, mime/quotedprintable
455 # HTTP, King of Dependencies.
458 < golang.org/x/net/http2/hpack
459 < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
461 FMT, NET, container/list, encoding/binary, log
462 < golang.org/x/text/transform
463 < golang.org/x/text/unicode/norm
464 < golang.org/x/text/unicode/bidi
465 < golang.org/x/text/secure/bidirule
466 < golang.org/x/net/idna
467 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
470 < net/http/httptrace;
473 golang.org/x/net/http/httpguts,
474 golang.org/x/net/http/httpproxy,
475 golang.org/x/net/http2/hpack,
477 net/http/internal/ascii,
478 net/http/internal/testcert,
484 # HTTP-aware packages
486 encoding/json, net/http
489 net/http, net/http/internal/ascii
490 < net/http/cookiejar, net/http/httputil;
500 FMT, compress/gzip, encoding/binary, text/tabwriter
503 OS, compress/gzip, regexp
506 html, internal/profile, net/http, runtime/pprof, runtime/trace
510 encoding/gob, encoding/json, go/token, html/template, net/http
526 FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
529 FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
530 internal/godebug, math/rand, encoding/hex, crypto/sha256
533 internal/fuzz, internal/testlog, runtime/pprof, regexp
534 < testing/internal/testdeps;
536 OS, flag, testing, internal/cfg
540 < internal/obscuretestdata;
543 < os/signal/internal/pty;
545 NET, testing, math/rand
546 < golang.org/x/net/nettest;
548 FMT, container/heap, math/rand
552 // listStdPkgs returns the same list of packages as "go list std".
553 func listStdPkgs(goroot string) ([]string, error) {
554 // Based on cmd/go's matchPackages function.
557 src := filepath.Join(goroot, "src") + string(filepath.Separator)
558 walkFn := func(path string, d fs.DirEntry, err error) error {
559 if err != nil || !d.IsDir() || path == src {
563 base := filepath.Base(path)
564 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
565 return filepath.SkipDir
568 name := filepath.ToSlash(path[len(src):])
569 if name == "builtin" || name == "cmd" {
570 return filepath.SkipDir
573 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
576 if err := filepath.WalkDir(src, walkFn); err != nil {
582 func TestDependencies(t *testing.T) {
583 if !testenv.HasSrc() {
584 // Tests run in a limited file system and we do not
585 // provide access to every source file.
586 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
590 all, err := listStdPkgs(ctxt.GOROOT)
596 sawImport := map[string]map[string]bool{} // from package => to package => true
597 policy := depsPolicy(t)
599 for _, pkg := range all {
600 imports, err := findImports(pkg)
605 if sawImport[pkg] == nil {
606 sawImport[pkg] = map[string]bool{}
610 for _, imp := range imports {
611 sawImport[pkg][imp] = true
613 bad = append(bad, imp)
617 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
621 // depPath returns the path between the given from and to packages.
622 // It returns the empty string if there's no dependency path.
623 var depPath func(string, string) string
624 depPath = func(from, to string) string {
625 if sawImport[from][to] {
626 return from + " => " + to
628 for pkg := range sawImport[from] {
629 if p := depPath(pkg, to); p != "" {
630 return from + " => " + p
637 var buildIgnore = []byte("\n//go:build ignore")
639 func findImports(pkg string) ([]string, error) {
641 if strings.HasPrefix(pkg, "golang.org") {
642 vpkg = "vendor/" + pkg
644 dir := filepath.Join(Default.GOROOT, "src", vpkg)
645 files, err := os.ReadDir(dir)
650 var haveImport = map[string]bool{}
651 fset := token.NewFileSet()
652 for _, file := range files {
654 if name == "slice_go14.go" || name == "slice_go18.go" {
655 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
658 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
662 name: filepath.Join(dir, name),
665 f, err := os.Open(info.name)
669 err = readGoInfo(f, &info)
672 return nil, fmt.Errorf("reading %v: %v", name, err)
674 if info.parsed.Name.Name == "main" {
677 if bytes.Contains(info.header, buildIgnore) {
680 for _, imp := range info.imports {
682 if !haveImport[path] {
683 haveImport[path] = true
684 imports = append(imports, path)
688 sort.Strings(imports)
692 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
693 func depsPolicy(t *testing.T) map[string]map[string]bool {
694 allowed := map[string]map[string]bool{"NONE": {}}
695 disallowed := [][2][]string{}
697 parseDepsRules(t, func(deps []string, op string, users []string) {
699 disallowed = append(disallowed, [2][]string{deps, users})
702 for _, u := range users {
703 if allowed[u] != nil {
704 t.Errorf("multiple deps lists for %s", u)
706 allowed[u] = make(map[string]bool)
707 for _, d := range deps {
708 if allowed[d] == nil {
709 t.Errorf("use of %s before its deps list", d)
716 // Check for missing deps info.
717 for _, deps := range allowed {
718 for d := range deps {
719 if allowed[d] == nil {
720 t.Errorf("missing deps list for %s", d)
725 // Complete transitive allowed deps.
726 for k := range allowed {
727 for i := range allowed {
728 for j := range allowed {
729 if i != k && k != j && allowed[i][k] && allowed[k][j] {
731 // Can only happen along with a "use of X before deps" error above,
732 // but this error is more specific - it makes clear that reordering the
733 // rules will not be enough to fix the problem.
734 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
742 // Check negative assertions against completed allowed deps.
743 for _, bad := range disallowed {
744 deps, users := bad[0], bad[1]
745 for _, d := range deps {
746 for _, u := range users {
748 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
761 // parseDepsRules parses depsRules, calling save(deps, op, users)
762 // for each deps < users or deps !< users rule
763 // (op is "<" or "!<").
764 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
765 p := &depsParser{t: t, lineno: 1, text: depsRules}
770 list, tok := p.nextList()
775 p.syntaxError("unexpected EOF")
786 if tok != "<" && tok != "!<" {
787 p.syntaxError("missing <")
793 // A depsParser parses the depsRules syntax described above.
794 type depsParser struct {
801 // syntaxError reports a parsing error.
802 func (p *depsParser) syntaxError(msg string) {
803 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
806 // nextList parses and returns a comma-separated list of names.
807 func (p *depsParser) nextList() (list []string, token string) {
816 case ",", "<", "!<", ";":
817 p.syntaxError("bad list syntax")
819 list = append(list, tok)
828 // nextToken returns the next token in the deps rules,
829 // one of ";" "," "<" "!<" or a name.
830 func (p *depsParser) nextToken() string {
842 if len(p.text) < 2 || p.text[1] != '<' {
843 p.syntaxError("unexpected token !")
849 i := strings.Index(p.text, "\n")
864 i := strings.IndexAny(p.text, "!;,<#\n \t")
876 // TestStdlibLowercase tests that all standard library package names are
877 // lowercase. See Issue 40065.
878 func TestStdlibLowercase(t *testing.T) {
879 if !testenv.HasSrc() {
880 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
884 all, err := listStdPkgs(ctxt.GOROOT)
889 for _, pkgname := range all {
890 if strings.ToLower(pkgname) != pkgname {
891 t.Errorf("package %q should not use upper-case path", pkgname)
896 // TestFindImports tests that findImports works. See #43249.
897 func TestFindImports(t *testing.T) {
898 imports, err := findImports("go/build")
902 t.Logf("go/build imports %q", imports)
903 want := []string{"bytes", "os", "path/filepath", "strings"}
905 for _, w := range want {
906 for _, imp := range imports {
911 t.Errorf("expected to find %q in import list", w)