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.
206 # Misc packages needing only FMT.
210 mime/quotedprintable,
211 net/internal/socktest,
218 # core ones do not use fmt.
224 < encoding/base32, encoding/base64;
226 FMT, encoding < flag;
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
273 < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
277 # go parser and friends.
282 < go/internal/typeparams
286 < go/build/constraint, go/doc/comment;
288 go/build/constraint, go/doc/comment, go/parser, text/tabwriter
292 go/doc/comment, go/parser, internal/lazyregexp, text/template
298 container/heap, go/constant, go/parser, regexp
301 FMT, internal/goexperiment
304 go/build/constraint, go/doc, go/parser, internal/buildcfg, internal/goroot, internal/goversion
309 < database/sql/internal
310 < database/sql/driver
314 FMT, compress/lzw, compress/zlib
316 < image, image/color/palette
317 < image/internal/imageutil
319 < image/gif, image/jpeg, image/png;
321 # cgo, delayed as long as possible.
322 # If you add a dependency on CGO, you must add the package
323 # to cgoPackages in cmd/dist/test.go as well.
328 < runtime/race, runtime/msan, runtime/asan;
330 # Bulk of the standard library must not use cgo.
331 # The prohibition stops at net and os/user.
332 C !< fmt, go/types, CRYPTO-MATH;
342 < internal/singleflight;
345 < golang.org/x/net/dns/dnsmessage,
346 golang.org/x/net/lif,
347 golang.org/x/net/route;
349 os, runtime, strconv, sync, unsafe,
353 internal/bytealg, internal/intern, internal/itoa, math/bits, sort, strconv
356 # net is unavoidable when doing any networking,
357 # so large dependencies must be kept out.
358 # This is a long-looking list but most of these
359 # are small with few dependencies.
361 golang.org/x/net/dns/dnsmessage,
362 golang.org/x/net/lif,
363 golang.org/x/net/route,
367 internal/singleflight,
374 math/rand !< net; # net uses runtime instead
376 # NET is net plus net-helper packages.
380 mime, net/textproto, net/url
383 # logging - most packages should not import; http and up is allowed
387 log !< crypto/tls, database/sql, go/importer, testing;
395 NONE < crypto/internal/boring/sig, crypto/internal/boring/syso;
396 sync/atomic < crypto/internal/boring/fipstls;
397 crypto/internal/boring/sig, crypto/internal/boring/fipstls < crypto/tls/fipsonly;
399 # CRYPTO is core crypto algorithms - no cgo, fmt, net.
400 # Unfortunately, stuck with reflect via encoding/binary.
401 crypto/internal/boring/sig,
402 crypto/internal/boring/syso,
404 golang.org/x/sys/cpu,
408 < crypto/internal/subtle
409 < crypto/internal/nistec/fiat
410 < crypto/internal/nistec
411 < crypto/internal/edwards25519/field, golang.org/x/crypto/curve25519/internal/field
412 < crypto/internal/edwards25519
414 < crypto/internal/boring
416 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
417 crypto/sha1, crypto/sha256, crypto/sha512
420 CGO, fmt, net !< CRYPTO;
422 # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
423 CRYPTO, FMT, math/big, embed
424 < crypto/internal/boring/bbig
425 < crypto/internal/randutil
429 < golang.org/x/crypto/cryptobyte/asn1
430 < golang.org/x/crypto/cryptobyte
431 < golang.org/x/crypto/curve25519
432 < crypto/dsa, crypto/elliptic, crypto/rsa
436 CGO, net !< CRYPTO-MATH;
438 # TLS, Prince of Dependencies.
439 CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
440 < golang.org/x/crypto/internal/subtle
441 < golang.org/x/crypto/chacha20
442 < golang.org/x/crypto/internal/poly1305
443 < golang.org/x/crypto/chacha20poly1305
444 < golang.org/x/crypto/hkdf
445 < crypto/x509/internal/macos
448 crypto/internal/boring/fipstls, crypto/x509/pkix
452 # crypto-aware packages
454 DEBUG, go/build, go/types, text/scanner, crypto/md5
456 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
459 NET, crypto/rand, mime/quotedprintable
465 # HTTP, King of Dependencies.
468 < golang.org/x/net/http2/hpack
469 < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
471 FMT, NET, container/list, encoding/binary, log
472 < golang.org/x/text/transform
473 < golang.org/x/text/unicode/norm
474 < golang.org/x/text/unicode/bidi
475 < golang.org/x/text/secure/bidirule
476 < golang.org/x/net/idna
477 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
480 < net/http/httptrace;
483 golang.org/x/net/http/httpguts,
484 golang.org/x/net/http/httpproxy,
485 golang.org/x/net/http2/hpack,
487 net/http/internal/ascii,
488 net/http/internal/testcert,
494 # HTTP-aware packages
496 encoding/json, net/http
499 net/http, net/http/internal/ascii
500 < net/http/cookiejar, net/http/httputil;
510 FMT, compress/gzip, encoding/binary, text/tabwriter
513 OS, compress/gzip, regexp
516 html, internal/profile, net/http, runtime/pprof, runtime/trace
520 encoding/gob, encoding/json, go/token, html/template, net/http
536 FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
539 FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
540 internal/godebug, math/rand, encoding/hex, crypto/sha256
543 internal/fuzz, internal/testlog, runtime/pprof, regexp
544 < testing/internal/testdeps;
546 OS, flag, testing, internal/cfg
550 < internal/obscuretestdata;
553 < os/signal/internal/pty;
555 NET, testing, math/rand
556 < golang.org/x/net/nettest;
559 < os/exec/internal/fdtest;
561 FMT, container/heap, math/rand
565 < internal/diff, internal/txtar;
568 // listStdPkgs returns the same list of packages as "go list std".
569 func listStdPkgs(goroot string) ([]string, error) {
570 // Based on cmd/go's matchPackages function.
573 src := filepath.Join(goroot, "src") + string(filepath.Separator)
574 walkFn := func(path string, d fs.DirEntry, err error) error {
575 if err != nil || !d.IsDir() || path == src {
579 base := filepath.Base(path)
580 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
581 return filepath.SkipDir
584 name := filepath.ToSlash(path[len(src):])
585 if name == "builtin" || name == "cmd" {
586 return filepath.SkipDir
589 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
592 if err := filepath.WalkDir(src, walkFn); err != nil {
598 func TestDependencies(t *testing.T) {
599 if !testenv.HasSrc() {
600 // Tests run in a limited file system and we do not
601 // provide access to every source file.
602 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
606 all, err := listStdPkgs(ctxt.GOROOT)
612 sawImport := map[string]map[string]bool{} // from package => to package => true
613 policy := depsPolicy(t)
615 for _, pkg := range all {
616 imports, err := findImports(pkg)
621 if sawImport[pkg] == nil {
622 sawImport[pkg] = map[string]bool{}
626 for _, imp := range imports {
627 sawImport[pkg][imp] = true
629 bad = append(bad, imp)
633 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
638 var buildIgnore = []byte("\n//go:build ignore")
640 func findImports(pkg string) ([]string, error) {
642 if strings.HasPrefix(pkg, "golang.org") {
643 vpkg = "vendor/" + pkg
645 dir := filepath.Join(Default.GOROOT, "src", vpkg)
646 files, err := os.ReadDir(dir)
651 var haveImport = map[string]bool{}
652 if pkg == "crypto/internal/boring" {
653 haveImport["C"] = true // kludge: prevent C from appearing in crypto/internal/boring imports
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)