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