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
103 # SYSCALL is RUNTIME plus the packages necessary for basic system calls.
104 RUNTIME, unicode/utf8, unicode/utf16, io
105 < internal/syscall/windows/sysdll, syscall/js
107 < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
108 < internal/syscall/execenv
111 # TIME is SYSCALL plus the core packages about time, including context.
118 # MATH is RUNTIME plus the basic math packages.
136 # STR is basic string and buffer manipulation.
137 RUNTIME, io, unicode/utf8, unicode/utf16, unicode
144 # OS is basic OS access, including helpers (path/filepath, os/exec, etc).
145 # OS includes string routines, but those must be layered above package os.
146 # OS does not include reflection.
153 unicode, fmt !< os, os/signal;
163 < golang.org/x/sys/cpu, internal/goroot;
165 # FMT is OS (which includes string routines) plus reflect and fmt.
166 # It does not include package log, which should be avoided in core packages.
179 # Misc packages needing only FMT.
183 mime/quotedprintable,
184 net/internal/socktest,
192 # core ones do not use fmt.
198 < encoding/base32, encoding/base64;
200 fmt !< encoding/base32, encoding/base64;
202 FMT, encoding/base32, encoding/base64
203 < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
204 encoding/json, encoding/pem, encoding/xml, mime;
209 < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
212 FMT, encoding/binary, math/rand
216 FMT, encoding/binary, hash/adler32, hash/crc32
217 < compress/bzip2, compress/flate, compress/lzw
218 < archive/zip, compress/gzip, compress/zlib;
222 < text/template/parse;
224 net/url, text/template/parse
226 < internal/lazytemplate;
228 encoding/json, html, text/template
235 < internal/lazyregexp;
238 encoding/binary, regexp
242 FMT, encoding/binary, compress/zlib
244 < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
247 # go parser and friends.
254 go/parser, text/tabwriter
258 go/parser, internal/lazyregexp, text/template
264 container/heap, go/constant, go/parser
267 go/doc, go/parser, internal/goroot, internal/goversion
270 DEBUG, go/build, go/types, text/scanner
271 < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
276 < database/sql/internal
277 < database/sql/driver
281 FMT, compress/lzw, compress/zlib
283 < image, image/color/palette
284 < image/internal/imageutil
286 < image/gif, image/jpeg, image/png;
288 # cgo, delayed as long as possible.
289 # If you add a dependency on CGO, you must add the package
290 # to cgoPackages in cmd/dist/test.go as well.
295 < runtime/race, runtime/msan;
297 # Bulk of the standard library must not use cgo.
298 # The prohibition stops at net and os/user.
299 C !< fmt, go/types, CRYPTO-MATH;
309 < internal/singleflight;
312 < golang.org/x/net/dns/dnsmessage,
313 golang.org/x/net/lif,
314 golang.org/x/net/route;
316 # net is unavoidable when doing any networking,
317 # so large dependencies must be kept out.
318 # This is a long-looking list but most of these
319 # are small with few dependencies.
320 # math/rand should probably be removed at some point.
322 golang.org/x/net/dns/dnsmessage,
323 golang.org/x/net/lif,
324 golang.org/x/net/route,
327 internal/singleflight,
335 # NET is net plus net-helper packages.
339 mime, net/textproto, net/url
342 # logging - most packages should not import; http and up is allowed
346 log !< crypto/tls, database/sql, go/importer, testing;
354 # CRYPTO is core crypto algorithms - no cgo, fmt, net.
355 # Unfortunately, stuck with reflect via encoding/binary.
356 encoding/binary, golang.org/x/sys/cpu, hash
359 < crypto/internal/subtle
361 < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
362 crypto/sha1, crypto/sha256, crypto/sha512
365 CGO, fmt, net !< CRYPTO;
367 # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
368 CRYPTO, FMT, math/big
370 < crypto/internal/randutil
371 < crypto/ed25519/internal/edwards25519
374 < golang.org/x/crypto/cryptobyte/asn1
375 < golang.org/x/crypto/cryptobyte
376 < golang.org/x/crypto/curve25519
377 < crypto/dsa, crypto/elliptic, crypto/rsa
381 CGO, net !< CRYPTO-MATH;
383 # TLS, Prince of Dependencies.
384 CGO, CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
385 < golang.org/x/crypto/internal/subtle
386 < golang.org/x/crypto/chacha20
387 < golang.org/x/crypto/poly1305
388 < golang.org/x/crypto/chacha20poly1305
389 < golang.org/x/crypto/hkdf
390 < crypto/x509/internal/macOS
395 # crypto-aware packages
397 NET, crypto/rand, mime/quotedprintable
403 # HTTP, King of Dependencies.
406 < golang.org/x/net/http2/hpack, net/http/internal;
408 FMT, NET, container/list, encoding/binary, log
409 < golang.org/x/text/transform
410 < golang.org/x/text/unicode/norm
411 < golang.org/x/text/unicode/bidi
412 < golang.org/x/text/secure/bidirule
413 < golang.org/x/net/idna
414 < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
417 < net/http/httptrace;
420 golang.org/x/net/http/httpguts,
421 golang.org/x/net/http/httpproxy,
422 golang.org/x/net/http2/hpack,
429 # HTTP-aware packages
431 encoding/json, net/http
435 < net/http/cookiejar, net/http/httputil;
445 FMT, compress/gzip, encoding/binary, text/tabwriter
448 OS, compress/gzip, regexp
451 html/template, internal/profile, net/http, runtime/pprof, runtime/trace
455 encoding/gob, encoding/json, go/token, html/template, net/http
466 FMT, flag, runtime/debug, runtime/trace
469 internal/testlog, runtime/pprof, regexp
470 < testing/internal/testdeps;
472 OS, flag, testing, internal/cfg
476 < internal/obscuretestdata;
479 < os/signal/internal/pty;
482 < golang.org/x/net/nettest;
484 FMT, container/heap, math/rand
488 // listStdPkgs returns the same list of packages as "go list std".
489 func listStdPkgs(goroot string) ([]string, error) {
490 // Based on cmd/go's matchPackages function.
493 src := filepath.Join(goroot, "src") + string(filepath.Separator)
494 walkFn := func(path string, fi os.FileInfo, err error) error {
495 if err != nil || !fi.IsDir() || path == src {
499 base := filepath.Base(path)
500 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
501 return filepath.SkipDir
504 name := filepath.ToSlash(path[len(src):])
505 if name == "builtin" || name == "cmd" {
506 return filepath.SkipDir
509 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
512 if err := filepath.Walk(src, walkFn); err != nil {
518 func TestDependencies(t *testing.T) {
519 iOS := runtime.GOOS == "darwin" && runtime.GOARCH == "arm64"
521 // Tests run in a limited file system and we do not
522 // provide access to every source file.
523 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
527 all, err := listStdPkgs(ctxt.GOROOT)
533 sawImport := map[string]map[string]bool{} // from package => to package => true
534 policy := depsPolicy(t)
536 for _, pkg := range all {
537 imports, err := findImports(pkg)
542 if sawImport[pkg] == nil {
543 sawImport[pkg] = map[string]bool{}
547 for _, imp := range imports {
548 sawImport[pkg][imp] = true
550 bad = append(bad, imp)
554 t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
558 // depPath returns the path between the given from and to packages.
559 // It returns the empty string if there's no dependency path.
560 var depPath func(string, string) string
561 depPath = func(from, to string) string {
562 if sawImport[from][to] {
563 return from + " => " + to
565 for pkg := range sawImport[from] {
566 if p := depPath(pkg, to); p != "" {
567 return from + " => " + p
574 var buildIgnore = []byte("\n// +build ignore")
576 func findImports(pkg string) ([]string, error) {
578 if strings.HasPrefix(pkg, "golang.org") {
579 vpkg = "vendor/" + pkg
581 dir := filepath.Join(Default.GOROOT, "src", vpkg)
582 files, err := ioutil.ReadDir(dir)
587 var haveImport = map[string]bool{}
588 for _, file := range files {
590 if name == "slice_go14.go" || name == "slice_go18.go" {
591 // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
594 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
597 f, err := os.Open(filepath.Join(dir, name))
602 data, err := readImports(f, false, &imp)
605 return nil, fmt.Errorf("reading %v: %v", name, err)
607 if bytes.Contains(data, buildIgnore) {
610 for _, quoted := range imp {
611 path, err := strconv.Unquote(quoted)
615 if !haveImport[path] {
616 haveImport[path] = true
617 imports = append(imports, path)
621 sort.Strings(imports)
625 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
626 func depsPolicy(t *testing.T) map[string]map[string]bool {
627 allowed := map[string]map[string]bool{"NONE": {}}
628 disallowed := [][2][]string{}
630 parseDepsRules(t, func(deps []string, op string, users []string) {
632 disallowed = append(disallowed, [2][]string{deps, users})
635 for _, u := range users {
636 if allowed[u] != nil {
637 t.Errorf("multiple deps lists for %s", u)
639 allowed[u] = make(map[string]bool)
640 for _, d := range deps {
641 if allowed[d] == nil {
642 t.Errorf("use of %s before its deps list", d)
649 // Check for missing deps info.
650 for _, deps := range allowed {
651 for d := range deps {
652 if allowed[d] == nil {
653 t.Errorf("missing deps list for %s", d)
658 // Complete transitive allowed deps.
659 for k := range allowed {
660 for i := range allowed {
661 for j := range allowed {
662 if i != k && k != j && allowed[i][k] && allowed[k][j] {
664 // Can only happen along with a "use of X before deps" error above,
665 // but this error is more specific - it makes clear that reordering the
666 // rules will not be enough to fix the problem.
667 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
675 // Check negative assertions against completed allowed deps.
676 for _, bad := range disallowed {
677 deps, users := bad[0], bad[1]
678 for _, d := range deps {
679 for _, u := range users {
681 t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
694 // parseDepsRules parses depsRules, calling save(deps, op, users)
695 // for each deps < users or deps !< users rule
696 // (op is "<" or "!<").
697 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
698 p := &depsParser{t: t, lineno: 1, text: depsRules}
703 list, tok := p.nextList()
708 p.syntaxError("unexpected EOF")
719 if tok != "<" && tok != "!<" {
720 p.syntaxError("missing <")
726 // A depsParser parses the depsRules syntax described above.
727 type depsParser struct {
734 // syntaxError reports a parsing error.
735 func (p *depsParser) syntaxError(msg string) {
736 p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
739 // nextList parses and returns a comma-separated list of names.
740 func (p *depsParser) nextList() (list []string, token string) {
749 case ",", "<", "!<", ";":
750 p.syntaxError("bad list syntax")
752 list = append(list, tok)
761 // nextToken returns the next token in the deps rules,
762 // one of ";" "," "<" "!<" or a name.
763 func (p *depsParser) nextToken() string {
775 if len(p.text) < 2 || p.text[1] != '<' {
776 p.syntaxError("unexpected token !")
782 i := strings.Index(p.text, "\n")
797 i := strings.IndexAny(p.text, "!;,<#\n \t")