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.
23 // depsRules defines the expected dependencies between packages in
24 // the Go source tree. It is a statement of policy.
26 // DO NOT CHANGE THIS DATA TO FIX BUILDS.
27 // Existing packages should not have their constraints relaxed
28 // without prior discussion.
29 // Negative assertions should almost never be removed.
31 // The general syntax of a rule is:
35 // which means c and d come after a and b in the partial order
36 // (that is, c and d can import a and b),
37 // but doesn't provide a relative order between a vs b or c vs d.
39 // The rules can chain together, as in:
43 // which is equivalent to
48 // Except for the special bottom element "NONE", each name
49 // must appear exactly once on the right-hand side of a rule.
50 // That rule serves as the definition of the allowed dependencies
51 // for that name. The definition must appear before any uses
52 // of the name on the left-hand side of a rule. (That is, the
53 // rules themselves must be ordered according to the partial
54 // order, for easier reading by people.)
56 // Negative assertions double-check the partial order:
60 // means that it must NOT be the case that i < j.
61 // Negative assertions may appear anywhere in the rules,
62 // even before i and j have been defined.
64 // Comments begin with #.
66 // All-caps names are pseudo-names for specific points
67 // in the dependency lattice.
70 # No dependencies allowed for any of these packages.
72 < container/list, container/ring,
73 internal/cfg, internal/cpu,
74 internal/goversion, internal/nettrace,
75 unicode/utf8, unicode/utf16, unicode,
78 # RUNTIME is the core runtime group of packages, all of them very light-weight.
81 < internal/unsafeheader
82 < runtime/internal/sys
83 < runtime/internal/atomic
84 < runtime/internal/math
89 < internal/reflectlite
91 < internal/oserror, math/bits
104 RUNTIME, unicode/utf8
109 # SYSCALL is RUNTIME plus the packages necessary for basic system calls.
110 RUNTIME, unicode/utf8, unicode/utf16
111 < internal/syscall/windows/sysdll, syscall/js
113 < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
114 < internal/syscall/execenv
117 # TIME is SYSCALL plus the core packages about time, including context.
127 # MATH is RUNTIME plus the basic math packages.
148 # STR is basic string and buffer manipulation.
149 RUNTIME, io, unicode/utf8, unicode/utf16, unicode
156 # OS is basic OS access, including helpers (path/filepath, os/exec, etc).
157 # OS includes string routines, but those must be layered above package os.
158 # OS does not include reflection.
165 unicode, fmt !< os, os/signal;
169 < io/ioutil, os/exec;
171 io/ioutil, os/exec, os/signal
177 < golang.org/x/sys/cpu, internal/goroot;
179 # FMT is OS (which includes string routines) plus reflect and fmt.
180 # It does not include package log, which should be avoided in core packages.
193 # Misc packages needing only FMT.
197 mime/quotedprintable,
198 net/internal/socktest,
206 # core ones do not use fmt.
212 < encoding/base32, encoding/base64;
214 fmt !< encoding/base32, encoding/base64;
216 FMT, encoding/base32, encoding/base64
217 < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
218 encoding/json, encoding/pem, encoding/xml, mime;
223 < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
226 FMT, encoding/binary, math/rand
230 FMT, encoding/binary, hash/adler32, hash/crc32
231 < compress/bzip2, compress/flate, compress/lzw
232 < archive/zip, compress/gzip, compress/zlib;
236 < text/template/parse;
238 net/url, text/template/parse
240 < internal/lazytemplate;
242 encoding/json, html, text/template
249 < internal/lazyregexp;
252 encoding/binary, regexp
256 FMT, encoding/binary, compress/zlib
258 < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
261 # go parser and friends.
268 go/parser, text/tabwriter
272 go/parser, internal/lazyregexp, text/template
278 container/heap, go/constant, go/parser
281 go/doc, go/parser, internal/goroot, internal/goversion
284 DEBUG, go/build, go/types, text/scanner
285 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
290 < database/sql/internal
291 < database/sql/driver
295 FMT, compress/lzw, compress/zlib
297 < image, image/color/palette
298 < image/internal/imageutil
300 < image/gif, image/jpeg, image/png;
302 # cgo, delayed as long as possible.
303 # If you add a dependency on CGO, you must add the package
304 # to cgoPackages in cmd/dist/test.go as well.
309 < runtime/race, runtime/msan;
311 # Bulk of the standard library must not use cgo.
312 # The prohibition stops at net and os/user.
313 C !< fmt, go/types, CRYPTO-MATH;
323 < internal/singleflight;
326 < golang.org/x/net/dns/dnsmessage,
327 golang.org/x/net/lif,
328 golang.org/x/net/route;
330 # net is unavoidable when doing any networking,
331 # so large dependencies must be kept out.
332 # This is a long-looking list but most of these
333 # are small with few dependencies.
335 golang.org/x/net/dns/dnsmessage,
336 golang.org/x/net/lif,
337 golang.org/x/net/route,
340 internal/singleflight,
346 math/rand !< net; # net uses runtime instead
348 # NET is net plus net-helper packages.
352 mime, net/textproto, net/url
355 # logging - most packages should not import; http and up is allowed
359 log !< crypto/tls, database/sql, go/importer, testing;
367 # CRYPTO is core crypto algorithms - no cgo, fmt, net.
368 # Unfortunately, stuck with reflect via encoding/binary.
369 encoding/binary, golang.org/x/sys/cpu, hash
372 < crypto/internal/subtle
374 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
375 crypto/sha1, crypto/sha256, crypto/sha512
378 CGO, fmt, net !< CRYPTO;
380 # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
381 CRYPTO, FMT, math/big
383 < crypto/internal/randutil
384 < crypto/ed25519/internal/edwards25519
387 < golang.org/x/crypto/cryptobyte/asn1
388 < golang.org/x/crypto/cryptobyte
389 < golang.org/x/crypto/curve25519
390 < crypto/dsa, crypto/elliptic, crypto/rsa
394 CGO, net !< CRYPTO-MATH;
396 # TLS, Prince of Dependencies.
397 CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
398 < golang.org/x/crypto/internal/subtle
399 < golang.org/x/crypto/chacha20
400 < golang.org/x/crypto/poly1305
401 < golang.org/x/crypto/chacha20poly1305
402 < golang.org/x/crypto/hkdf
403 < crypto/x509/internal/macos
408 # crypto-aware packages
410 NET, crypto/rand, mime/quotedprintable
416 # HTTP, King of Dependencies.
419 < golang.org/x/net/http2/hpack, net/http/internal;
421 FMT, NET, container/list, encoding/binary, log
422 < golang.org/x/text/transform
423 < golang.org/x/text/unicode/norm
424 < golang.org/x/text/unicode/bidi
425 < golang.org/x/text/secure/bidirule
426 < golang.org/x/net/idna
427 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
430 < net/http/httptrace;
433 golang.org/x/net/http/httpguts,
434 golang.org/x/net/http/httpproxy,
435 golang.org/x/net/http2/hpack,
442 # HTTP-aware packages
444 encoding/json, net/http
448 < net/http/cookiejar, net/http/httputil;
458 FMT, compress/gzip, encoding/binary, text/tabwriter
461 OS, compress/gzip, regexp
464 html, internal/profile, net/http, runtime/pprof, runtime/trace
468 encoding/gob, encoding/json, go/token, html/template, net/http
484 FMT, flag, runtime/debug, runtime/trace, internal/sysinfo
487 internal/testlog, runtime/pprof, regexp
488 < testing/internal/testdeps;
490 OS, flag, testing, internal/cfg
494 < internal/obscuretestdata;
497 < os/signal/internal/pty;
499 NET, testing, math/rand
500 < golang.org/x/net/nettest;
502 FMT, container/heap, math/rand
506 // listStdPkgs returns the same list of packages as "go list std".
507 func listStdPkgs(goroot string) ([]string, error) {
508 // Based on cmd/go's matchPackages function.
511 src := filepath.Join(goroot, "src") + string(filepath.Separator)
512 walkFn := func(path string, d fs.DirEntry, err error) error {
513 if err != nil || !d.IsDir() || path == src {
517 base := filepath.Base(path)
518 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
519 return filepath.SkipDir
522 name := filepath.ToSlash(path[len(src):])
523 if name == "builtin" || name == "cmd" {
524 return filepath.SkipDir
527 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
530 if err := filepath.WalkDir(src, walkFn); err != nil {
536 func TestDependencies(t *testing.T) {
537 if !testenv.HasSrc() {
538 // Tests run in a limited file system and we do not
539 // provide access to every source file.
540 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
544 all, err := listStdPkgs(ctxt.GOROOT)
550 sawImport := map[string]map[string]bool{} // from package => to package => true
551 policy := depsPolicy(t)
553 for _, pkg := range all {
554 imports, err := findImports(pkg)
559 if sawImport[pkg] == nil {
560 sawImport[pkg] = map[string]bool{}
564 for _, imp := range imports {
565 sawImport[pkg][imp] = true
567 bad = append(bad, imp)
571 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
575 // depPath returns the path between the given from and to packages.
576 // It returns the empty string if there's no dependency path.
577 var depPath func(string, string) string
578 depPath = func(from, to string) string {
579 if sawImport[from][to] {
580 return from + " => " + to
582 for pkg := range sawImport[from] {
583 if p := depPath(pkg, to); p != "" {
584 return from + " => " + p
591 var buildIgnore = []byte("\n// +build ignore")
593 func findImports(pkg string) ([]string, error) {
595 if strings.HasPrefix(pkg, "golang.org") {
596 vpkg = "vendor/" + pkg
598 dir := filepath.Join(Default.GOROOT, "src", vpkg)
599 files, err := os.ReadDir(dir)
604 var haveImport = map[string]bool{}
605 for _, file := range files {
607 if name == "slice_go14.go" || name == "slice_go18.go" {
608 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
611 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
615 info.name = filepath.Join(dir, name)
616 f, err := os.Open(info.name)
620 err = readGoInfo(f, &info)
623 return nil, fmt.Errorf("reading %v: %v", name, err)
625 if bytes.Contains(info.header, buildIgnore) {
628 for _, imp := range info.imports {
630 if !haveImport[path] {
631 haveImport[path] = true
632 imports = append(imports, path)
636 sort.Strings(imports)
640 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
641 func depsPolicy(t *testing.T) map[string]map[string]bool {
642 allowed := map[string]map[string]bool{"NONE": {}}
643 disallowed := [][2][]string{}
645 parseDepsRules(t, func(deps []string, op string, users []string) {
647 disallowed = append(disallowed, [2][]string{deps, users})
650 for _, u := range users {
651 if allowed[u] != nil {
652 t.Errorf("multiple deps lists for %s", u)
654 allowed[u] = make(map[string]bool)
655 for _, d := range deps {
656 if allowed[d] == nil {
657 t.Errorf("use of %s before its deps list", d)
664 // Check for missing deps info.
665 for _, deps := range allowed {
666 for d := range deps {
667 if allowed[d] == nil {
668 t.Errorf("missing deps list for %s", d)
673 // Complete transitive allowed deps.
674 for k := range allowed {
675 for i := range allowed {
676 for j := range allowed {
677 if i != k && k != j && allowed[i][k] && allowed[k][j] {
679 // Can only happen along with a "use of X before deps" error above,
680 // but this error is more specific - it makes clear that reordering the
681 // rules will not be enough to fix the problem.
682 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
690 // Check negative assertions against completed allowed deps.
691 for _, bad := range disallowed {
692 deps, users := bad[0], bad[1]
693 for _, d := range deps {
694 for _, u := range users {
696 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
709 // parseDepsRules parses depsRules, calling save(deps, op, users)
710 // for each deps < users or deps !< users rule
711 // (op is "<" or "!<").
712 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
713 p := &depsParser{t: t, lineno: 1, text: depsRules}
718 list, tok := p.nextList()
723 p.syntaxError("unexpected EOF")
734 if tok != "<" && tok != "!<" {
735 p.syntaxError("missing <")
741 // A depsParser parses the depsRules syntax described above.
742 type depsParser struct {
749 // syntaxError reports a parsing error.
750 func (p *depsParser) syntaxError(msg string) {
751 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
754 // nextList parses and returns a comma-separated list of names.
755 func (p *depsParser) nextList() (list []string, token string) {
764 case ",", "<", "!<", ";":
765 p.syntaxError("bad list syntax")
767 list = append(list, tok)
776 // nextToken returns the next token in the deps rules,
777 // one of ";" "," "<" "!<" or a name.
778 func (p *depsParser) nextToken() string {
790 if len(p.text) < 2 || p.text[1] != '<' {
791 p.syntaxError("unexpected token !")
797 i := strings.Index(p.text, "\n")
812 i := strings.IndexAny(p.text, "!;,<#\n \t")
824 // TestStdlibLowercase tests that all standard library package names are
825 // lowercase. See Issue 40065.
826 func TestStdlibLowercase(t *testing.T) {
827 if !testenv.HasSrc() {
828 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
832 all, err := listStdPkgs(ctxt.GOROOT)
837 for _, pkgname := range all {
838 if strings.ToLower(pkgname) != pkgname {
839 t.Errorf("package %q should not use upper-case path", pkgname)