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,
75 internal/goversion, internal/nettrace,
76 unicode/utf8, unicode/utf16, unicode,
79 # These packages depend only on unsafe.
83 # RUNTIME is the core runtime group of packages, all of them very light-weight.
84 internal/abi, internal/cpu, unsafe
86 < internal/unsafeheader
87 < runtime/internal/sys
88 < runtime/internal/atomic
89 < runtime/internal/math
94 < internal/reflectlite
96 < internal/oserror, math/bits
109 RUNTIME, unicode/utf8
114 # SYSCALL is RUNTIME plus the packages necessary for basic system calls.
115 RUNTIME, unicode/utf8, unicode/utf16
116 < internal/syscall/windows/sysdll, syscall/js
118 < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
119 < internal/syscall/execenv
122 # TIME is SYSCALL plus the core packages about time, including context.
132 # MATH is RUNTIME plus the basic math packages.
153 # STR is basic string and buffer manipulation.
154 RUNTIME, io, unicode/utf8, unicode/utf16, unicode
161 # OS is basic OS access, including helpers (path/filepath, os/exec, etc).
162 # OS includes string routines, but those must be layered above package os.
163 # OS does not include reflection.
173 unicode, fmt !< os, os/signal;
177 < io/ioutil, os/exec;
179 io/ioutil, os/exec, os/signal
185 < golang.org/x/sys/cpu;
187 # FMT is OS (which includes string routines) plus reflect and fmt.
188 # It does not include package log, which should be avoided in core packages.
207 # Misc packages needing only FMT.
211 mime/quotedprintable,
212 net/internal/socktest,
220 # core ones do not use fmt.
226 < encoding/base32, encoding/base64;
228 fmt !< encoding/base32, encoding/base64;
230 FMT, encoding/base32, encoding/base64
231 < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
232 encoding/json, encoding/pem, encoding/xml, mime;
237 < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
240 FMT, encoding/binary, math/rand
244 FMT, encoding/binary, hash/adler32, hash/crc32
245 < compress/bzip2, compress/flate, compress/lzw
246 < archive/zip, compress/gzip, compress/zlib;
250 < text/template/parse;
252 net/url, text/template/parse
254 < internal/lazytemplate;
256 encoding/json, html, text/template
263 < internal/lazyregexp;
266 encoding/binary, regexp
270 FMT, encoding/binary, compress/zlib
272 < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
275 # go parser and friends.
282 go/parser, text/tabwriter
286 go/parser, internal/lazyregexp, text/template
292 container/heap, go/constant, go/parser, regexp
296 < go/build/constraint;
298 go/doc, go/parser, internal/goroot, internal/goversion
301 DEBUG, go/build, go/types, text/scanner
302 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
307 < database/sql/internal
308 < database/sql/driver
312 FMT, compress/lzw, compress/zlib
314 < image, image/color/palette
315 < image/internal/imageutil
317 < image/gif, image/jpeg, image/png;
319 # cgo, delayed as long as possible.
320 # If you add a dependency on CGO, you must add the package
321 # to cgoPackages in cmd/dist/test.go as well.
326 < runtime/race, runtime/msan;
328 # Bulk of the standard library must not use cgo.
329 # The prohibition stops at net and os/user.
340 < internal/singleflight;
343 < golang.org/x/net/dns/dnsmessage,
344 golang.org/x/net/lif,
345 golang.org/x/net/route;
347 # net is unavoidable when doing any networking,
348 # so large dependencies must be kept out.
349 # This is a long-looking list but most of these
350 # are small with few dependencies.
352 golang.org/x/net/dns/dnsmessage,
353 golang.org/x/net/lif,
354 golang.org/x/net/route,
357 internal/singleflight,
363 math/rand !< net; # net uses runtime instead
365 # NET is net plus net-helper packages.
369 mime, net/textproto, net/url
372 # logging - most packages should not import; http and up is allowed
376 log !< crypto/tls, database/sql, go/importer, testing;
384 NONE < crypto/internal/boring/sig;
385 sync/atomic < crypto/internal/boring/fipstls;
387 encoding/binary, golang.org/x/sys/cpu, hash,
389 CGO, crypto/internal/boring/sig, crypto/internal/boring/fipstls
392 < crypto/internal/subtle
395 < crypto/internal/boring
396 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
397 crypto/sha1, crypto/sha256, crypto/sha512
399 < crypto/internal/randutil
400 < crypto/ed25519/internal/edwards25519
402 < golang.org/x/crypto/cryptobyte/asn1
403 < golang.org/x/crypto/cryptobyte
404 < golang.org/x/crypto/curve25519
405 < crypto/dsa, crypto/elliptic, crypto/rsa
409 net !< CRYPTO-BORING;
411 # TLS, Prince of Dependencies.
412 CRYPTO-BORING, NET, container/list, encoding/hex, encoding/pem
413 < golang.org/x/crypto/internal/subtle
414 < golang.org/x/crypto/chacha20
415 < golang.org/x/crypto/poly1305
416 < golang.org/x/crypto/chacha20poly1305
417 < golang.org/x/crypto/hkdf
418 < crypto/x509/internal/macos
423 crypto/internal/boring/sig, crypto/internal/boring/fipstls
424 < crypto/tls/fipsonly;
426 crypto/internal/boring
429 # crypto-aware packages
431 NET, crypto/rand, mime/quotedprintable
437 # HTTP, King of Dependencies.
440 < golang.org/x/net/http2/hpack, net/http/internal;
442 FMT, NET, container/list, encoding/binary, log
443 < golang.org/x/text/transform
444 < golang.org/x/text/unicode/norm
445 < golang.org/x/text/unicode/bidi
446 < golang.org/x/text/secure/bidirule
447 < golang.org/x/net/idna
448 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
451 < net/http/httptrace;
454 golang.org/x/net/http/httpguts,
455 golang.org/x/net/http/httpproxy,
456 golang.org/x/net/http2/hpack,
463 # HTTP-aware packages
465 encoding/json, net/http
469 < net/http/cookiejar, net/http/httputil;
479 FMT, compress/gzip, encoding/binary, text/tabwriter
482 OS, compress/gzip, regexp
485 html, internal/profile, net/http, runtime/pprof, runtime/trace
489 encoding/gob, encoding/json, go/token, html/template, net/http
505 FMT, flag, runtime/debug, runtime/trace, internal/sysinfo
508 internal/testlog, runtime/pprof, regexp
509 < testing/internal/testdeps;
511 OS, flag, testing, internal/cfg
515 < internal/obscuretestdata;
518 < os/signal/internal/pty;
520 NET, testing, math/rand
521 < golang.org/x/net/nettest;
523 FMT, container/heap, math/rand
527 // listStdPkgs returns the same list of packages as "go list std".
528 func listStdPkgs(goroot string) ([]string, error) {
529 // Based on cmd/go's matchPackages function.
532 src := filepath.Join(goroot, "src") + string(filepath.Separator)
533 walkFn := func(path string, d fs.DirEntry, err error) error {
534 if err != nil || !d.IsDir() || path == src {
538 base := filepath.Base(path)
539 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
540 return filepath.SkipDir
543 name := filepath.ToSlash(path[len(src):])
544 if name == "builtin" || name == "cmd" {
545 return filepath.SkipDir
548 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
551 if err := filepath.WalkDir(src, walkFn); err != nil {
557 func TestDependencies(t *testing.T) {
558 if !testenv.HasSrc() {
559 // Tests run in a limited file system and we do not
560 // provide access to every source file.
561 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
565 all, err := listStdPkgs(ctxt.GOROOT)
571 sawImport := map[string]map[string]bool{} // from package => to package => true
572 policy := depsPolicy(t)
574 for _, pkg := range all {
575 imports, err := findImports(pkg)
580 if sawImport[pkg] == nil {
581 sawImport[pkg] = map[string]bool{}
585 for _, imp := range imports {
586 sawImport[pkg][imp] = true
588 bad = append(bad, imp)
592 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
596 // depPath returns the path between the given from and to packages.
597 // It returns the empty string if there's no dependency path.
598 var depPath func(string, string) string
599 depPath = func(from, to string) string {
600 if sawImport[from][to] {
601 return from + " => " + to
603 for pkg := range sawImport[from] {
604 if p := depPath(pkg, to); p != "" {
605 return from + " => " + p
612 var buildIgnore = []byte("\n// +build ignore")
614 func findImports(pkg string) ([]string, error) {
616 if strings.HasPrefix(pkg, "golang.org") {
617 vpkg = "vendor/" + pkg
619 dir := filepath.Join(Default.GOROOT, "src", vpkg)
620 files, err := os.ReadDir(dir)
625 var haveImport = map[string]bool{}
626 fset := token.NewFileSet()
627 for _, file := range files {
629 if name == "slice_go14.go" || name == "slice_go18.go" {
630 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
633 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
637 name: filepath.Join(dir, name),
640 f, err := os.Open(info.name)
644 err = readGoInfo(f, &info)
647 return nil, fmt.Errorf("reading %v: %v", name, err)
649 if bytes.Contains(info.header, buildIgnore) {
652 for _, imp := range info.imports {
654 if !haveImport[path] {
655 haveImport[path] = true
656 imports = append(imports, path)
660 sort.Strings(imports)
664 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
665 func depsPolicy(t *testing.T) map[string]map[string]bool {
666 allowed := map[string]map[string]bool{"NONE": {}}
667 disallowed := [][2][]string{}
669 parseDepsRules(t, func(deps []string, op string, users []string) {
671 disallowed = append(disallowed, [2][]string{deps, users})
674 for _, u := range users {
675 if allowed[u] != nil {
676 t.Errorf("multiple deps lists for %s", u)
678 allowed[u] = make(map[string]bool)
679 for _, d := range deps {
680 if allowed[d] == nil {
681 t.Errorf("use of %s before its deps list", d)
688 // Check for missing deps info.
689 for _, deps := range allowed {
690 for d := range deps {
691 if allowed[d] == nil {
692 t.Errorf("missing deps list for %s", d)
697 // Complete transitive allowed deps.
698 for k := range allowed {
699 for i := range allowed {
700 for j := range allowed {
701 if i != k && k != j && allowed[i][k] && allowed[k][j] {
703 // Can only happen along with a "use of X before deps" error above,
704 // but this error is more specific - it makes clear that reordering the
705 // rules will not be enough to fix the problem.
706 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
714 // Check negative assertions against completed allowed deps.
715 for _, bad := range disallowed {
716 deps, users := bad[0], bad[1]
717 for _, d := range deps {
718 for _, u := range users {
720 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
733 // parseDepsRules parses depsRules, calling save(deps, op, users)
734 // for each deps < users or deps !< users rule
735 // (op is "<" or "!<").
736 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
737 p := &depsParser{t: t, lineno: 1, text: depsRules}
742 list, tok := p.nextList()
747 p.syntaxError("unexpected EOF")
758 if tok != "<" && tok != "!<" {
759 p.syntaxError("missing <")
765 // A depsParser parses the depsRules syntax described above.
766 type depsParser struct {
773 // syntaxError reports a parsing error.
774 func (p *depsParser) syntaxError(msg string) {
775 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
778 // nextList parses and returns a comma-separated list of names.
779 func (p *depsParser) nextList() (list []string, token string) {
788 case ",", "<", "!<", ";":
789 p.syntaxError("bad list syntax")
791 list = append(list, tok)
800 // nextToken returns the next token in the deps rules,
801 // one of ";" "," "<" "!<" or a name.
802 func (p *depsParser) nextToken() string {
814 if len(p.text) < 2 || p.text[1] != '<' {
815 p.syntaxError("unexpected token !")
821 i := strings.Index(p.text, "\n")
836 i := strings.IndexAny(p.text, "!;,<#\n \t")
848 // TestStdlibLowercase tests that all standard library package names are
849 // lowercase. See Issue 40065.
850 func TestStdlibLowercase(t *testing.T) {
851 if !testenv.HasSrc() {
852 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
856 all, err := listStdPkgs(ctxt.GOROOT)
861 for _, pkgname := range all {
862 if strings.ToLower(pkgname) != pkgname {
863 t.Errorf("package %q should not use upper-case path", pkgname)
868 // TestFindImports tests that findImports works. See #43249.
869 func TestFindImports(t *testing.T) {
870 imports, err := findImports("go/build")
874 t.Logf("go/build imports %q", imports)
875 want := []string{"bytes", "os", "path/filepath", "strings"}
877 for _, w := range want {
878 for _, imp := range imports {
883 t.Errorf("expected to find %q in import list", w)