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.
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 NONE < crypto/internal/boring/sig;
390 sync/atomic < crypto/internal/boring/fipstls;
392 encoding/binary, golang.org/x/sys/cpu, hash,
394 CGO, crypto/internal/boring/sig, crypto/internal/boring/fipstls
397 < crypto/internal/subtle
398 < crypto/ed25519/internal/edwards25519/field
399 < crypto/ed25519/internal/edwards25519
402 < crypto/internal/boring
403 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
404 crypto/sha1, crypto/sha256, crypto/sha512
406 < crypto/internal/randutil
408 < golang.org/x/crypto/cryptobyte/asn1
409 < golang.org/x/crypto/cryptobyte
410 < golang.org/x/crypto/curve25519
411 < crypto/dsa, crypto/elliptic, crypto/rsa
415 net !< CRYPTO-BORING;
417 # TLS, Prince of Dependencies.
418 CRYPTO-BORING, NET, container/list, encoding/hex, encoding/pem
419 < golang.org/x/crypto/internal/subtle
420 < golang.org/x/crypto/chacha20
421 < golang.org/x/crypto/poly1305
422 < golang.org/x/crypto/chacha20poly1305
423 < golang.org/x/crypto/hkdf
424 < crypto/x509/internal/macos
429 crypto/internal/boring/sig, crypto/internal/boring/fipstls
430 < crypto/tls/fipsonly;
432 crypto/internal/boring
435 # crypto-aware packages
437 NET, crypto/rand, mime/quotedprintable
443 # HTTP, King of Dependencies.
446 < golang.org/x/net/http2/hpack, net/http/internal;
448 FMT, NET, container/list, encoding/binary, log
449 < golang.org/x/text/transform
450 < golang.org/x/text/unicode/norm
451 < golang.org/x/text/unicode/bidi
452 < golang.org/x/text/secure/bidirule
453 < golang.org/x/net/idna
454 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
457 < net/http/httptrace;
460 golang.org/x/net/http/httpguts,
461 golang.org/x/net/http/httpproxy,
462 golang.org/x/net/http2/hpack,
469 # HTTP-aware packages
471 encoding/json, net/http
475 < net/http/cookiejar, net/http/httputil;
485 FMT, compress/gzip, encoding/binary, text/tabwriter
488 OS, compress/gzip, regexp
491 html, internal/profile, net/http, runtime/pprof, runtime/trace
495 encoding/gob, encoding/json, go/token, html/template, net/http
511 FMT, flag, runtime/debug, runtime/trace, internal/sysinfo, math/rand
514 internal/testlog, runtime/pprof, regexp
515 < testing/internal/testdeps;
517 OS, flag, testing, internal/cfg
521 < internal/obscuretestdata;
524 < os/signal/internal/pty;
526 NET, testing, math/rand
527 < golang.org/x/net/nettest;
529 FMT, container/heap, math/rand
533 // listStdPkgs returns the same list of packages as "go list std".
534 func listStdPkgs(goroot string) ([]string, error) {
535 // Based on cmd/go's matchPackages function.
538 src := filepath.Join(goroot, "src") + string(filepath.Separator)
539 walkFn := func(path string, d fs.DirEntry, err error) error {
540 if err != nil || !d.IsDir() || path == src {
544 base := filepath.Base(path)
545 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
546 return filepath.SkipDir
549 name := filepath.ToSlash(path[len(src):])
550 if name == "builtin" || name == "cmd" {
551 return filepath.SkipDir
554 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
557 if err := filepath.WalkDir(src, walkFn); err != nil {
563 func TestDependencies(t *testing.T) {
564 if !testenv.HasSrc() {
565 // Tests run in a limited file system and we do not
566 // provide access to every source file.
567 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
571 all, err := listStdPkgs(ctxt.GOROOT)
577 sawImport := map[string]map[string]bool{} // from package => to package => true
578 policy := depsPolicy(t)
580 for _, pkg := range all {
581 imports, err := findImports(pkg)
586 if sawImport[pkg] == nil {
587 sawImport[pkg] = map[string]bool{}
591 for _, imp := range imports {
592 sawImport[pkg][imp] = true
594 bad = append(bad, imp)
598 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
602 // depPath returns the path between the given from and to packages.
603 // It returns the empty string if there's no dependency path.
604 var depPath func(string, string) string
605 depPath = func(from, to string) string {
606 if sawImport[from][to] {
607 return from + " => " + to
609 for pkg := range sawImport[from] {
610 if p := depPath(pkg, to); p != "" {
611 return from + " => " + p
618 var buildIgnore = []byte("\n// +build ignore")
620 func findImports(pkg string) ([]string, error) {
622 if strings.HasPrefix(pkg, "golang.org") {
623 vpkg = "vendor/" + pkg
625 dir := filepath.Join(Default.GOROOT, "src", vpkg)
626 files, err := os.ReadDir(dir)
631 var haveImport = map[string]bool{}
632 fset := token.NewFileSet()
633 for _, file := range files {
635 if name == "slice_go14.go" || name == "slice_go18.go" {
636 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
639 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
643 name: filepath.Join(dir, name),
646 f, err := os.Open(info.name)
650 err = readGoInfo(f, &info)
653 return nil, fmt.Errorf("reading %v: %v", name, err)
655 if bytes.Contains(info.header, buildIgnore) {
658 for _, imp := range info.imports {
660 if !haveImport[path] {
661 haveImport[path] = true
662 imports = append(imports, path)
666 sort.Strings(imports)
670 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
671 func depsPolicy(t *testing.T) map[string]map[string]bool {
672 allowed := map[string]map[string]bool{"NONE": {}}
673 disallowed := [][2][]string{}
675 parseDepsRules(t, func(deps []string, op string, users []string) {
677 disallowed = append(disallowed, [2][]string{deps, users})
680 for _, u := range users {
681 if allowed[u] != nil {
682 t.Errorf("multiple deps lists for %s", u)
684 allowed[u] = make(map[string]bool)
685 for _, d := range deps {
686 if allowed[d] == nil {
687 t.Errorf("use of %s before its deps list", d)
694 // Check for missing deps info.
695 for _, deps := range allowed {
696 for d := range deps {
697 if allowed[d] == nil {
698 t.Errorf("missing deps list for %s", d)
703 // Complete transitive allowed deps.
704 for k := range allowed {
705 for i := range allowed {
706 for j := range allowed {
707 if i != k && k != j && allowed[i][k] && allowed[k][j] {
709 // Can only happen along with a "use of X before deps" error above,
710 // but this error is more specific - it makes clear that reordering the
711 // rules will not be enough to fix the problem.
712 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
720 // Check negative assertions against completed allowed deps.
721 for _, bad := range disallowed {
722 deps, users := bad[0], bad[1]
723 for _, d := range deps {
724 for _, u := range users {
726 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
739 // parseDepsRules parses depsRules, calling save(deps, op, users)
740 // for each deps < users or deps !< users rule
741 // (op is "<" or "!<").
742 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
743 p := &depsParser{t: t, lineno: 1, text: depsRules}
748 list, tok := p.nextList()
753 p.syntaxError("unexpected EOF")
764 if tok != "<" && tok != "!<" {
765 p.syntaxError("missing <")
771 // A depsParser parses the depsRules syntax described above.
772 type depsParser struct {
779 // syntaxError reports a parsing error.
780 func (p *depsParser) syntaxError(msg string) {
781 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
784 // nextList parses and returns a comma-separated list of names.
785 func (p *depsParser) nextList() (list []string, token string) {
794 case ",", "<", "!<", ";":
795 p.syntaxError("bad list syntax")
797 list = append(list, tok)
806 // nextToken returns the next token in the deps rules,
807 // one of ";" "," "<" "!<" or a name.
808 func (p *depsParser) nextToken() string {
820 if len(p.text) < 2 || p.text[1] != '<' {
821 p.syntaxError("unexpected token !")
827 i := strings.Index(p.text, "\n")
842 i := strings.IndexAny(p.text, "!;,<#\n \t")
854 // TestStdlibLowercase tests that all standard library package names are
855 // lowercase. See Issue 40065.
856 func TestStdlibLowercase(t *testing.T) {
857 if !testenv.HasSrc() {
858 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
862 all, err := listStdPkgs(ctxt.GOROOT)
867 for _, pkgname := range all {
868 if strings.ToLower(pkgname) != pkgname {
869 t.Errorf("package %q should not use upper-case path", pkgname)
874 // TestFindImports tests that findImports works. See #43249.
875 func TestFindImports(t *testing.T) {
876 imports, err := findImports("go/build")
880 t.Logf("go/build imports %q", imports)
881 want := []string{"bytes", "os", "path/filepath", "strings"}
883 for _, w := range want {
884 for _, imp := range imports {
889 t.Errorf("expected to find %q in import list", w)