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.
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 NONE < crypto/internal/boring/sig;
404 sync/atomic < crypto/internal/boring/fipstls;
406 encoding/binary, golang.org/x/sys/cpu, hash,
408 CGO, crypto/internal/boring/sig, crypto/internal/boring/fipstls
411 < crypto/internal/subtle
412 < crypto/elliptic/internal/fiat
413 < crypto/elliptic/internal/nistec
414 < crypto/ed25519/internal/edwards25519/field, golang.org/x/crypto/curve25519/internal/field
415 < crypto/ed25519/internal/edwards25519
418 < crypto/internal/boring
419 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
420 crypto/sha1, crypto/sha256, crypto/sha512
422 < crypto/internal/randutil
424 < golang.org/x/crypto/cryptobyte/asn1
425 < golang.org/x/crypto/cryptobyte
426 < golang.org/x/crypto/curve25519
427 < crypto/dsa, crypto/elliptic, crypto/rsa
431 net !< CRYPTO-BORING;
433 # TLS, Prince of Dependencies.
434 CRYPTO-BORING, NET, container/list, encoding/hex, encoding/pem
435 < golang.org/x/crypto/internal/subtle
436 < golang.org/x/crypto/chacha20
437 < golang.org/x/crypto/poly1305
438 < golang.org/x/crypto/chacha20poly1305
439 < golang.org/x/crypto/hkdf
440 < crypto/x509/internal/macos
445 crypto/internal/boring/sig, crypto/internal/boring/fipstls
446 < crypto/tls/fipsonly;
448 crypto/internal/boring
451 # crypto-aware packages
453 NET, crypto/rand, mime/quotedprintable
459 # HTTP, King of Dependencies.
462 < golang.org/x/net/http2/hpack
463 < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
465 FMT, NET, container/list, encoding/binary, log
466 < golang.org/x/text/transform
467 < golang.org/x/text/unicode/norm
468 < golang.org/x/text/unicode/bidi
469 < golang.org/x/text/secure/bidirule
470 < golang.org/x/net/idna
471 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
474 < net/http/httptrace;
477 golang.org/x/net/http/httpguts,
478 golang.org/x/net/http/httpproxy,
479 golang.org/x/net/http2/hpack,
481 net/http/internal/ascii,
482 net/http/internal/testcert,
488 # HTTP-aware packages
490 encoding/json, net/http
493 net/http, net/http/internal/ascii
494 < net/http/cookiejar, net/http/httputil;
504 FMT, compress/gzip, encoding/binary, text/tabwriter
507 OS, compress/gzip, regexp
510 html, internal/profile, net/http, runtime/pprof, runtime/trace
514 encoding/gob, encoding/json, go/token, html/template, net/http
530 FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
533 FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
534 internal/godebug, math/rand, encoding/hex, crypto/sha256
537 internal/fuzz, internal/testlog, runtime/pprof, regexp
538 < testing/internal/testdeps;
540 OS, flag, testing, internal/cfg
544 < internal/obscuretestdata;
547 < os/signal/internal/pty;
549 NET, testing, math/rand
550 < golang.org/x/net/nettest;
552 FMT, container/heap, math/rand
556 // listStdPkgs returns the same list of packages as "go list std".
557 func listStdPkgs(goroot string) ([]string, error) {
558 // Based on cmd/go's matchPackages function.
561 src := filepath.Join(goroot, "src") + string(filepath.Separator)
562 walkFn := func(path string, d fs.DirEntry, err error) error {
563 if err != nil || !d.IsDir() || path == src {
567 base := filepath.Base(path)
568 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
569 return filepath.SkipDir
572 name := filepath.ToSlash(path[len(src):])
573 if name == "builtin" || name == "cmd" {
574 return filepath.SkipDir
577 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
580 if err := filepath.WalkDir(src, walkFn); err != nil {
586 func TestDependencies(t *testing.T) {
587 if !testenv.HasSrc() {
588 // Tests run in a limited file system and we do not
589 // provide access to every source file.
590 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
594 all, err := listStdPkgs(ctxt.GOROOT)
600 sawImport := map[string]map[string]bool{} // from package => to package => true
601 policy := depsPolicy(t)
603 for _, pkg := range all {
604 imports, err := findImports(pkg)
609 if sawImport[pkg] == nil {
610 sawImport[pkg] = map[string]bool{}
614 for _, imp := range imports {
615 sawImport[pkg][imp] = true
617 bad = append(bad, imp)
621 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
625 // depPath returns the path between the given from and to packages.
626 // It returns the empty string if there's no dependency path.
627 var depPath func(string, string) string
628 depPath = func(from, to string) string {
629 if sawImport[from][to] {
630 return from + " => " + to
632 for pkg := range sawImport[from] {
633 if p := depPath(pkg, to); p != "" {
634 return from + " => " + p
641 var buildIgnore = []byte("\n//go:build ignore")
643 func findImports(pkg string) ([]string, error) {
645 if strings.HasPrefix(pkg, "golang.org") {
646 vpkg = "vendor/" + pkg
648 dir := filepath.Join(Default.GOROOT, "src", vpkg)
649 files, err := os.ReadDir(dir)
654 var haveImport = map[string]bool{}
655 fset := token.NewFileSet()
656 for _, file := range files {
658 if name == "slice_go14.go" || name == "slice_go18.go" {
659 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
662 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
666 name: filepath.Join(dir, name),
669 f, err := os.Open(info.name)
673 err = readGoInfo(f, &info)
676 return nil, fmt.Errorf("reading %v: %v", name, err)
678 if info.parsed.Name.Name == "main" {
681 if bytes.Contains(info.header, buildIgnore) {
684 for _, imp := range info.imports {
686 if !haveImport[path] {
687 haveImport[path] = true
688 imports = append(imports, path)
692 sort.Strings(imports)
696 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
697 func depsPolicy(t *testing.T) map[string]map[string]bool {
698 allowed := map[string]map[string]bool{"NONE": {}}
699 disallowed := [][2][]string{}
701 parseDepsRules(t, func(deps []string, op string, users []string) {
703 disallowed = append(disallowed, [2][]string{deps, users})
706 for _, u := range users {
707 if allowed[u] != nil {
708 t.Errorf("multiple deps lists for %s", u)
710 allowed[u] = make(map[string]bool)
711 for _, d := range deps {
712 if allowed[d] == nil {
713 t.Errorf("use of %s before its deps list", d)
720 // Check for missing deps info.
721 for _, deps := range allowed {
722 for d := range deps {
723 if allowed[d] == nil {
724 t.Errorf("missing deps list for %s", d)
729 // Complete transitive allowed deps.
730 for k := range allowed {
731 for i := range allowed {
732 for j := range allowed {
733 if i != k && k != j && allowed[i][k] && allowed[k][j] {
735 // Can only happen along with a "use of X before deps" error above,
736 // but this error is more specific - it makes clear that reordering the
737 // rules will not be enough to fix the problem.
738 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
746 // Check negative assertions against completed allowed deps.
747 for _, bad := range disallowed {
748 deps, users := bad[0], bad[1]
749 for _, d := range deps {
750 for _, u := range users {
752 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
765 // parseDepsRules parses depsRules, calling save(deps, op, users)
766 // for each deps < users or deps !< users rule
767 // (op is "<" or "!<").
768 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
769 p := &depsParser{t: t, lineno: 1, text: depsRules}
774 list, tok := p.nextList()
779 p.syntaxError("unexpected EOF")
790 if tok != "<" && tok != "!<" {
791 p.syntaxError("missing <")
797 // A depsParser parses the depsRules syntax described above.
798 type depsParser struct {
805 // syntaxError reports a parsing error.
806 func (p *depsParser) syntaxError(msg string) {
807 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
810 // nextList parses and returns a comma-separated list of names.
811 func (p *depsParser) nextList() (list []string, token string) {
820 case ",", "<", "!<", ";":
821 p.syntaxError("bad list syntax")
823 list = append(list, tok)
832 // nextToken returns the next token in the deps rules,
833 // one of ";" "," "<" "!<" or a name.
834 func (p *depsParser) nextToken() string {
846 if len(p.text) < 2 || p.text[1] != '<' {
847 p.syntaxError("unexpected token !")
853 i := strings.Index(p.text, "\n")
868 i := strings.IndexAny(p.text, "!;,<#\n \t")
880 // TestStdlibLowercase tests that all standard library package names are
881 // lowercase. See Issue 40065.
882 func TestStdlibLowercase(t *testing.T) {
883 if !testenv.HasSrc() {
884 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
888 all, err := listStdPkgs(ctxt.GOROOT)
893 for _, pkgname := range all {
894 if strings.ToLower(pkgname) != pkgname {
895 t.Errorf("package %q should not use upper-case path", pkgname)
900 // TestFindImports tests that findImports works. See #43249.
901 func TestFindImports(t *testing.T) {
902 imports, err := findImports("go/build")
906 t.Logf("go/build imports %q", imports)
907 want := []string{"bytes", "os", "path/filepath", "strings"}
909 for _, w := range want {
910 for _, imp := range imports {
915 t.Errorf("expected to find %q in import list", w)