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 < constraints, container/list, container/ring,
74 internal/cfg, internal/cpu, internal/goarch,
75 internal/goexperiment, internal/goos,
76 internal/goversion, internal/nettrace,
77 unicode/utf8, unicode/utf16, unicode,
80 # These packages depend only on internal/goarch and unsafe.
81 internal/goarch, unsafe
84 # RUNTIME is the core runtime group of packages, all of them very light-weight.
85 internal/abi, internal/cpu, internal/goarch,
86 internal/goexperiment, internal/goos, unsafe
89 < internal/unsafeheader
90 < runtime/internal/sys
91 < runtime/internal/syscall
92 < runtime/internal/atomic
93 < runtime/internal/math
98 < internal/reflectlite
100 < internal/oserror, math/bits
113 RUNTIME, unicode/utf8
118 # SYSCALL is RUNTIME plus the packages necessary for basic system calls.
119 RUNTIME, unicode/utf8, unicode/utf16
120 < internal/syscall/windows/sysdll, syscall/js
122 < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
123 < internal/syscall/execenv
126 # TIME is SYSCALL plus the core packages about time, including context.
136 # MATH is RUNTIME plus the basic math packages.
157 # STR is basic string and buffer manipulation.
158 RUNTIME, io, unicode/utf8, unicode/utf16, unicode
165 # OS is basic OS access, including helpers (path/filepath, os/exec, etc).
166 # OS includes string routines, but those must be layered above package os.
167 # OS does not include reflection.
177 unicode, fmt !< net, os, os/signal;
181 < io/ioutil, os/exec;
183 io/ioutil, os/exec, os/signal
189 < golang.org/x/sys/cpu;
191 os < internal/godebug;
193 # FMT is OS (which includes string routines) plus reflect and fmt.
194 # It does not include package log, which should be avoided in core packages.
213 # Misc packages needing only FMT.
216 mime/quotedprintable,
217 net/internal/socktest,
224 # core ones do not use fmt.
230 < encoding/base32, encoding/base64;
232 FMT, encoding < flag;
234 fmt !< encoding/base32, encoding/base64;
236 FMT, encoding/base32, encoding/base64
237 < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
238 encoding/json, encoding/pem, encoding/xml, mime;
243 < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
246 FMT, encoding/binary, math/rand
250 FMT, encoding/binary, hash/adler32, hash/crc32
251 < compress/bzip2, compress/flate, compress/lzw
252 < archive/zip, compress/gzip, compress/zlib;
256 < text/template/parse;
258 net/url, text/template/parse
260 < internal/lazytemplate;
262 encoding/json, html, text/template
269 < internal/lazyregexp;
272 encoding/binary, regexp
276 FMT, encoding/binary, compress/zlib
279 < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
283 # go parser and friends.
288 < go/internal/typeparams
292 < go/build/constraint;
294 go/build/constraint, go/parser, text/tabwriter
298 go/parser, internal/lazyregexp, text/template
304 container/heap, go/constant, go/parser, regexp
307 FMT, internal/goexperiment
310 go/build/constraint, go/doc, go/parser, internal/buildcfg, internal/goroot, internal/goversion
315 < database/sql/internal
316 < database/sql/driver
320 FMT, compress/lzw, compress/zlib
322 < image, image/color/palette
323 < image/internal/imageutil
325 < image/gif, image/jpeg, image/png;
327 # cgo, delayed as long as possible.
328 # If you add a dependency on CGO, you must add the package
329 # to cgoPackages in cmd/dist/test.go as well.
334 < runtime/race, runtime/msan, runtime/asan;
336 # Bulk of the standard library must not use cgo.
337 # The prohibition stops at net and os/user.
338 C !< fmt, go/types, CRYPTO-MATH;
348 < internal/singleflight;
351 < golang.org/x/net/dns/dnsmessage,
352 golang.org/x/net/lif,
353 golang.org/x/net/route;
355 os, runtime, strconv, sync, unsafe,
359 internal/bytealg, internal/intern, internal/itoa, math/bits, sort, strconv
362 # net is unavoidable when doing any networking,
363 # so large dependencies must be kept out.
364 # This is a long-looking list but most of these
365 # are small with few dependencies.
367 golang.org/x/net/dns/dnsmessage,
368 golang.org/x/net/lif,
369 golang.org/x/net/route,
373 internal/singleflight,
380 math/rand !< net; # net uses runtime instead
382 # NET is net plus net-helper packages.
386 mime, net/textproto, net/url
389 # logging - most packages should not import; http and up is allowed
393 log !< crypto/tls, database/sql, go/importer, testing;
401 # CRYPTO is core crypto algorithms - no cgo, fmt, net.
402 # Unfortunately, stuck with reflect via encoding/binary.
403 encoding/binary, golang.org/x/sys/cpu, hash
406 < crypto/internal/subtle
407 < crypto/elliptic/internal/fiat
408 < crypto/elliptic/internal/nistec
409 < crypto/ed25519/internal/edwards25519/field, golang.org/x/crypto/curve25519/internal/field
410 < crypto/ed25519/internal/edwards25519
412 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
413 crypto/sha1, crypto/sha256, crypto/sha512
416 CGO, fmt, net !< CRYPTO;
418 # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
419 CRYPTO, FMT, math/big, embed
421 < crypto/internal/randutil
424 < golang.org/x/crypto/cryptobyte/asn1
425 < golang.org/x/crypto/cryptobyte
426 < golang.org/x/crypto/curve25519
427 < crypto/dsa, crypto/elliptic, crypto/rsa
431 CGO, net !< CRYPTO-MATH;
433 # TLS, Prince of Dependencies.
434 CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
435 < golang.org/x/crypto/internal/subtle
436 < golang.org/x/crypto/chacha20
437 < golang.org/x/crypto/internal/poly1305
438 < golang.org/x/crypto/chacha20poly1305
439 < golang.org/x/crypto/hkdf
440 < crypto/x509/internal/macos
445 # crypto-aware packages
447 CRYPTO, DEBUG, go/build, go/types, text/scanner
449 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
452 NET, crypto/rand, mime/quotedprintable
458 # HTTP, King of Dependencies.
461 < golang.org/x/net/http2/hpack
462 < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
464 FMT, NET, container/list, encoding/binary, log
465 < golang.org/x/text/transform
466 < golang.org/x/text/unicode/norm
467 < golang.org/x/text/unicode/bidi
468 < golang.org/x/text/secure/bidirule
469 < golang.org/x/net/idna
470 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
473 < net/http/httptrace;
476 golang.org/x/net/http/httpguts,
477 golang.org/x/net/http/httpproxy,
478 golang.org/x/net/http2/hpack,
480 net/http/internal/ascii,
481 net/http/internal/testcert,
487 # HTTP-aware packages
489 encoding/json, net/http
492 net/http, net/http/internal/ascii
493 < net/http/cookiejar, net/http/httputil;
503 FMT, compress/gzip, encoding/binary, text/tabwriter
506 OS, compress/gzip, regexp
509 html, internal/profile, net/http, runtime/pprof, runtime/trace
513 encoding/gob, encoding/json, go/token, html/template, net/http
529 FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
532 FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
533 internal/godebug, math/rand, encoding/hex, crypto/sha256
536 internal/fuzz, internal/testlog, runtime/pprof, regexp
537 < testing/internal/testdeps;
539 OS, flag, testing, internal/cfg
543 < internal/obscuretestdata;
546 < os/signal/internal/pty;
548 NET, testing, math/rand
549 < golang.org/x/net/nettest;
552 < os/exec/internal/fdtest;
554 FMT, container/heap, math/rand
558 < internal/diff, internal/txtar;
561 // listStdPkgs returns the same list of packages as "go list std".
562 func listStdPkgs(goroot string) ([]string, error) {
563 // Based on cmd/go's matchPackages function.
566 src := filepath.Join(goroot, "src") + string(filepath.Separator)
567 walkFn := func(path string, d fs.DirEntry, err error) error {
568 if err != nil || !d.IsDir() || path == src {
572 base := filepath.Base(path)
573 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
574 return filepath.SkipDir
577 name := filepath.ToSlash(path[len(src):])
578 if name == "builtin" || name == "cmd" {
579 return filepath.SkipDir
582 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
585 if err := filepath.WalkDir(src, walkFn); err != nil {
591 func TestDependencies(t *testing.T) {
592 if !testenv.HasSrc() {
593 // Tests run in a limited file system and we do not
594 // provide access to every source file.
595 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
599 all, err := listStdPkgs(ctxt.GOROOT)
605 sawImport := map[string]map[string]bool{} // from package => to package => true
606 policy := depsPolicy(t)
608 for _, pkg := range all {
609 imports, err := findImports(pkg)
614 if sawImport[pkg] == nil {
615 sawImport[pkg] = map[string]bool{}
619 for _, imp := range imports {
620 sawImport[pkg][imp] = true
622 bad = append(bad, imp)
626 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
631 var buildIgnore = []byte("\n//go:build ignore")
633 func findImports(pkg string) ([]string, error) {
635 if strings.HasPrefix(pkg, "golang.org") {
636 vpkg = "vendor/" + pkg
638 dir := filepath.Join(Default.GOROOT, "src", vpkg)
639 files, err := os.ReadDir(dir)
644 var haveImport = map[string]bool{}
645 fset := token.NewFileSet()
646 for _, file := range files {
648 if name == "slice_go14.go" || name == "slice_go18.go" {
649 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
652 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
656 name: filepath.Join(dir, name),
659 f, err := os.Open(info.name)
663 err = readGoInfo(f, &info)
666 return nil, fmt.Errorf("reading %v: %v", name, err)
668 if info.parsed.Name.Name == "main" {
671 if bytes.Contains(info.header, buildIgnore) {
674 for _, imp := range info.imports {
676 if !haveImport[path] {
677 haveImport[path] = true
678 imports = append(imports, path)
682 sort.Strings(imports)
686 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
687 func depsPolicy(t *testing.T) map[string]map[string]bool {
688 allowed := map[string]map[string]bool{"NONE": {}}
689 disallowed := [][2][]string{}
691 parseDepsRules(t, func(deps []string, op string, users []string) {
693 disallowed = append(disallowed, [2][]string{deps, users})
696 for _, u := range users {
697 if allowed[u] != nil {
698 t.Errorf("multiple deps lists for %s", u)
700 allowed[u] = make(map[string]bool)
701 for _, d := range deps {
702 if allowed[d] == nil {
703 t.Errorf("use of %s before its deps list", d)
710 // Check for missing deps info.
711 for _, deps := range allowed {
712 for d := range deps {
713 if allowed[d] == nil {
714 t.Errorf("missing deps list for %s", d)
719 // Complete transitive allowed deps.
720 for k := range allowed {
721 for i := range allowed {
722 for j := range allowed {
723 if i != k && k != j && allowed[i][k] && allowed[k][j] {
725 // Can only happen along with a "use of X before deps" error above,
726 // but this error is more specific - it makes clear that reordering the
727 // rules will not be enough to fix the problem.
728 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
736 // Check negative assertions against completed allowed deps.
737 for _, bad := range disallowed {
738 deps, users := bad[0], bad[1]
739 for _, d := range deps {
740 for _, u := range users {
742 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
755 // parseDepsRules parses depsRules, calling save(deps, op, users)
756 // for each deps < users or deps !< users rule
757 // (op is "<" or "!<").
758 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
759 p := &depsParser{t: t, lineno: 1, text: depsRules}
764 list, tok := p.nextList()
769 p.syntaxError("unexpected EOF")
780 if tok != "<" && tok != "!<" {
781 p.syntaxError("missing <")
787 // A depsParser parses the depsRules syntax described above.
788 type depsParser struct {
795 // syntaxError reports a parsing error.
796 func (p *depsParser) syntaxError(msg string) {
797 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
800 // nextList parses and returns a comma-separated list of names.
801 func (p *depsParser) nextList() (list []string, token string) {
810 case ",", "<", "!<", ";":
811 p.syntaxError("bad list syntax")
813 list = append(list, tok)
822 // nextToken returns the next token in the deps rules,
823 // one of ";" "," "<" "!<" or a name.
824 func (p *depsParser) nextToken() string {
836 if len(p.text) < 2 || p.text[1] != '<' {
837 p.syntaxError("unexpected token !")
843 i := strings.Index(p.text, "\n")
858 i := strings.IndexAny(p.text, "!;,<#\n \t")
870 // TestStdlibLowercase tests that all standard library package names are
871 // lowercase. See Issue 40065.
872 func TestStdlibLowercase(t *testing.T) {
873 if !testenv.HasSrc() {
874 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
878 all, err := listStdPkgs(ctxt.GOROOT)
883 for _, pkgname := range all {
884 if strings.ToLower(pkgname) != pkgname {
885 t.Errorf("package %q should not use upper-case path", pkgname)
890 // TestFindImports tests that findImports works. See #43249.
891 func TestFindImports(t *testing.T) {
892 imports, err := findImports("go/build")
896 t.Logf("go/build imports %q", imports)
897 want := []string{"bytes", "os", "path/filepath", "strings"}
899 for _, w := range want {
900 for _, imp := range imports {
905 t.Errorf("expected to find %q in import list", w)