]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/build/deps_test.go
cmd/compile: set correct type for OpIData
[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         "internal/testenv"
14         "io/fs"
15         "os"
16         "path/filepath"
17         "runtime"
18         "sort"
19         "strings"
20         "testing"
21 )
22
23 // depsRules defines the expected dependencies between packages in
24 // the Go source tree. It is a statement of policy.
25 //
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.
30 //
31 // The general syntax of a rule is:
32 //
33 //              a, b < c, d;
34 //
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.
38 //
39 // The rules can chain together, as in:
40 //
41 //              e < f, g < h;
42 //
43 // which is equivalent to
44 //
45 //              e < f, g;
46 //              f, g < h;
47 //
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.)
55 //
56 // Negative assertions double-check the partial order:
57 //
58 //              i !< j
59 //
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.
63 //
64 // Comments begin with #.
65 //
66 // All-caps names are pseudo-names for specific points
67 // in the dependency lattice.
68 //
69 var depsRules = `
70         # No dependencies allowed for any of these packages.
71         NONE
72         < container/list, container/ring,
73           internal/cfg, internal/cpu,
74           internal/goversion, internal/nettrace,
75           unicode/utf8, unicode/utf16, unicode,
76           unsafe;
77
78         # RUNTIME is the core runtime group of packages, all of them very light-weight.
79         internal/cpu, unsafe
80         < internal/bytealg
81         < internal/unsafeheader
82         < runtime/internal/sys
83         < runtime/internal/atomic
84         < runtime/internal/math
85         < runtime
86         < sync/atomic
87         < internal/race
88         < sync
89         < internal/reflectlite
90         < errors
91         < internal/oserror, math/bits
92         < RUNTIME;
93
94         RUNTIME
95         < sort
96         < container/heap;
97
98         RUNTIME
99         < io;
100
101         syscall !< io;
102         reflect !< sort;
103
104         RUNTIME, unicode/utf8
105         < path;
106
107         unicode !< path;
108
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
112         < syscall
113         < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
114         < internal/syscall/execenv
115         < SYSCALL;
116
117         # TIME is SYSCALL plus the core packages about time, including context.
118         SYSCALL
119         < time/tzdata
120         < time
121         < context
122         < TIME;
123
124         TIME, io, path, sort
125         < io/fs;
126
127         # MATH is RUNTIME plus the basic math packages.
128         RUNTIME
129         < math
130         < MATH;
131
132         unicode !< math;
133
134         MATH
135         < math/cmplx;
136
137         MATH
138         < math/rand;
139
140         MATH
141         < runtime/metrics;
142
143         MATH, unicode/utf8
144         < strconv;
145
146         unicode !< strconv;
147
148         # STR is basic string and buffer manipulation.
149         RUNTIME, io, unicode/utf8, unicode/utf16, unicode
150         < bytes, strings
151         < bufio;
152
153         bufio, path, strconv
154         < STR;
155
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.
159         io/fs
160         < internal/testlog
161         < internal/poll
162         < os
163         < os/signal;
164
165         unicode, fmt !< os, os/signal;
166
167         os/signal, STR
168         < path/filepath
169         < io/ioutil, os/exec;
170
171         io/ioutil, os/exec, os/signal
172         < OS;
173
174         reflect !< OS;
175
176         OS
177         < golang.org/x/sys/cpu, internal/goroot;
178
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.
181         strconv, unicode
182         < reflect;
183
184         os, reflect
185         < internal/fmtsort
186         < fmt;
187
188         OS, fmt
189         < FMT;
190
191         log !< FMT;
192
193         # Misc packages needing only FMT.
194         FMT
195         < flag,
196           html,
197           mime/quotedprintable,
198           net/internal/socktest,
199           net/url,
200           runtime/debug,
201           runtime/trace,
202           text/scanner,
203           text/tabwriter;
204
205         # encodings
206         # core ones do not use fmt.
207         io, strconv
208         < encoding;
209
210         encoding, reflect
211         < encoding/binary
212         < encoding/base32, encoding/base64;
213
214         fmt !< encoding/base32, encoding/base64;
215
216         FMT, encoding/base32, encoding/base64
217         < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
218           encoding/json, encoding/pem, encoding/xml, mime;
219
220         # hashes
221         io
222         < hash
223         < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
224
225         # math/big
226         FMT, encoding/binary, math/rand
227         < math/big;
228
229         # compression
230         FMT, encoding/binary, hash/adler32, hash/crc32
231         < compress/bzip2, compress/flate, compress/lzw
232         < archive/zip, compress/gzip, compress/zlib;
233
234         # templates
235         FMT
236         < text/template/parse;
237
238         net/url, text/template/parse
239         < text/template
240         < internal/lazytemplate;
241
242         encoding/json, html, text/template
243         < html/template;
244
245         # regexp
246         FMT
247         < regexp/syntax
248         < regexp
249         < internal/lazyregexp;
250
251         # suffix array
252         encoding/binary, regexp
253         < index/suffixarray;
254
255         # executable parsing
256         FMT, encoding/binary, compress/zlib
257         < debug/dwarf
258         < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
259         < DEBUG;
260
261         # go parser and friends.
262         FMT
263         < go/token
264         < go/scanner
265         < go/ast
266         < go/parser;
267
268         go/parser, text/tabwriter
269         < go/printer
270         < go/format;
271
272         go/parser, internal/lazyregexp, text/template
273         < go/doc;
274
275         math/big, go/token
276         < go/constant;
277
278         container/heap, go/constant, go/parser
279         < go/types;
280
281         go/doc, go/parser, internal/goroot, internal/goversion
282         < go/build;
283
284         DEBUG, go/build, go/types, text/scanner
285         < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
286         < go/importer;
287
288         # databases
289         FMT
290         < database/sql/internal
291         < database/sql/driver
292         < database/sql;
293
294         # images
295         FMT, compress/lzw, compress/zlib
296         < image/color
297         < image, image/color/palette
298         < image/internal/imageutil
299         < image/draw
300         < image/gif, image/jpeg, image/png;
301
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.
305         RUNTIME
306         < C
307         < runtime/cgo
308         < CGO
309         < runtime/race, runtime/msan;
310
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;
314
315         CGO, OS
316         < plugin;
317
318         CGO, FMT
319         < os/user
320         < archive/tar;
321
322         sync
323         < internal/singleflight;
324
325         os
326         < golang.org/x/net/dns/dnsmessage,
327           golang.org/x/net/lif,
328           golang.org/x/net/route;
329
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.
334         CGO,
335         golang.org/x/net/dns/dnsmessage,
336         golang.org/x/net/lif,
337         golang.org/x/net/route,
338         internal/nettrace,
339         internal/poll,
340         internal/singleflight,
341         internal/race,
342         os
343         < net;
344
345         fmt, unicode !< net;
346         math/rand !< net; # net uses runtime instead
347
348         # NET is net plus net-helper packages.
349         FMT, net
350         < net/textproto;
351
352         mime, net/textproto, net/url
353         < NET;
354
355         # logging - most packages should not import; http and up is allowed
356         FMT
357         < log;
358
359         log !< crypto/tls, database/sql, go/importer, testing;
360
361         FMT, log, net
362         < log/syslog;
363
364         NET, log
365         < net/mail;
366
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
370         < crypto
371         < crypto/subtle
372         < crypto/internal/subtle
373         < crypto/cipher
374         < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
375           crypto/sha1, crypto/sha256, crypto/sha512
376         < CRYPTO;
377
378         CGO, fmt, net !< CRYPTO;
379
380         # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
381         CRYPTO, FMT, math/big
382         < crypto/rand
383         < crypto/internal/randutil
384         < crypto/ed25519/internal/edwards25519
385         < crypto/ed25519
386         < encoding/asn1
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
391         < crypto/ecdsa
392         < CRYPTO-MATH;
393
394         CGO, net !< CRYPTO-MATH;
395
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
404         < crypto/x509/pkix
405         < crypto/x509
406         < crypto/tls;
407
408         # crypto-aware packages
409
410         NET, crypto/rand, mime/quotedprintable
411         < mime/multipart;
412
413         crypto/tls
414         < net/smtp;
415
416         # HTTP, King of Dependencies.
417
418         FMT
419         < golang.org/x/net/http2/hpack, net/http/internal;
420
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;
428
429         NET, crypto/tls
430         < net/http/httptrace;
431
432         compress/gzip,
433         golang.org/x/net/http/httpguts,
434         golang.org/x/net/http/httpproxy,
435         golang.org/x/net/http2/hpack,
436         net/http/internal,
437         net/http/httptrace,
438         mime/multipart,
439         log
440         < net/http;
441
442         # HTTP-aware packages
443
444         encoding/json, net/http
445         < expvar;
446
447         net/http
448         < net/http/cookiejar, net/http/httputil;
449
450         net/http, flag
451         < net/http/httptest;
452
453         net/http, regexp
454         < net/http/cgi
455         < net/http/fcgi;
456
457         # Profiling
458         FMT, compress/gzip, encoding/binary, text/tabwriter
459         < runtime/pprof;
460
461         OS, compress/gzip, regexp
462         < internal/profile;
463
464         html, internal/profile, net/http, runtime/pprof, runtime/trace
465         < net/http/pprof;
466
467         # RPC
468         encoding/gob, encoding/json, go/token, html/template, net/http
469         < net/rpc
470         < net/rpc/jsonrpc;
471
472         # System Information
473         internal/cpu, sync
474         < internal/sysinfo;
475
476         # Test-only
477         log
478         < testing/iotest
479         < testing/fstest;
480
481         FMT, flag, math/rand
482         < testing/quick;
483
484         FMT, flag, runtime/debug, runtime/trace, internal/sysinfo
485         < testing;
486
487         internal/testlog, runtime/pprof, regexp
488         < testing/internal/testdeps;
489
490         OS, flag, testing, internal/cfg
491         < internal/testenv;
492
493         OS, encoding/base64
494         < internal/obscuretestdata;
495
496         CGO, OS, fmt
497         < os/signal/internal/pty;
498
499         NET, testing, math/rand
500         < golang.org/x/net/nettest;
501
502         FMT, container/heap, math/rand
503         < internal/trace;
504 `
505
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.
509         var pkgs []string
510
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 {
514                         return nil
515                 }
516
517                 base := filepath.Base(path)
518                 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
519                         return filepath.SkipDir
520                 }
521
522                 name := filepath.ToSlash(path[len(src):])
523                 if name == "builtin" || name == "cmd" {
524                         return filepath.SkipDir
525                 }
526
527                 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
528                 return nil
529         }
530         if err := filepath.WalkDir(src, walkFn); err != nil {
531                 return nil, err
532         }
533         return pkgs, nil
534 }
535
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)
541         }
542
543         ctxt := Default
544         all, err := listStdPkgs(ctxt.GOROOT)
545         if err != nil {
546                 t.Fatal(err)
547         }
548         sort.Strings(all)
549
550         sawImport := map[string]map[string]bool{} // from package => to package => true
551         policy := depsPolicy(t)
552
553         for _, pkg := range all {
554                 imports, err := findImports(pkg)
555                 if err != nil {
556                         t.Error(err)
557                         continue
558                 }
559                 if sawImport[pkg] == nil {
560                         sawImport[pkg] = map[string]bool{}
561                 }
562                 ok := policy[pkg]
563                 var bad []string
564                 for _, imp := range imports {
565                         sawImport[pkg][imp] = true
566                         if !ok[imp] {
567                                 bad = append(bad, imp)
568                         }
569                 }
570                 if bad != nil {
571                         t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
572                 }
573         }
574
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
581                 }
582                 for pkg := range sawImport[from] {
583                         if p := depPath(pkg, to); p != "" {
584                                 return from + " => " + p
585                         }
586                 }
587                 return ""
588         }
589 }
590
591 var buildIgnore = []byte("\n// +build ignore")
592
593 func findImports(pkg string) ([]string, error) {
594         vpkg := pkg
595         if strings.HasPrefix(pkg, "golang.org") {
596                 vpkg = "vendor/" + pkg
597         }
598         dir := filepath.Join(Default.GOROOT, "src", vpkg)
599         files, err := os.ReadDir(dir)
600         if err != nil {
601                 return nil, err
602         }
603         var imports []string
604         var haveImport = map[string]bool{}
605         for _, file := range files {
606                 name := file.Name()
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.
609                         continue
610                 }
611                 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
612                         continue
613                 }
614                 var info fileInfo
615                 info.name = filepath.Join(dir, name)
616                 f, err := os.Open(info.name)
617                 if err != nil {
618                         return nil, err
619                 }
620                 err = readGoInfo(f, &info)
621                 f.Close()
622                 if err != nil {
623                         return nil, fmt.Errorf("reading %v: %v", name, err)
624                 }
625                 if bytes.Contains(info.header, buildIgnore) {
626                         continue
627                 }
628                 for _, imp := range info.imports {
629                         path := imp.path
630                         if !haveImport[path] {
631                                 haveImport[path] = true
632                                 imports = append(imports, path)
633                         }
634                 }
635         }
636         sort.Strings(imports)
637         return imports, nil
638 }
639
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{}
644
645         parseDepsRules(t, func(deps []string, op string, users []string) {
646                 if op == "!<" {
647                         disallowed = append(disallowed, [2][]string{deps, users})
648                         return
649                 }
650                 for _, u := range users {
651                         if allowed[u] != nil {
652                                 t.Errorf("multiple deps lists for %s", u)
653                         }
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)
658                                 }
659                                 allowed[u][d] = true
660                         }
661                 }
662         })
663
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)
669                         }
670                 }
671         }
672
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] {
678                                         if i == 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)
683                                         }
684                                         allowed[i][j] = true
685                                 }
686                         }
687                 }
688         }
689
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 {
695                                 if allowed[u][d] {
696                                         t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
697                                 }
698                         }
699                 }
700         }
701
702         if t.Failed() {
703                 t.FailNow()
704         }
705
706         return allowed
707 }
708
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}
714
715         var prev []string
716         var op string
717         for {
718                 list, tok := p.nextList()
719                 if tok == "" {
720                         if prev == nil {
721                                 break
722                         }
723                         p.syntaxError("unexpected EOF")
724                 }
725                 if prev != nil {
726                         save(prev, op, list)
727                 }
728                 prev = list
729                 if tok == ";" {
730                         prev = nil
731                         op = ""
732                         continue
733                 }
734                 if tok != "<" && tok != "!<" {
735                         p.syntaxError("missing <")
736                 }
737                 op = tok
738         }
739 }
740
741 // A depsParser parses the depsRules syntax described above.
742 type depsParser struct {
743         t        *testing.T
744         lineno   int
745         lastWord string
746         text     string
747 }
748
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)
752 }
753
754 // nextList parses and returns a comma-separated list of names.
755 func (p *depsParser) nextList() (list []string, token string) {
756         for {
757                 tok := p.nextToken()
758                 switch tok {
759                 case "":
760                         if len(list) == 0 {
761                                 return nil, ""
762                         }
763                         fallthrough
764                 case ",", "<", "!<", ";":
765                         p.syntaxError("bad list syntax")
766                 }
767                 list = append(list, tok)
768
769                 tok = p.nextToken()
770                 if tok != "," {
771                         return list, tok
772                 }
773         }
774 }
775
776 // nextToken returns the next token in the deps rules,
777 // one of ";" "," "<" "!<" or a name.
778 func (p *depsParser) nextToken() string {
779         for {
780                 if p.text == "" {
781                         return ""
782                 }
783                 switch p.text[0] {
784                 case ';', ',', '<':
785                         t := p.text[:1]
786                         p.text = p.text[1:]
787                         return t
788
789                 case '!':
790                         if len(p.text) < 2 || p.text[1] != '<' {
791                                 p.syntaxError("unexpected token !")
792                         }
793                         p.text = p.text[2:]
794                         return "!<"
795
796                 case '#':
797                         i := strings.Index(p.text, "\n")
798                         if i < 0 {
799                                 i = len(p.text)
800                         }
801                         p.text = p.text[i:]
802                         continue
803
804                 case '\n':
805                         p.lineno++
806                         fallthrough
807                 case ' ', '\t':
808                         p.text = p.text[1:]
809                         continue
810
811                 default:
812                         i := strings.IndexAny(p.text, "!;,<#\n \t")
813                         if i < 0 {
814                                 i = len(p.text)
815                         }
816                         t := p.text[:i]
817                         p.text = p.text[i:]
818                         p.lastWord = t
819                         return t
820                 }
821         }
822 }
823
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)
829         }
830
831         ctxt := Default
832         all, err := listStdPkgs(ctxt.GOROOT)
833         if err != nil {
834                 t.Fatal(err)
835         }
836
837         for _, pkgname := range all {
838                 if strings.ToLower(pkgname) != pkgname {
839                         t.Errorf("package %q should not use upper-case path", pkgname)
840                 }
841         }
842 }