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, embed
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/internal/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;
549 < os/exec/internal/fdtest;
551 FMT, container/heap, math/rand
555 // listStdPkgs returns the same list of packages as "go list std".
556 func listStdPkgs(goroot string) ([]string, error) {
557 // Based on cmd/go's matchPackages function.
560 src := filepath.Join(goroot, "src") + string(filepath.Separator)
561 walkFn := func(path string, d fs.DirEntry, err error) error {
562 if err != nil || !d.IsDir() || path == src {
566 base := filepath.Base(path)
567 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
568 return filepath.SkipDir
571 name := filepath.ToSlash(path[len(src):])
572 if name == "builtin" || name == "cmd" {
573 return filepath.SkipDir
576 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
579 if err := filepath.WalkDir(src, walkFn); err != nil {
585 func TestDependencies(t *testing.T) {
586 if !testenv.HasSrc() {
587 // Tests run in a limited file system and we do not
588 // provide access to every source file.
589 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
593 all, err := listStdPkgs(ctxt.GOROOT)
599 sawImport := map[string]map[string]bool{} // from package => to package => true
600 policy := depsPolicy(t)
602 for _, pkg := range all {
603 imports, err := findImports(pkg)
608 if sawImport[pkg] == nil {
609 sawImport[pkg] = map[string]bool{}
613 for _, imp := range imports {
614 sawImport[pkg][imp] = true
616 bad = append(bad, imp)
620 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
624 // depPath returns the path between the given from and to packages.
625 // It returns the empty string if there's no dependency path.
626 var depPath func(string, string) string
627 depPath = func(from, to string) string {
628 if sawImport[from][to] {
629 return from + " => " + to
631 for pkg := range sawImport[from] {
632 if p := depPath(pkg, to); p != "" {
633 return from + " => " + p
640 var buildIgnore = []byte("\n//go:build ignore")
642 func findImports(pkg string) ([]string, error) {
644 if strings.HasPrefix(pkg, "golang.org") {
645 vpkg = "vendor/" + pkg
647 dir := filepath.Join(Default.GOROOT, "src", vpkg)
648 files, err := os.ReadDir(dir)
653 var haveImport = map[string]bool{}
654 fset := token.NewFileSet()
655 for _, file := range files {
657 if name == "slice_go14.go" || name == "slice_go18.go" {
658 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
661 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
665 name: filepath.Join(dir, name),
668 f, err := os.Open(info.name)
672 err = readGoInfo(f, &info)
675 return nil, fmt.Errorf("reading %v: %v", name, err)
677 if info.parsed.Name.Name == "main" {
680 if bytes.Contains(info.header, buildIgnore) {
683 for _, imp := range info.imports {
685 if !haveImport[path] {
686 haveImport[path] = true
687 imports = append(imports, path)
691 sort.Strings(imports)
695 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
696 func depsPolicy(t *testing.T) map[string]map[string]bool {
697 allowed := map[string]map[string]bool{"NONE": {}}
698 disallowed := [][2][]string{}
700 parseDepsRules(t, func(deps []string, op string, users []string) {
702 disallowed = append(disallowed, [2][]string{deps, users})
705 for _, u := range users {
706 if allowed[u] != nil {
707 t.Errorf("multiple deps lists for %s", u)
709 allowed[u] = make(map[string]bool)
710 for _, d := range deps {
711 if allowed[d] == nil {
712 t.Errorf("use of %s before its deps list", d)
719 // Check for missing deps info.
720 for _, deps := range allowed {
721 for d := range deps {
722 if allowed[d] == nil {
723 t.Errorf("missing deps list for %s", d)
728 // Complete transitive allowed deps.
729 for k := range allowed {
730 for i := range allowed {
731 for j := range allowed {
732 if i != k && k != j && allowed[i][k] && allowed[k][j] {
734 // Can only happen along with a "use of X before deps" error above,
735 // but this error is more specific - it makes clear that reordering the
736 // rules will not be enough to fix the problem.
737 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
745 // Check negative assertions against completed allowed deps.
746 for _, bad := range disallowed {
747 deps, users := bad[0], bad[1]
748 for _, d := range deps {
749 for _, u := range users {
751 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
764 // parseDepsRules parses depsRules, calling save(deps, op, users)
765 // for each deps < users or deps !< users rule
766 // (op is "<" or "!<").
767 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
768 p := &depsParser{t: t, lineno: 1, text: depsRules}
773 list, tok := p.nextList()
778 p.syntaxError("unexpected EOF")
789 if tok != "<" && tok != "!<" {
790 p.syntaxError("missing <")
796 // A depsParser parses the depsRules syntax described above.
797 type depsParser struct {
804 // syntaxError reports a parsing error.
805 func (p *depsParser) syntaxError(msg string) {
806 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
809 // nextList parses and returns a comma-separated list of names.
810 func (p *depsParser) nextList() (list []string, token string) {
819 case ",", "<", "!<", ";":
820 p.syntaxError("bad list syntax")
822 list = append(list, tok)
831 // nextToken returns the next token in the deps rules,
832 // one of ";" "," "<" "!<" or a name.
833 func (p *depsParser) nextToken() string {
845 if len(p.text) < 2 || p.text[1] != '<' {
846 p.syntaxError("unexpected token !")
852 i := strings.Index(p.text, "\n")
867 i := strings.IndexAny(p.text, "!;,<#\n \t")
879 // TestStdlibLowercase tests that all standard library package names are
880 // lowercase. See Issue 40065.
881 func TestStdlibLowercase(t *testing.T) {
882 if !testenv.HasSrc() {
883 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
887 all, err := listStdPkgs(ctxt.GOROOT)
892 for _, pkgname := range all {
893 if strings.ToLower(pkgname) != pkgname {
894 t.Errorf("package %q should not use upper-case path", pkgname)
899 // TestFindImports tests that findImports works. See #43249.
900 func TestFindImports(t *testing.T) {
901 imports, err := findImports("go/build")
905 t.Logf("go/build imports %q", imports)
906 want := []string{"bytes", "os", "path/filepath", "strings"}
908 for _, w := range want {
909 for _, imp := range imports {
914 t.Errorf("expected to find %q in import list", w)