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/bcache, 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
416 crypto/internal/boring/bcache
417 < crypto/internal/boring
419 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
420 crypto/sha1, crypto/sha256, crypto/sha512
423 CGO, fmt, net !< CRYPTO;
425 # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
426 CRYPTO, FMT, math/big, embed
427 < crypto/internal/boring/bbig
428 < crypto/internal/randutil
432 < golang.org/x/crypto/cryptobyte/asn1
433 < golang.org/x/crypto/cryptobyte
434 < golang.org/x/crypto/curve25519
435 < crypto/dsa, crypto/elliptic, crypto/rsa
439 CGO, net !< CRYPTO-MATH;
441 # TLS, Prince of Dependencies.
442 CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
443 < golang.org/x/crypto/internal/subtle
444 < golang.org/x/crypto/chacha20
445 < golang.org/x/crypto/internal/poly1305
446 < golang.org/x/crypto/chacha20poly1305
447 < golang.org/x/crypto/hkdf
448 < crypto/x509/internal/macos
451 crypto/internal/boring/fipstls, crypto/x509/pkix
455 # crypto-aware packages
457 DEBUG, go/build, go/types, text/scanner, crypto/md5
459 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
462 NET, crypto/rand, mime/quotedprintable
468 # HTTP, King of Dependencies.
471 < golang.org/x/net/http2/hpack
472 < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
474 FMT, NET, container/list, encoding/binary, log
475 < golang.org/x/text/transform
476 < golang.org/x/text/unicode/norm
477 < golang.org/x/text/unicode/bidi
478 < golang.org/x/text/secure/bidirule
479 < golang.org/x/net/idna
480 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
483 < net/http/httptrace;
486 golang.org/x/net/http/httpguts,
487 golang.org/x/net/http/httpproxy,
488 golang.org/x/net/http2/hpack,
490 net/http/internal/ascii,
491 net/http/internal/testcert,
497 # HTTP-aware packages
499 encoding/json, net/http
502 net/http, net/http/internal/ascii
503 < net/http/cookiejar, net/http/httputil;
513 FMT, compress/gzip, encoding/binary, text/tabwriter
516 OS, compress/gzip, regexp
519 html, internal/profile, net/http, runtime/pprof, runtime/trace
523 encoding/gob, encoding/json, go/token, html/template, net/http
539 FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
542 FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
543 internal/godebug, math/rand, encoding/hex, crypto/sha256
546 internal/fuzz, internal/testlog, runtime/pprof, regexp
547 < testing/internal/testdeps;
549 OS, flag, testing, internal/cfg
553 < internal/obscuretestdata;
556 < os/signal/internal/pty;
558 NET, testing, math/rand
559 < golang.org/x/net/nettest;
562 < os/exec/internal/fdtest;
564 FMT, container/heap, math/rand
568 < internal/diff, internal/txtar;
571 // listStdPkgs returns the same list of packages as "go list std".
572 func listStdPkgs(goroot string) ([]string, error) {
573 // Based on cmd/go's matchPackages function.
576 src := filepath.Join(goroot, "src") + string(filepath.Separator)
577 walkFn := func(path string, d fs.DirEntry, err error) error {
578 if err != nil || !d.IsDir() || path == src {
582 base := filepath.Base(path)
583 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
584 return filepath.SkipDir
587 name := filepath.ToSlash(path[len(src):])
588 if name == "builtin" || name == "cmd" {
589 return filepath.SkipDir
592 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
595 if err := filepath.WalkDir(src, walkFn); err != nil {
601 func TestDependencies(t *testing.T) {
602 if !testenv.HasSrc() {
603 // Tests run in a limited file system and we do not
604 // provide access to every source file.
605 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
609 all, err := listStdPkgs(ctxt.GOROOT)
615 sawImport := map[string]map[string]bool{} // from package => to package => true
616 policy := depsPolicy(t)
618 for _, pkg := range all {
619 imports, err := findImports(pkg)
624 if sawImport[pkg] == nil {
625 sawImport[pkg] = map[string]bool{}
629 for _, imp := range imports {
630 sawImport[pkg][imp] = true
632 bad = append(bad, imp)
636 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
641 var buildIgnore = []byte("\n//go:build ignore")
643 func findImports(pkg string) ([]string, error) {
645 if strings.HasPrefix(pkg, "golang.org") {
646 vpkg = "vendor/" + pkg
648 dir := filepath.Join(Default.GOROOT, "src", vpkg)
649 files, err := os.ReadDir(dir)
654 var haveImport = map[string]bool{}
655 if pkg == "crypto/internal/boring" {
656 haveImport["C"] = true // kludge: prevent C from appearing in crypto/internal/boring imports
658 fset := token.NewFileSet()
659 for _, file := range files {
661 if name == "slice_go14.go" || name == "slice_go18.go" {
662 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
665 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
669 name: filepath.Join(dir, name),
672 f, err := os.Open(info.name)
676 err = readGoInfo(f, &info)
679 return nil, fmt.Errorf("reading %v: %v", name, err)
681 if info.parsed.Name.Name == "main" {
684 if bytes.Contains(info.header, buildIgnore) {
687 for _, imp := range info.imports {
689 if !haveImport[path] {
690 haveImport[path] = true
691 imports = append(imports, path)
695 sort.Strings(imports)
699 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
700 func depsPolicy(t *testing.T) map[string]map[string]bool {
701 allowed := map[string]map[string]bool{"NONE": {}}
702 disallowed := [][2][]string{}
704 parseDepsRules(t, func(deps []string, op string, users []string) {
706 disallowed = append(disallowed, [2][]string{deps, users})
709 for _, u := range users {
710 if allowed[u] != nil {
711 t.Errorf("multiple deps lists for %s", u)
713 allowed[u] = make(map[string]bool)
714 for _, d := range deps {
715 if allowed[d] == nil {
716 t.Errorf("use of %s before its deps list", d)
723 // Check for missing deps info.
724 for _, deps := range allowed {
725 for d := range deps {
726 if allowed[d] == nil {
727 t.Errorf("missing deps list for %s", d)
732 // Complete transitive allowed deps.
733 for k := range allowed {
734 for i := range allowed {
735 for j := range allowed {
736 if i != k && k != j && allowed[i][k] && allowed[k][j] {
738 // Can only happen along with a "use of X before deps" error above,
739 // but this error is more specific - it makes clear that reordering the
740 // rules will not be enough to fix the problem.
741 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
749 // Check negative assertions against completed allowed deps.
750 for _, bad := range disallowed {
751 deps, users := bad[0], bad[1]
752 for _, d := range deps {
753 for _, u := range users {
755 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
768 // parseDepsRules parses depsRules, calling save(deps, op, users)
769 // for each deps < users or deps !< users rule
770 // (op is "<" or "!<").
771 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
772 p := &depsParser{t: t, lineno: 1, text: depsRules}
777 list, tok := p.nextList()
782 p.syntaxError("unexpected EOF")
793 if tok != "<" && tok != "!<" {
794 p.syntaxError("missing <")
800 // A depsParser parses the depsRules syntax described above.
801 type depsParser struct {
808 // syntaxError reports a parsing error.
809 func (p *depsParser) syntaxError(msg string) {
810 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
813 // nextList parses and returns a comma-separated list of names.
814 func (p *depsParser) nextList() (list []string, token string) {
823 case ",", "<", "!<", ";":
824 p.syntaxError("bad list syntax")
826 list = append(list, tok)
835 // nextToken returns the next token in the deps rules,
836 // one of ";" "," "<" "!<" or a name.
837 func (p *depsParser) nextToken() string {
849 if len(p.text) < 2 || p.text[1] != '<' {
850 p.syntaxError("unexpected token !")
856 i := strings.Index(p.text, "\n")
871 i := strings.IndexAny(p.text, "!;,<#\n \t")
883 // TestStdlibLowercase tests that all standard library package names are
884 // lowercase. See Issue 40065.
885 func TestStdlibLowercase(t *testing.T) {
886 if !testenv.HasSrc() {
887 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
891 all, err := listStdPkgs(ctxt.GOROOT)
896 for _, pkgname := range all {
897 if strings.ToLower(pkgname) != pkgname {
898 t.Errorf("package %q should not use upper-case path", pkgname)
903 // TestFindImports tests that findImports works. See #43249.
904 func TestFindImports(t *testing.T) {
905 imports, err := findImports("go/build")
909 t.Logf("go/build imports %q", imports)
910 want := []string{"bytes", "os", "path/filepath", "strings"}
912 for _, w := range want {
913 for _, imp := range imports {
918 t.Errorf("expected to find %q in import list", w)