]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/build/deps_test.go
[dev.unified] all: merge master (85d87b9) into dev.unified
[gostls13.git] / src / go / build / deps_test.go
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.
4
5 // This file exercises the import parser but also checks that
6 // some low-level packages do not have new dependencies added.
7
8 package build
9
10 import (
11         "bytes"
12         "fmt"
13         "go/token"
14         "internal/dag"
15         "internal/testenv"
16         "io/fs"
17         "os"
18         "path/filepath"
19         "runtime"
20         "sort"
21         "strings"
22         "testing"
23 )
24
25 // depsRules defines the expected dependencies between packages in
26 // the Go source tree. It is a statement of policy.
27 //
28 // DO NOT CHANGE THIS DATA TO FIX BUILDS.
29 // Existing packages should not have their constraints relaxed
30 // without prior discussion.
31 // Negative assertions should almost never be removed.
32 //
33 // "a < b" means package b can import package a.
34 //
35 // See `go doc internal/dag' for the full syntax.
36 //
37 // All-caps names are pseudo-names for specific points
38 // in the dependency lattice.
39 var depsRules = `
40         # No dependencies allowed for any of these packages.
41         NONE
42         < constraints, container/list, container/ring,
43           internal/cfg, internal/cpu, internal/goarch,
44           internal/goexperiment, internal/goos,
45           internal/goversion, internal/nettrace,
46           unicode/utf8, unicode/utf16, unicode,
47           unsafe;
48
49         # These packages depend only on internal/goarch and unsafe.
50         internal/goarch, unsafe
51         < internal/abi;
52
53         # RUNTIME is the core runtime group of packages, all of them very light-weight.
54         internal/abi, internal/cpu, internal/goarch,
55         internal/goexperiment, internal/goos, unsafe
56         < internal/bytealg
57         < internal/itoa
58         < internal/unsafeheader
59         < runtime/internal/sys
60         < runtime/internal/syscall
61         < runtime/internal/atomic
62         < runtime/internal/math
63         < runtime
64         < sync/atomic
65         < internal/race
66         < sync
67         < internal/reflectlite
68         < errors
69         < internal/oserror, math/bits
70         < RUNTIME;
71
72         RUNTIME
73         < sort
74         < container/heap;
75
76         RUNTIME
77         < io;
78
79         syscall !< io;
80         reflect !< sort;
81
82         RUNTIME, unicode/utf8
83         < path;
84
85         unicode !< path;
86
87         # SYSCALL is RUNTIME plus the packages necessary for basic system calls.
88         RUNTIME, unicode/utf8, unicode/utf16
89         < internal/syscall/windows/sysdll, syscall/js
90         < syscall
91         < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
92         < internal/syscall/execenv
93         < SYSCALL;
94
95         # TIME is SYSCALL plus the core packages about time, including context.
96         SYSCALL
97         < time/tzdata
98         < time
99         < context
100         < TIME;
101
102         TIME, io, path, sort
103         < io/fs;
104
105         # MATH is RUNTIME plus the basic math packages.
106         RUNTIME
107         < math
108         < MATH;
109
110         unicode !< math;
111
112         MATH
113         < math/cmplx;
114
115         MATH
116         < math/rand;
117
118         MATH
119         < runtime/metrics;
120
121         MATH, unicode/utf8
122         < strconv;
123
124         unicode !< strconv;
125
126         # STR is basic string and buffer manipulation.
127         RUNTIME, io, unicode/utf8, unicode/utf16, unicode
128         < bytes, strings
129         < bufio;
130
131         bufio, path, strconv
132         < STR;
133
134         # OS is basic OS access, including helpers (path/filepath, os/exec, etc).
135         # OS includes string routines, but those must be layered above package os.
136         # OS does not include reflection.
137         io/fs
138         < internal/testlog
139         < internal/poll
140         < os
141         < os/signal;
142
143         io/fs
144         < embed;
145
146         unicode, fmt !< net, os, os/signal;
147
148         os/signal, STR
149         < path/filepath
150         < io/ioutil;
151
152         os < internal/godebug;
153
154         path/filepath, internal/godebug < os/exec;
155
156         io/ioutil, os/exec, os/signal
157         < OS;
158
159         reflect !< OS;
160
161         OS
162         < golang.org/x/sys/cpu;
163
164         # FMT is OS (which includes string routines) plus reflect and fmt.
165         # It does not include package log, which should be avoided in core packages.
166         strconv, unicode
167         < reflect;
168
169         os, reflect
170         < internal/fmtsort
171         < fmt;
172
173         OS, fmt
174         < FMT;
175
176         log !< FMT;
177
178         # Misc packages needing only FMT.
179         FMT
180         < html,
181           internal/dag,
182           internal/goroot,
183           mime/quotedprintable,
184           net/internal/socktest,
185           net/url,
186           runtime/trace,
187           text/scanner,
188           text/tabwriter;
189
190         # encodings
191         # core ones do not use fmt.
192         io, strconv
193         < encoding;
194
195         encoding, reflect
196         < encoding/binary
197         < encoding/base32, encoding/base64;
198
199         FMT, encoding < flag;
200
201         fmt !< encoding/base32, encoding/base64;
202
203         FMT, encoding/base32, encoding/base64
204         < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
205           encoding/json, encoding/pem, encoding/xml, mime;
206
207         # hashes
208         io
209         < hash
210         < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
211
212         # math/big
213         FMT, encoding/binary, math/rand
214         < math/big;
215
216         # compression
217         FMT, encoding/binary, hash/adler32, hash/crc32
218         < compress/bzip2, compress/flate, compress/lzw
219         < archive/zip, compress/gzip, compress/zlib;
220
221         # templates
222         FMT
223         < text/template/parse;
224
225         net/url, text/template/parse
226         < text/template
227         < internal/lazytemplate;
228
229         encoding/json, html, text/template
230         < html/template;
231
232         # regexp
233         FMT
234         < regexp/syntax
235         < regexp
236         < internal/lazyregexp;
237
238         # suffix array
239         encoding/binary, regexp
240         < index/suffixarray;
241
242         # executable parsing
243         FMT, encoding/binary, compress/zlib
244         < runtime/debug
245         < debug/dwarf
246         < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
247         < debug/buildinfo
248         < DEBUG;
249
250         # go parser and friends.
251         FMT
252         < go/token
253         < go/scanner
254         < go/ast
255         < go/internal/typeparams
256         < go/parser;
257
258         FMT
259         < go/build/constraint, go/doc/comment;
260
261         go/build/constraint, go/doc/comment, go/parser, text/tabwriter
262         < go/printer
263         < go/format;
264
265         go/doc/comment, go/parser, internal/lazyregexp, text/template
266         < go/doc;
267
268         math/big, go/token
269         < go/constant;
270
271         container/heap, go/constant, go/parser, regexp
272         < go/types;
273
274         FMT, internal/goexperiment
275         < internal/buildcfg;
276
277         go/build/constraint, go/doc, go/parser, internal/buildcfg, internal/goroot, internal/goversion
278         < go/build;
279
280         # databases
281         FMT
282         < database/sql/internal
283         < database/sql/driver
284         < database/sql;
285
286         # images
287         FMT, compress/lzw, compress/zlib
288         < image/color
289         < image, image/color/palette
290         < image/internal/imageutil
291         < image/draw
292         < image/gif, image/jpeg, image/png;
293
294         # cgo, delayed as long as possible.
295         # If you add a dependency on CGO, you must add the package
296         # to cgoPackages in cmd/dist/test.go as well.
297         RUNTIME
298         < C
299         < runtime/cgo
300         < CGO
301         < runtime/race, runtime/msan, runtime/asan;
302
303         # Bulk of the standard library must not use cgo.
304         # The prohibition stops at net and os/user.
305         C !< fmt, go/types, CRYPTO-MATH;
306
307         CGO, OS
308         < plugin;
309
310         CGO, FMT
311         < os/user
312         < archive/tar;
313
314         sync
315         < internal/singleflight;
316
317         os
318         < golang.org/x/net/dns/dnsmessage,
319           golang.org/x/net/lif,
320           golang.org/x/net/route;
321
322         os, runtime, strconv, sync, unsafe,
323         internal/godebug
324         < internal/intern;
325
326         internal/bytealg, internal/intern, internal/itoa, math/bits, sort, strconv
327         < net/netip;
328
329         # net is unavoidable when doing any networking,
330         # so large dependencies must be kept out.
331         # This is a long-looking list but most of these
332         # are small with few dependencies.
333         CGO,
334         golang.org/x/net/dns/dnsmessage,
335         golang.org/x/net/lif,
336         golang.org/x/net/route,
337         internal/godebug,
338         internal/nettrace,
339         internal/poll,
340         internal/singleflight,
341         internal/race,
342         net/netip,
343         os
344         < net;
345
346         fmt, unicode !< net;
347         math/rand !< net; # net uses runtime instead
348
349         # NET is net plus net-helper packages.
350         FMT, net
351         < net/textproto;
352
353         mime, net/textproto, net/url
354         < NET;
355
356         # logging - most packages should not import; http and up is allowed
357         FMT
358         < log;
359
360         log !< crypto/tls, database/sql, go/importer, testing;
361
362         FMT, log, net
363         < log/syslog;
364
365         NET, log
366         < net/mail;
367
368         NONE < crypto/internal/boring/sig, crypto/internal/boring/syso;
369         sync/atomic < crypto/internal/boring/bcache, crypto/internal/boring/fipstls;
370         crypto/internal/boring/sig, crypto/internal/boring/fipstls < crypto/tls/fipsonly;
371
372         # CRYPTO is core crypto algorithms - no cgo, fmt, net.
373         # Unfortunately, stuck with reflect via encoding/binary.
374         crypto/internal/boring/sig,
375         crypto/internal/boring/syso,
376         encoding/binary,
377         golang.org/x/sys/cpu,
378         hash, embed
379         < crypto
380         < crypto/subtle
381         < crypto/internal/subtle
382         < crypto/internal/nistec/fiat
383         < crypto/internal/nistec
384         < crypto/internal/edwards25519/field, golang.org/x/crypto/curve25519/internal/field
385         < crypto/internal/edwards25519
386         < crypto/cipher;
387
388         crypto/cipher,
389         crypto/internal/boring/bcache
390         < crypto/internal/boring
391         < crypto/boring
392         < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
393           crypto/sha1, crypto/sha256, crypto/sha512
394         < CRYPTO;
395
396         CGO, fmt, net !< CRYPTO;
397
398         # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
399         CRYPTO, FMT, math/big, embed
400         < crypto/internal/boring/bbig
401         < crypto/internal/randutil
402         < crypto/rand
403         < crypto/ed25519
404         < encoding/asn1
405         < golang.org/x/crypto/cryptobyte/asn1
406         < golang.org/x/crypto/cryptobyte
407         < golang.org/x/crypto/curve25519
408         < crypto/dsa, crypto/elliptic, crypto/rsa
409         < crypto/ecdsa
410         < CRYPTO-MATH;
411
412         CGO, net !< CRYPTO-MATH;
413
414         # TLS, Prince of Dependencies.
415         CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
416         < golang.org/x/crypto/internal/subtle
417         < golang.org/x/crypto/chacha20
418         < golang.org/x/crypto/internal/poly1305
419         < golang.org/x/crypto/chacha20poly1305
420         < golang.org/x/crypto/hkdf
421         < crypto/x509/internal/macos
422         < crypto/x509/pkix;
423
424         crypto/internal/boring/fipstls, crypto/x509/pkix
425         < crypto/x509
426         < crypto/tls;
427
428         # crypto-aware packages
429
430         DEBUG, go/build, go/types, text/scanner, crypto/md5
431         < internal/pkgbits
432         < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
433         < go/importer;
434
435         NET, crypto/rand, mime/quotedprintable
436         < mime/multipart;
437
438         crypto/tls
439         < net/smtp;
440
441         # HTTP, King of Dependencies.
442
443         FMT
444         < golang.org/x/net/http2/hpack
445         < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
446
447         FMT, NET, container/list, encoding/binary, log
448         < golang.org/x/text/transform
449         < golang.org/x/text/unicode/norm
450         < golang.org/x/text/unicode/bidi
451         < golang.org/x/text/secure/bidirule
452         < golang.org/x/net/idna
453         < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
454
455         NET, crypto/tls
456         < net/http/httptrace;
457
458         compress/gzip,
459         golang.org/x/net/http/httpguts,
460         golang.org/x/net/http/httpproxy,
461         golang.org/x/net/http2/hpack,
462         net/http/internal,
463         net/http/internal/ascii,
464         net/http/internal/testcert,
465         net/http/httptrace,
466         mime/multipart,
467         log
468         < net/http;
469
470         # HTTP-aware packages
471
472         encoding/json, net/http
473         < expvar;
474
475         net/http, net/http/internal/ascii
476         < net/http/cookiejar, net/http/httputil;
477
478         net/http, flag
479         < net/http/httptest;
480
481         net/http, regexp
482         < net/http/cgi
483         < net/http/fcgi;
484
485         # Profiling
486         FMT, compress/gzip, encoding/binary, text/tabwriter
487         < runtime/pprof;
488
489         OS, compress/gzip, regexp
490         < internal/profile;
491
492         html, internal/profile, net/http, runtime/pprof, runtime/trace
493         < net/http/pprof;
494
495         # RPC
496         encoding/gob, encoding/json, go/token, html/template, net/http
497         < net/rpc
498         < net/rpc/jsonrpc;
499
500         # System Information
501         internal/cpu, sync
502         < internal/sysinfo;
503
504         # Test-only
505         log
506         < testing/iotest
507         < testing/fstest;
508
509         FMT, flag, math/rand
510         < testing/quick;
511
512         FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
513         < testing;
514
515         FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
516         internal/godebug, math/rand, encoding/hex, crypto/sha256
517         < internal/fuzz;
518
519         internal/fuzz, internal/testlog, runtime/pprof, regexp
520         < testing/internal/testdeps;
521
522         OS, flag, testing, internal/cfg
523         < internal/testenv;
524
525         OS, encoding/base64
526         < internal/obscuretestdata;
527
528         CGO, OS, fmt
529         < os/signal/internal/pty;
530
531         NET, testing, math/rand
532         < golang.org/x/net/nettest;
533
534         syscall
535         < os/exec/internal/fdtest;
536
537         FMT, container/heap, math/rand
538         < internal/trace;
539
540         FMT
541         < internal/diff, internal/txtar;
542 `
543
544 // listStdPkgs returns the same list of packages as "go list std".
545 func listStdPkgs(goroot string) ([]string, error) {
546         // Based on cmd/go's matchPackages function.
547         var pkgs []string
548
549         src := filepath.Join(goroot, "src") + string(filepath.Separator)
550         walkFn := func(path string, d fs.DirEntry, err error) error {
551                 if err != nil || !d.IsDir() || path == src {
552                         return nil
553                 }
554
555                 base := filepath.Base(path)
556                 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
557                         return filepath.SkipDir
558                 }
559
560                 name := filepath.ToSlash(path[len(src):])
561                 if name == "builtin" || name == "cmd" {
562                         return filepath.SkipDir
563                 }
564
565                 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
566                 return nil
567         }
568         if err := filepath.WalkDir(src, walkFn); err != nil {
569                 return nil, err
570         }
571         return pkgs, nil
572 }
573
574 func TestDependencies(t *testing.T) {
575         if !testenv.HasSrc() {
576                 // Tests run in a limited file system and we do not
577                 // provide access to every source file.
578                 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
579         }
580
581         ctxt := Default
582         all, err := listStdPkgs(ctxt.GOROOT)
583         if err != nil {
584                 t.Fatal(err)
585         }
586         sort.Strings(all)
587
588         sawImport := map[string]map[string]bool{} // from package => to package => true
589         policy := depsPolicy(t)
590
591         for _, pkg := range all {
592                 imports, err := findImports(pkg)
593                 if err != nil {
594                         t.Error(err)
595                         continue
596                 }
597                 if sawImport[pkg] == nil {
598                         sawImport[pkg] = map[string]bool{}
599                 }
600                 var bad []string
601                 for _, imp := range imports {
602                         sawImport[pkg][imp] = true
603                         if !policy.HasEdge(pkg, imp) {
604                                 bad = append(bad, imp)
605                         }
606                 }
607                 if bad != nil {
608                         t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
609                 }
610         }
611 }
612
613 var buildIgnore = []byte("\n//go:build ignore")
614
615 func findImports(pkg string) ([]string, error) {
616         vpkg := pkg
617         if strings.HasPrefix(pkg, "golang.org") {
618                 vpkg = "vendor/" + pkg
619         }
620         dir := filepath.Join(Default.GOROOT, "src", vpkg)
621         files, err := os.ReadDir(dir)
622         if err != nil {
623                 return nil, err
624         }
625         var imports []string
626         var haveImport = map[string]bool{}
627         if pkg == "crypto/internal/boring" {
628                 haveImport["C"] = true // kludge: prevent C from appearing in crypto/internal/boring imports
629         }
630         fset := token.NewFileSet()
631         for _, file := range files {
632                 name := file.Name()
633                 if name == "slice_go14.go" || name == "slice_go18.go" {
634                         // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
635                         continue
636                 }
637                 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
638                         continue
639                 }
640                 info := fileInfo{
641                         name: filepath.Join(dir, name),
642                         fset: fset,
643                 }
644                 f, err := os.Open(info.name)
645                 if err != nil {
646                         return nil, err
647                 }
648                 err = readGoInfo(f, &info)
649                 f.Close()
650                 if err != nil {
651                         return nil, fmt.Errorf("reading %v: %v", name, err)
652                 }
653                 if info.parsed.Name.Name == "main" {
654                         continue
655                 }
656                 if bytes.Contains(info.header, buildIgnore) {
657                         continue
658                 }
659                 for _, imp := range info.imports {
660                         path := imp.path
661                         if !haveImport[path] {
662                                 haveImport[path] = true
663                                 imports = append(imports, path)
664                         }
665                 }
666         }
667         sort.Strings(imports)
668         return imports, nil
669 }
670
671 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
672 func depsPolicy(t *testing.T) *dag.Graph {
673         g, err := dag.Parse(depsRules)
674         if err != nil {
675                 t.Fatal(err)
676         }
677         return g
678 }
679
680 // TestStdlibLowercase tests that all standard library package names are
681 // lowercase. See Issue 40065.
682 func TestStdlibLowercase(t *testing.T) {
683         if !testenv.HasSrc() {
684                 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
685         }
686
687         ctxt := Default
688         all, err := listStdPkgs(ctxt.GOROOT)
689         if err != nil {
690                 t.Fatal(err)
691         }
692
693         for _, pkgname := range all {
694                 if strings.ToLower(pkgname) != pkgname {
695                         t.Errorf("package %q should not use upper-case path", pkgname)
696                 }
697         }
698 }
699
700 // TestFindImports tests that findImports works.  See #43249.
701 func TestFindImports(t *testing.T) {
702         imports, err := findImports("go/build")
703         if err != nil {
704                 t.Fatal(err)
705         }
706         t.Logf("go/build imports %q", imports)
707         want := []string{"bytes", "os", "path/filepath", "strings"}
708 wantLoop:
709         for _, w := range want {
710                 for _, imp := range imports {
711                         if imp == w {
712                                 continue wantLoop
713                         }
714                 }
715                 t.Errorf("expected to find %q in import list", w)
716         }
717 }