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.
70 # No dependencies allowed for any of these packages.
72 < constraints, container/list, container/ring,
73 internal/cfg, internal/cpu, internal/goarch,
74 internal/goexperiment, internal/goos,
75 internal/goversion, internal/nettrace,
76 unicode/utf8, unicode/utf16, unicode,
79 # These packages depend only on internal/goarch and unsafe.
80 internal/goarch, unsafe
83 # RUNTIME is the core runtime group of packages, all of them very light-weight.
84 internal/abi, internal/cpu, internal/goarch,
85 internal/goexperiment, internal/goos, unsafe
88 < internal/unsafeheader
89 < runtime/internal/sys
90 < runtime/internal/syscall
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.
215 mime/quotedprintable,
216 net/internal/socktest,
223 # core ones do not use fmt.
229 < encoding/base32, encoding/base64;
231 FMT, encoding < flag;
233 fmt !< encoding/base32, encoding/base64;
235 FMT, encoding/base32, encoding/base64
236 < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
237 encoding/json, encoding/pem, encoding/xml, mime;
242 < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
245 FMT, encoding/binary, math/rand
249 FMT, encoding/binary, hash/adler32, hash/crc32
250 < compress/bzip2, compress/flate, compress/lzw
251 < archive/zip, compress/gzip, compress/zlib;
255 < text/template/parse;
257 net/url, text/template/parse
259 < internal/lazytemplate;
261 encoding/json, html, text/template
268 < internal/lazyregexp;
271 encoding/binary, regexp
275 FMT, encoding/binary, compress/zlib
278 < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
282 # go parser and friends.
287 < go/internal/typeparams
291 < go/build/constraint, go/doc/comment;
293 go/build/constraint, go/doc/comment, go/parser, text/tabwriter
297 go/doc/comment, go/parser, internal/lazyregexp, text/template
303 container/heap, go/constant, go/parser, regexp
306 FMT, internal/goexperiment
309 go/build/constraint, go/doc, go/parser, internal/buildcfg, internal/goroot, internal/goversion
314 < database/sql/internal
315 < database/sql/driver
319 FMT, compress/lzw, compress/zlib
321 < image, image/color/palette
322 < image/internal/imageutil
324 < image/gif, image/jpeg, image/png;
326 # cgo, delayed as long as possible.
327 # If you add a dependency on CGO, you must add the package
328 # to cgoPackages in cmd/dist/test.go as well.
333 < runtime/race, runtime/msan, runtime/asan;
335 # Bulk of the standard library must not use cgo.
336 # The prohibition stops at net and os/user.
337 C !< fmt, go/types, CRYPTO-MATH;
347 < internal/singleflight;
350 < golang.org/x/net/dns/dnsmessage,
351 golang.org/x/net/lif,
352 golang.org/x/net/route;
354 os, runtime, strconv, sync, unsafe,
358 internal/bytealg, internal/intern, internal/itoa, math/bits, sort, strconv
361 # net is unavoidable when doing any networking,
362 # so large dependencies must be kept out.
363 # This is a long-looking list but most of these
364 # are small with few dependencies.
366 golang.org/x/net/dns/dnsmessage,
367 golang.org/x/net/lif,
368 golang.org/x/net/route,
372 internal/singleflight,
379 math/rand !< net; # net uses runtime instead
381 # NET is net plus net-helper packages.
385 mime, net/textproto, net/url
388 # logging - most packages should not import; http and up is allowed
392 log !< crypto/tls, database/sql, go/importer, testing;
400 NONE < crypto/internal/boring/sig, crypto/internal/boring/syso;
401 sync/atomic < crypto/internal/boring/fipstls;
402 crypto/internal/boring/sig, crypto/internal/boring/fipstls < crypto/tls/fipsonly;
404 # CRYPTO is core crypto algorithms - no cgo, fmt, net.
405 # Unfortunately, stuck with reflect via encoding/binary.
406 crypto/internal/boring/sig,
407 crypto/internal/boring/syso,
409 golang.org/x/sys/cpu,
413 < crypto/internal/subtle
414 < crypto/elliptic/internal/fiat
415 < crypto/elliptic/internal/nistec
416 < crypto/ed25519/internal/edwards25519/field, golang.org/x/crypto/curve25519/internal/field
417 < crypto/ed25519/internal/edwards25519
419 < crypto/internal/boring
421 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
422 crypto/sha1, crypto/sha256, crypto/sha512
425 CGO, fmt, net !< CRYPTO;
427 # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
428 CRYPTO, FMT, math/big, embed
429 < crypto/internal/boring/bbig
430 < crypto/internal/randutil
434 < golang.org/x/crypto/cryptobyte/asn1
435 < golang.org/x/crypto/cryptobyte
436 < golang.org/x/crypto/curve25519
437 < crypto/dsa, crypto/elliptic, crypto/rsa
441 CGO, net !< CRYPTO-MATH;
443 # TLS, Prince of Dependencies.
444 CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
445 < golang.org/x/crypto/internal/subtle
446 < golang.org/x/crypto/chacha20
447 < golang.org/x/crypto/internal/poly1305
448 < golang.org/x/crypto/chacha20poly1305
449 < golang.org/x/crypto/hkdf
450 < crypto/x509/internal/macos
453 crypto/internal/boring/fipstls, crypto/x509/pkix
457 # crypto-aware packages
459 DEBUG, go/build, go/types, text/scanner, crypto/md5
461 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
464 NET, crypto/rand, mime/quotedprintable
470 # HTTP, King of Dependencies.
473 < golang.org/x/net/http2/hpack
474 < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
476 FMT, NET, container/list, encoding/binary, log
477 < golang.org/x/text/transform
478 < golang.org/x/text/unicode/norm
479 < golang.org/x/text/unicode/bidi
480 < golang.org/x/text/secure/bidirule
481 < golang.org/x/net/idna
482 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
485 < net/http/httptrace;
488 golang.org/x/net/http/httpguts,
489 golang.org/x/net/http/httpproxy,
490 golang.org/x/net/http2/hpack,
492 net/http/internal/ascii,
493 net/http/internal/testcert,
499 # HTTP-aware packages
501 encoding/json, net/http
504 net/http, net/http/internal/ascii
505 < net/http/cookiejar, net/http/httputil;
515 FMT, compress/gzip, encoding/binary, text/tabwriter
518 OS, compress/gzip, regexp
521 html, internal/profile, net/http, runtime/pprof, runtime/trace
525 encoding/gob, encoding/json, go/token, html/template, net/http
541 FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
544 FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
545 internal/godebug, math/rand, encoding/hex, crypto/sha256
548 internal/fuzz, internal/testlog, runtime/pprof, regexp
549 < testing/internal/testdeps;
551 OS, flag, testing, internal/cfg
555 < internal/obscuretestdata;
558 < os/signal/internal/pty;
560 NET, testing, math/rand
561 < golang.org/x/net/nettest;
564 < os/exec/internal/fdtest;
566 FMT, container/heap, math/rand
570 < internal/diff, internal/txtar;
573 // listStdPkgs returns the same list of packages as "go list std".
574 func listStdPkgs(goroot string) ([]string, error) {
575 // Based on cmd/go's matchPackages function.
578 src := filepath.Join(goroot, "src") + string(filepath.Separator)
579 walkFn := func(path string, d fs.DirEntry, err error) error {
580 if err != nil || !d.IsDir() || path == src {
584 base := filepath.Base(path)
585 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
586 return filepath.SkipDir
589 name := filepath.ToSlash(path[len(src):])
590 if name == "builtin" || name == "cmd" {
591 return filepath.SkipDir
594 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
597 if err := filepath.WalkDir(src, walkFn); err != nil {
603 func TestDependencies(t *testing.T) {
604 if !testenv.HasSrc() {
605 // Tests run in a limited file system and we do not
606 // provide access to every source file.
607 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
611 all, err := listStdPkgs(ctxt.GOROOT)
617 sawImport := map[string]map[string]bool{} // from package => to package => true
618 policy := depsPolicy(t)
620 for _, pkg := range all {
621 imports, err := findImports(pkg)
626 if sawImport[pkg] == nil {
627 sawImport[pkg] = map[string]bool{}
631 for _, imp := range imports {
632 sawImport[pkg][imp] = true
634 bad = append(bad, imp)
638 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
643 var buildIgnore = []byte("\n//go:build ignore")
645 func findImports(pkg string) ([]string, error) {
647 if strings.HasPrefix(pkg, "golang.org") {
648 vpkg = "vendor/" + pkg
650 dir := filepath.Join(Default.GOROOT, "src", vpkg)
651 files, err := os.ReadDir(dir)
656 var haveImport = map[string]bool{}
657 if pkg == "crypto/internal/boring" {
658 haveImport["C"] = true // kludge: prevent C from appearing in crypto/internal/boring imports
660 fset := token.NewFileSet()
661 for _, file := range files {
663 if name == "slice_go14.go" || name == "slice_go18.go" {
664 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
667 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
671 name: filepath.Join(dir, name),
674 f, err := os.Open(info.name)
678 err = readGoInfo(f, &info)
681 return nil, fmt.Errorf("reading %v: %v", name, err)
683 if info.parsed.Name.Name == "main" {
686 if bytes.Contains(info.header, buildIgnore) {
689 for _, imp := range info.imports {
691 if !haveImport[path] {
692 haveImport[path] = true
693 imports = append(imports, path)
697 sort.Strings(imports)
701 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
702 func depsPolicy(t *testing.T) map[string]map[string]bool {
703 allowed := map[string]map[string]bool{"NONE": {}}
704 disallowed := [][2][]string{}
706 parseDepsRules(t, func(deps []string, op string, users []string) {
708 disallowed = append(disallowed, [2][]string{deps, users})
711 for _, u := range users {
712 if allowed[u] != nil {
713 t.Errorf("multiple deps lists for %s", u)
715 allowed[u] = make(map[string]bool)
716 for _, d := range deps {
717 if allowed[d] == nil {
718 t.Errorf("use of %s before its deps list", d)
725 // Check for missing deps info.
726 for _, deps := range allowed {
727 for d := range deps {
728 if allowed[d] == nil {
729 t.Errorf("missing deps list for %s", d)
734 // Complete transitive allowed deps.
735 for k := range allowed {
736 for i := range allowed {
737 for j := range allowed {
738 if i != k && k != j && allowed[i][k] && allowed[k][j] {
740 // Can only happen along with a "use of X before deps" error above,
741 // but this error is more specific - it makes clear that reordering the
742 // rules will not be enough to fix the problem.
743 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
751 // Check negative assertions against completed allowed deps.
752 for _, bad := range disallowed {
753 deps, users := bad[0], bad[1]
754 for _, d := range deps {
755 for _, u := range users {
757 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
770 // parseDepsRules parses depsRules, calling save(deps, op, users)
771 // for each deps < users or deps !< users rule
772 // (op is "<" or "!<").
773 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
774 p := &depsParser{t: t, lineno: 1, text: depsRules}
779 list, tok := p.nextList()
784 p.syntaxError("unexpected EOF")
795 if tok != "<" && tok != "!<" {
796 p.syntaxError("missing <")
802 // A depsParser parses the depsRules syntax described above.
803 type depsParser struct {
810 // syntaxError reports a parsing error.
811 func (p *depsParser) syntaxError(msg string) {
812 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
815 // nextList parses and returns a comma-separated list of names.
816 func (p *depsParser) nextList() (list []string, token string) {
825 case ",", "<", "!<", ";":
826 p.syntaxError("bad list syntax")
828 list = append(list, tok)
837 // nextToken returns the next token in the deps rules,
838 // one of ";" "," "<" "!<" or a name.
839 func (p *depsParser) nextToken() string {
851 if len(p.text) < 2 || p.text[1] != '<' {
852 p.syntaxError("unexpected token !")
858 i := strings.Index(p.text, "\n")
873 i := strings.IndexAny(p.text, "!;,<#\n \t")
885 // TestStdlibLowercase tests that all standard library package names are
886 // lowercase. See Issue 40065.
887 func TestStdlibLowercase(t *testing.T) {
888 if !testenv.HasSrc() {
889 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
893 all, err := listStdPkgs(ctxt.GOROOT)
898 for _, pkgname := range all {
899 if strings.ToLower(pkgname) != pkgname {
900 t.Errorf("package %q should not use upper-case path", pkgname)
905 // TestFindImports tests that findImports works. See #43249.
906 func TestFindImports(t *testing.T) {
907 imports, err := findImports("go/build")
911 t.Logf("go/build imports %q", imports)
912 want := []string{"bytes", "os", "path/filepath", "strings"}
914 for _, w := range want {
915 for _, imp := range imports {
920 t.Errorf("expected to find %q in import list", w)