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, internal/goexperiment,
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, internal/goexperiment, unsafe
87 < internal/unsafeheader
88 < runtime/internal/sys
89 < runtime/internal/atomic
90 < runtime/internal/math
95 < internal/reflectlite
97 < internal/oserror, math/bits
110 RUNTIME, unicode/utf8
115 # SYSCALL is RUNTIME plus the packages necessary for basic system calls.
116 RUNTIME, unicode/utf8, unicode/utf16
117 < internal/syscall/windows/sysdll, syscall/js
119 < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
120 < internal/syscall/execenv
123 # TIME is SYSCALL plus the core packages about time, including context.
133 # MATH is RUNTIME plus the basic math packages.
154 # STR is basic string and buffer manipulation.
155 RUNTIME, io, unicode/utf8, unicode/utf16, unicode
162 # OS is basic OS access, including helpers (path/filepath, os/exec, etc).
163 # OS includes string routines, but those must be layered above package os.
164 # OS does not include reflection.
174 unicode, fmt !< os, os/signal;
178 < io/ioutil, os/exec;
180 io/ioutil, os/exec, os/signal
186 < golang.org/x/sys/cpu;
188 # FMT is OS (which includes string routines) plus reflect and fmt.
189 # It does not include package log, which should be avoided in core packages.
208 # Misc packages needing only FMT.
212 mime/quotedprintable,
213 net/internal/socktest,
221 # core ones do not use fmt.
227 < encoding/base32, encoding/base64;
229 fmt !< encoding/base32, encoding/base64;
231 FMT, encoding/base32, encoding/base64
232 < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
233 encoding/json, encoding/pem, encoding/xml, mime;
238 < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
241 FMT, encoding/binary, math/rand
245 FMT, encoding/binary, hash/adler32, hash/crc32
246 < compress/bzip2, compress/flate, compress/lzw
247 < archive/zip, compress/gzip, compress/zlib;
251 < text/template/parse;
253 net/url, text/template/parse
255 < internal/lazytemplate;
257 encoding/json, html, text/template
264 < internal/lazyregexp;
267 encoding/binary, regexp
271 FMT, encoding/binary, compress/zlib
273 < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
276 # go parser and friends.
281 < go/internal/typeparams
285 < go/build/constraint;
287 go/build/constraint, go/parser, text/tabwriter
291 go/parser, internal/lazyregexp, text/template
297 container/heap, go/constant, go/parser, regexp
300 FMT, internal/goexperiment
303 go/build/constraint, go/doc, go/parser, internal/buildcfg, internal/goroot, internal/goversion
306 DEBUG, go/build, go/types, text/scanner
307 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
312 < database/sql/internal
313 < database/sql/driver
317 FMT, compress/lzw, compress/zlib
319 < image, image/color/palette
320 < image/internal/imageutil
322 < image/gif, image/jpeg, image/png;
324 # cgo, delayed as long as possible.
325 # If you add a dependency on CGO, you must add the package
326 # to cgoPackages in cmd/dist/test.go as well.
331 < runtime/race, runtime/msan;
333 # Bulk of the standard library must not use cgo.
334 # The prohibition stops at net and os/user.
335 C !< fmt, go/types, CRYPTO-MATH;
345 < internal/singleflight;
348 < golang.org/x/net/dns/dnsmessage,
349 golang.org/x/net/lif,
350 golang.org/x/net/route;
352 # net is unavoidable when doing any networking,
353 # so large dependencies must be kept out.
354 # This is a long-looking list but most of these
355 # are small with few dependencies.
357 golang.org/x/net/dns/dnsmessage,
358 golang.org/x/net/lif,
359 golang.org/x/net/route,
362 internal/singleflight,
368 math/rand !< net; # net uses runtime instead
370 # NET is net plus net-helper packages.
374 mime, net/textproto, net/url
377 # logging - most packages should not import; http and up is allowed
381 log !< crypto/tls, database/sql, go/importer, testing;
389 # CRYPTO is core crypto algorithms - no cgo, fmt, net.
390 # Unfortunately, stuck with reflect via encoding/binary.
391 encoding/binary, golang.org/x/sys/cpu, hash
394 < crypto/internal/subtle
395 < crypto/elliptic/internal/fiat
396 < crypto/ed25519/internal/edwards25519/field
397 < crypto/ed25519/internal/edwards25519
399 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
400 crypto/sha1, crypto/sha256, crypto/sha512
403 CGO, fmt, net !< CRYPTO;
405 # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
406 CRYPTO, FMT, math/big
408 < crypto/internal/randutil
411 < golang.org/x/crypto/cryptobyte/asn1
412 < golang.org/x/crypto/cryptobyte
413 < golang.org/x/crypto/curve25519
414 < crypto/dsa, crypto/elliptic, crypto/rsa
418 CGO, net !< CRYPTO-MATH;
420 # TLS, Prince of Dependencies.
421 CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
422 < golang.org/x/crypto/internal/subtle
423 < golang.org/x/crypto/chacha20
424 < golang.org/x/crypto/poly1305
425 < golang.org/x/crypto/chacha20poly1305
426 < golang.org/x/crypto/hkdf
427 < crypto/x509/internal/macos
432 # crypto-aware packages
434 NET, crypto/rand, mime/quotedprintable
440 # HTTP, King of Dependencies.
443 < golang.org/x/net/http2/hpack, net/http/internal, net/http/internal/ascii;
445 FMT, NET, container/list, encoding/binary, log
446 < golang.org/x/text/transform
447 < golang.org/x/text/unicode/norm
448 < golang.org/x/text/unicode/bidi
449 < golang.org/x/text/secure/bidirule
450 < golang.org/x/net/idna
451 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
454 < net/http/httptrace;
457 golang.org/x/net/http/httpguts,
458 golang.org/x/net/http/httpproxy,
459 golang.org/x/net/http2/hpack,
461 net/http/internal/ascii,
467 # HTTP-aware packages
469 encoding/json, net/http
472 net/http, net/http/internal/ascii
473 < net/http/cookiejar, net/http/httputil;
483 FMT, compress/gzip, encoding/binary, text/tabwriter
486 OS, compress/gzip, regexp
489 html, internal/profile, net/http, runtime/pprof, runtime/trace
493 encoding/gob, encoding/json, go/token, html/template, net/http
509 FMT, flag, runtime/debug, runtime/trace, internal/sysinfo, math/rand
512 internal/testlog, runtime/pprof, regexp
513 < testing/internal/testdeps;
515 OS, flag, testing, internal/cfg
519 < internal/obscuretestdata;
522 < os/signal/internal/pty;
524 NET, testing, math/rand
525 < golang.org/x/net/nettest;
527 FMT, container/heap, math/rand
531 // listStdPkgs returns the same list of packages as "go list std".
532 func listStdPkgs(goroot string) ([]string, error) {
533 // Based on cmd/go's matchPackages function.
536 src := filepath.Join(goroot, "src") + string(filepath.Separator)
537 walkFn := func(path string, d fs.DirEntry, err error) error {
538 if err != nil || !d.IsDir() || path == src {
542 base := filepath.Base(path)
543 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
544 return filepath.SkipDir
547 name := filepath.ToSlash(path[len(src):])
548 if name == "builtin" || name == "cmd" {
549 return filepath.SkipDir
552 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
555 if err := filepath.WalkDir(src, walkFn); err != nil {
561 func TestDependencies(t *testing.T) {
562 if !testenv.HasSrc() {
563 // Tests run in a limited file system and we do not
564 // provide access to every source file.
565 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
569 all, err := listStdPkgs(ctxt.GOROOT)
575 sawImport := map[string]map[string]bool{} // from package => to package => true
576 policy := depsPolicy(t)
578 for _, pkg := range all {
579 imports, err := findImports(pkg)
584 if sawImport[pkg] == nil {
585 sawImport[pkg] = map[string]bool{}
589 for _, imp := range imports {
590 sawImport[pkg][imp] = true
592 bad = append(bad, imp)
596 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
600 // depPath returns the path between the given from and to packages.
601 // It returns the empty string if there's no dependency path.
602 var depPath func(string, string) string
603 depPath = func(from, to string) string {
604 if sawImport[from][to] {
605 return from + " => " + to
607 for pkg := range sawImport[from] {
608 if p := depPath(pkg, to); p != "" {
609 return from + " => " + p
616 var buildIgnore = []byte("\n// +build ignore")
618 func findImports(pkg string) ([]string, error) {
620 if strings.HasPrefix(pkg, "golang.org") {
621 vpkg = "vendor/" + pkg
623 dir := filepath.Join(Default.GOROOT, "src", vpkg)
624 files, err := os.ReadDir(dir)
629 var haveImport = map[string]bool{}
630 fset := token.NewFileSet()
631 for _, file := range files {
633 if name == "slice_go14.go" || name == "slice_go18.go" {
634 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
637 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
641 name: filepath.Join(dir, name),
644 f, err := os.Open(info.name)
648 err = readGoInfo(f, &info)
651 return nil, fmt.Errorf("reading %v: %v", name, err)
653 if bytes.Contains(info.header, buildIgnore) {
656 for _, imp := range info.imports {
658 if !haveImport[path] {
659 haveImport[path] = true
660 imports = append(imports, path)
664 sort.Strings(imports)
668 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
669 func depsPolicy(t *testing.T) map[string]map[string]bool {
670 allowed := map[string]map[string]bool{"NONE": {}}
671 disallowed := [][2][]string{}
673 parseDepsRules(t, func(deps []string, op string, users []string) {
675 disallowed = append(disallowed, [2][]string{deps, users})
678 for _, u := range users {
679 if allowed[u] != nil {
680 t.Errorf("multiple deps lists for %s", u)
682 allowed[u] = make(map[string]bool)
683 for _, d := range deps {
684 if allowed[d] == nil {
685 t.Errorf("use of %s before its deps list", d)
692 // Check for missing deps info.
693 for _, deps := range allowed {
694 for d := range deps {
695 if allowed[d] == nil {
696 t.Errorf("missing deps list for %s", d)
701 // Complete transitive allowed deps.
702 for k := range allowed {
703 for i := range allowed {
704 for j := range allowed {
705 if i != k && k != j && allowed[i][k] && allowed[k][j] {
707 // Can only happen along with a "use of X before deps" error above,
708 // but this error is more specific - it makes clear that reordering the
709 // rules will not be enough to fix the problem.
710 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
718 // Check negative assertions against completed allowed deps.
719 for _, bad := range disallowed {
720 deps, users := bad[0], bad[1]
721 for _, d := range deps {
722 for _, u := range users {
724 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
737 // parseDepsRules parses depsRules, calling save(deps, op, users)
738 // for each deps < users or deps !< users rule
739 // (op is "<" or "!<").
740 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
741 p := &depsParser{t: t, lineno: 1, text: depsRules}
746 list, tok := p.nextList()
751 p.syntaxError("unexpected EOF")
762 if tok != "<" && tok != "!<" {
763 p.syntaxError("missing <")
769 // A depsParser parses the depsRules syntax described above.
770 type depsParser struct {
777 // syntaxError reports a parsing error.
778 func (p *depsParser) syntaxError(msg string) {
779 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
782 // nextList parses and returns a comma-separated list of names.
783 func (p *depsParser) nextList() (list []string, token string) {
792 case ",", "<", "!<", ";":
793 p.syntaxError("bad list syntax")
795 list = append(list, tok)
804 // nextToken returns the next token in the deps rules,
805 // one of ";" "," "<" "!<" or a name.
806 func (p *depsParser) nextToken() string {
818 if len(p.text) < 2 || p.text[1] != '<' {
819 p.syntaxError("unexpected token !")
825 i := strings.Index(p.text, "\n")
840 i := strings.IndexAny(p.text, "!;,<#\n \t")
852 // TestStdlibLowercase tests that all standard library package names are
853 // lowercase. See Issue 40065.
854 func TestStdlibLowercase(t *testing.T) {
855 if !testenv.HasSrc() {
856 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
860 all, err := listStdPkgs(ctxt.GOROOT)
865 for _, pkgname := range all {
866 if strings.ToLower(pkgname) != pkgname {
867 t.Errorf("package %q should not use upper-case path", pkgname)
872 // TestFindImports tests that findImports works. See #43249.
873 func TestFindImports(t *testing.T) {
874 imports, err := findImports("go/build")
878 t.Logf("go/build imports %q", imports)
879 want := []string{"bytes", "os", "path/filepath", "strings"}
881 for _, w := range want {
882 for _, imp := range imports {
887 t.Errorf("expected to find %q in import list", w)