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.
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;
403 encoding/binary, golang.org/x/sys/cpu, hash,
404 FMT, math/big, embed,
405 CGO, crypto/internal/boring/sig, crypto/internal/boring/fipstls, crypto/internal/boring/syso
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
415 < crypto/internal/boring
416 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
417 crypto/sha1, crypto/sha256, crypto/sha512
418 < crypto/internal/randutil
421 < golang.org/x/crypto/cryptobyte/asn1
422 < golang.org/x/crypto/cryptobyte
423 < golang.org/x/crypto/curve25519
424 < crypto/dsa, crypto/elliptic, crypto/rsa
428 net !< CRYPTO-BORING;
430 # TLS, Prince of Dependencies.
431 CRYPTO-BORING, NET, container/list, encoding/hex, encoding/pem
432 < golang.org/x/crypto/internal/subtle
433 < golang.org/x/crypto/chacha20
434 < golang.org/x/crypto/internal/poly1305
435 < golang.org/x/crypto/chacha20poly1305
436 < golang.org/x/crypto/hkdf
437 < crypto/x509/internal/macos
442 crypto/internal/boring/sig, crypto/internal/boring/fipstls
443 < crypto/tls/fipsonly;
445 crypto/internal/boring
448 # crypto-aware packages
450 CRYPTO-BORING, DEBUG, go/build, go/types, text/scanner
452 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
455 NET, crypto/rand, mime/quotedprintable
461 # HTTP, King of Dependencies.
464 < golang.org/x/net/http2/hpack
465 < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
467 FMT, NET, container/list, encoding/binary, log
468 < golang.org/x/text/transform
469 < golang.org/x/text/unicode/norm
470 < golang.org/x/text/unicode/bidi
471 < golang.org/x/text/secure/bidirule
472 < golang.org/x/net/idna
473 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
476 < net/http/httptrace;
479 golang.org/x/net/http/httpguts,
480 golang.org/x/net/http/httpproxy,
481 golang.org/x/net/http2/hpack,
483 net/http/internal/ascii,
484 net/http/internal/testcert,
490 # HTTP-aware packages
492 encoding/json, net/http
495 net/http, net/http/internal/ascii
496 < net/http/cookiejar, net/http/httputil;
506 FMT, compress/gzip, encoding/binary, text/tabwriter
509 OS, compress/gzip, regexp
512 html, internal/profile, net/http, runtime/pprof, runtime/trace
516 encoding/gob, encoding/json, go/token, html/template, net/http
532 FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
535 FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
536 internal/godebug, math/rand, encoding/hex, crypto/sha256
539 internal/fuzz, internal/testlog, runtime/pprof, regexp
540 < testing/internal/testdeps;
542 OS, flag, testing, internal/cfg
546 < internal/obscuretestdata;
549 < os/signal/internal/pty;
551 NET, testing, math/rand
552 < golang.org/x/net/nettest;
555 < os/exec/internal/fdtest;
557 FMT, container/heap, math/rand
561 < internal/diff, internal/txtar;
564 // listStdPkgs returns the same list of packages as "go list std".
565 func listStdPkgs(goroot string) ([]string, error) {
566 // Based on cmd/go's matchPackages function.
569 src := filepath.Join(goroot, "src") + string(filepath.Separator)
570 walkFn := func(path string, d fs.DirEntry, err error) error {
571 if err != nil || !d.IsDir() || path == src {
575 base := filepath.Base(path)
576 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
577 return filepath.SkipDir
580 name := filepath.ToSlash(path[len(src):])
581 if name == "builtin" || name == "cmd" {
582 return filepath.SkipDir
585 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
588 if err := filepath.WalkDir(src, walkFn); err != nil {
594 func TestDependencies(t *testing.T) {
595 if !testenv.HasSrc() {
596 // Tests run in a limited file system and we do not
597 // provide access to every source file.
598 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
602 all, err := listStdPkgs(ctxt.GOROOT)
608 sawImport := map[string]map[string]bool{} // from package => to package => true
609 policy := depsPolicy(t)
611 for _, pkg := range all {
612 imports, err := findImports(pkg)
617 if sawImport[pkg] == nil {
618 sawImport[pkg] = map[string]bool{}
622 for _, imp := range imports {
623 sawImport[pkg][imp] = true
625 bad = append(bad, imp)
629 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
634 var buildIgnore = []byte("\n//go:build ignore")
636 func findImports(pkg string) ([]string, error) {
638 if strings.HasPrefix(pkg, "golang.org") {
639 vpkg = "vendor/" + pkg
641 dir := filepath.Join(Default.GOROOT, "src", vpkg)
642 files, err := os.ReadDir(dir)
647 var haveImport = map[string]bool{}
648 fset := token.NewFileSet()
649 for _, file := range files {
651 if name == "slice_go14.go" || name == "slice_go18.go" {
652 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
655 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
659 name: filepath.Join(dir, name),
662 f, err := os.Open(info.name)
666 err = readGoInfo(f, &info)
669 return nil, fmt.Errorf("reading %v: %v", name, err)
671 if info.parsed.Name.Name == "main" {
674 if bytes.Contains(info.header, buildIgnore) {
677 for _, imp := range info.imports {
679 if !haveImport[path] {
680 haveImport[path] = true
681 imports = append(imports, path)
685 sort.Strings(imports)
689 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
690 func depsPolicy(t *testing.T) map[string]map[string]bool {
691 allowed := map[string]map[string]bool{"NONE": {}}
692 disallowed := [][2][]string{}
694 parseDepsRules(t, func(deps []string, op string, users []string) {
696 disallowed = append(disallowed, [2][]string{deps, users})
699 for _, u := range users {
700 if allowed[u] != nil {
701 t.Errorf("multiple deps lists for %s", u)
703 allowed[u] = make(map[string]bool)
704 for _, d := range deps {
705 if allowed[d] == nil {
706 t.Errorf("use of %s before its deps list", d)
713 // Check for missing deps info.
714 for _, deps := range allowed {
715 for d := range deps {
716 if allowed[d] == nil {
717 t.Errorf("missing deps list for %s", d)
722 // Complete transitive allowed deps.
723 for k := range allowed {
724 for i := range allowed {
725 for j := range allowed {
726 if i != k && k != j && allowed[i][k] && allowed[k][j] {
728 // Can only happen along with a "use of X before deps" error above,
729 // but this error is more specific - it makes clear that reordering the
730 // rules will not be enough to fix the problem.
731 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
739 // Check negative assertions against completed allowed deps.
740 for _, bad := range disallowed {
741 deps, users := bad[0], bad[1]
742 for _, d := range deps {
743 for _, u := range users {
745 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
758 // parseDepsRules parses depsRules, calling save(deps, op, users)
759 // for each deps < users or deps !< users rule
760 // (op is "<" or "!<").
761 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
762 p := &depsParser{t: t, lineno: 1, text: depsRules}
767 list, tok := p.nextList()
772 p.syntaxError("unexpected EOF")
783 if tok != "<" && tok != "!<" {
784 p.syntaxError("missing <")
790 // A depsParser parses the depsRules syntax described above.
791 type depsParser struct {
798 // syntaxError reports a parsing error.
799 func (p *depsParser) syntaxError(msg string) {
800 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
803 // nextList parses and returns a comma-separated list of names.
804 func (p *depsParser) nextList() (list []string, token string) {
813 case ",", "<", "!<", ";":
814 p.syntaxError("bad list syntax")
816 list = append(list, tok)
825 // nextToken returns the next token in the deps rules,
826 // one of ";" "," "<" "!<" or a name.
827 func (p *depsParser) nextToken() string {
839 if len(p.text) < 2 || p.text[1] != '<' {
840 p.syntaxError("unexpected token !")
846 i := strings.Index(p.text, "\n")
861 i := strings.IndexAny(p.text, "!;,<#\n \t")
873 // TestStdlibLowercase tests that all standard library package names are
874 // lowercase. See Issue 40065.
875 func TestStdlibLowercase(t *testing.T) {
876 if !testenv.HasSrc() {
877 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
881 all, err := listStdPkgs(ctxt.GOROOT)
886 for _, pkgname := range all {
887 if strings.ToLower(pkgname) != pkgname {
888 t.Errorf("package %q should not use upper-case path", pkgname)
893 // TestFindImports tests that findImports works. See #43249.
894 func TestFindImports(t *testing.T) {
895 imports, err := findImports("go/build")
899 t.Logf("go/build imports %q", imports)
900 want := []string{"bytes", "os", "path/filepath", "strings"}
902 for _, w := range want {
903 for _, imp := range imports {
908 t.Errorf("expected to find %q in import list", w)