]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/build/deps_test.go
go/build: rewrite TestDependencies to be cleaner, more correct
[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         "io/ioutil"
14         "os"
15         "path/filepath"
16         "runtime"
17         "sort"
18         "strconv"
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         reflect !< sort;
102
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
106         < syscall
107         < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
108         < internal/syscall/execenv
109         < SYSCALL;
110
111         # TIME is SYSCALL plus the core packages about time, including context.
112         SYSCALL
113         < time/tzdata
114         < time
115         < context
116         < TIME;
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, unicode/utf8
132         < strconv;
133
134         unicode !< strconv;
135
136         # STR is basic string and buffer manipulation.
137         RUNTIME, io, unicode/utf8, unicode/utf16, unicode
138         < bytes, strings
139         < bufio, path;
140
141         bufio, path, strconv
142         < STR;
143
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.
147         TIME, io, sort
148         < internal/testlog
149         < internal/poll
150         < os
151         < os/signal;
152
153         unicode, fmt !< os, os/signal;
154
155         os/signal, STR
156         < path/filepath
157         < io/ioutil, os/exec
158         < OS;
159
160         reflect !< OS;
161
162         OS
163         < golang.org/x/sys/cpu, internal/goroot;
164
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.
167         strconv, unicode
168         < reflect;
169
170         os, reflect
171         < internal/fmtsort
172         < fmt;
173
174         OS, fmt
175         < FMT;
176
177         log !< FMT;
178
179         # Misc packages needing only FMT.
180         FMT
181         < flag,
182           html,
183           mime/quotedprintable,
184           net/internal/socktest,
185           net/url,
186           runtime/debug,
187           runtime/trace,
188           text/scanner,
189           text/tabwriter;
190
191         # encodings
192         # core ones do not use fmt.
193         io, strconv
194         < encoding;
195
196         encoding, reflect
197         < encoding/binary
198         < encoding/base32, encoding/base64;
199
200         fmt !< encoding/base32, encoding/base64;
201
202         FMT, encoding/base32, encoding/base64
203         < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
204           encoding/json, encoding/pem, encoding/xml, mime;
205
206         # hashes
207         io
208         < hash
209         < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
210
211         # math/big
212         FMT, encoding/binary, math/rand
213         < math/big;
214
215         # compression
216         FMT, encoding/binary, hash/adler32, hash/crc32
217         < compress/bzip2, compress/flate, compress/lzw
218         < archive/zip, compress/gzip, compress/zlib;
219
220         # templates
221         FMT
222         < text/template/parse;
223
224         net/url, text/template/parse
225         < text/template
226         < internal/lazytemplate;
227
228         encoding/json, html, text/template
229         < html/template;
230
231         # regexp
232         FMT
233         < regexp/syntax
234         < regexp
235         < internal/lazyregexp;
236
237         # suffix array
238         encoding/binary, regexp
239         < index/suffixarray;
240
241         # executable parsing
242         FMT, encoding/binary, compress/zlib
243         < debug/dwarf
244         < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
245         < DEBUG;
246
247         # go parser and friends.
248         FMT
249         < go/token
250         < go/scanner
251         < go/ast
252         < go/parser;
253
254         go/parser, text/tabwriter
255         < go/printer
256         < go/format;
257
258         go/parser, internal/lazyregexp, text/template
259         < go/doc;
260
261         math/big, go/token
262         < go/constant;
263
264         container/heap, go/constant, go/parser
265         < go/types;
266
267         go/doc, go/parser, internal/goroot, internal/goversion
268         < go/build;
269
270         DEBUG, go/build, go/types, text/scanner
271         < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
272         < go/importer;
273
274         # databases
275         FMT
276         < database/sql/internal
277         < database/sql/driver
278         < database/sql;
279
280         # images
281         FMT, compress/lzw, compress/zlib
282         < image/color
283         < image, image/color/palette
284         < image/internal/imageutil
285         < image/draw
286         < image/gif, image/jpeg, image/png;
287
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.
291         RUNTIME
292         < C
293         < runtime/cgo
294         < CGO
295         < runtime/race, runtime/msan;
296
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;
300
301         CGO, OS
302         < plugin;
303
304         CGO, FMT
305         < os/user
306         < archive/tar;
307
308         sync
309         < internal/singleflight;
310
311         os
312         < golang.org/x/net/dns/dnsmessage,
313           golang.org/x/net/lif,
314           golang.org/x/net/route;
315
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.
321         CGO,
322         golang.org/x/net/dns/dnsmessage,
323         golang.org/x/net/lif,
324         golang.org/x/net/route,
325         internal/nettrace,
326         internal/poll,
327         internal/singleflight,
328         internal/race,
329         math/rand,
330         os
331         < net;
332
333         fmt, unicode !< net;
334
335         # NET is net plus net-helper packages.
336         FMT, net
337         < net/textproto;
338
339         mime, net/textproto, net/url
340         < NET;
341
342         # logging - most packages should not import; http and up is allowed
343         FMT
344         < log;
345
346         log !< crypto/tls, database/sql, go/importer, testing;
347
348         FMT, log, net
349         < log/syslog;
350
351         NET, log
352         < net/mail;
353
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
357         < crypto
358         < crypto/subtle
359         < crypto/internal/subtle
360         < crypto/cipher
361         < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
362           crypto/sha1, crypto/sha256, crypto/sha512
363         < CRYPTO;
364
365         CGO, fmt, net !< CRYPTO;
366
367         # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
368         CRYPTO, FMT, math/big
369         < crypto/rand
370         < crypto/internal/randutil
371         < crypto/ed25519/internal/edwards25519
372         < crypto/ed25519
373         < encoding/asn1
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
378         < crypto/ecdsa
379         < CRYPTO-MATH;
380
381         CGO, net !< CRYPTO-MATH;
382
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
391         < crypto/x509/pkix
392         < crypto/x509
393         < crypto/tls;
394
395         # crypto-aware packages
396
397         NET, crypto/rand, mime/quotedprintable
398         < mime/multipart;
399
400         crypto/tls
401         < net/smtp;
402
403         # HTTP, King of Dependencies.
404
405         FMT
406         < golang.org/x/net/http2/hpack, net/http/internal;
407
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;
415
416         NET, crypto/tls
417         < net/http/httptrace;
418
419         compress/gzip,
420         golang.org/x/net/http/httpguts,
421         golang.org/x/net/http/httpproxy,
422         golang.org/x/net/http2/hpack,
423         net/http/internal,
424         net/http/httptrace,
425         mime/multipart,
426         log
427         < net/http;
428
429         # HTTP-aware packages
430
431         encoding/json, net/http
432         < expvar;
433
434         net/http
435         < net/http/cookiejar, net/http/httputil;
436
437         net/http, flag
438         < net/http/httptest;
439
440         net/http, regexp
441         < net/http/cgi
442         < net/http/fcgi;
443
444         # Profiling
445         FMT, compress/gzip, encoding/binary, text/tabwriter
446         < runtime/pprof;
447
448         OS, compress/gzip, regexp
449         < internal/profile;
450
451         html/template, internal/profile, net/http, runtime/pprof, runtime/trace
452         < net/http/pprof;
453
454         # RPC
455         encoding/gob, encoding/json, go/token, html/template, net/http
456         < net/rpc
457         < net/rpc/jsonrpc;
458
459         # Test-only
460         log
461         < testing/iotest;
462
463         FMT, flag, math/rand
464         < testing/quick;
465
466         FMT, flag, runtime/debug, runtime/trace
467         < testing;
468
469         internal/testlog, runtime/pprof, regexp
470         < testing/internal/testdeps;
471
472         OS, flag, testing, internal/cfg
473         < internal/testenv;
474
475         OS, encoding/base64
476         < internal/obscuretestdata;
477
478         CGO, OS, fmt
479         < os/signal/internal/pty;
480
481         NET, testing
482         < golang.org/x/net/nettest;
483
484         FMT, container/heap, math/rand
485         < internal/trace;
486 `
487
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.
491         var pkgs []string
492
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 {
496                         return nil
497                 }
498
499                 base := filepath.Base(path)
500                 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
501                         return filepath.SkipDir
502                 }
503
504                 name := filepath.ToSlash(path[len(src):])
505                 if name == "builtin" || name == "cmd" {
506                         return filepath.SkipDir
507                 }
508
509                 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
510                 return nil
511         }
512         if err := filepath.Walk(src, walkFn); err != nil {
513                 return nil, err
514         }
515         return pkgs, nil
516 }
517
518 func TestDependencies(t *testing.T) {
519         iOS := runtime.GOOS == "darwin" && runtime.GOARCH == "arm64"
520         if iOS {
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)
524         }
525
526         ctxt := Default
527         all, err := listStdPkgs(ctxt.GOROOT)
528         if err != nil {
529                 t.Fatal(err)
530         }
531         sort.Strings(all)
532
533         sawImport := map[string]map[string]bool{} // from package => to package => true
534         policy := depsPolicy(t)
535
536         for _, pkg := range all {
537                 imports, err := findImports(pkg)
538                 if err != nil {
539                         t.Error(err)
540                         continue
541                 }
542                 if sawImport[pkg] == nil {
543                         sawImport[pkg] = map[string]bool{}
544                 }
545                 ok := policy[pkg]
546                 var bad []string
547                 for _, imp := range imports {
548                         sawImport[pkg][imp] = true
549                         if !ok[imp] {
550                                 bad = append(bad, imp)
551                         }
552                 }
553                 if bad != nil {
554                         t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
555                 }
556         }
557
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
564                 }
565                 for pkg := range sawImport[from] {
566                         if p := depPath(pkg, to); p != "" {
567                                 return from + " => " + p
568                         }
569                 }
570                 return ""
571         }
572 }
573
574 var buildIgnore = []byte("\n// +build ignore")
575
576 func findImports(pkg string) ([]string, error) {
577         vpkg := pkg
578         if strings.HasPrefix(pkg, "golang.org") {
579                 vpkg = "vendor/" + pkg
580         }
581         dir := filepath.Join(Default.GOROOT, "src", vpkg)
582         files, err := ioutil.ReadDir(dir)
583         if err != nil {
584                 return nil, err
585         }
586         var imports []string
587         var haveImport = map[string]bool{}
588         for _, file := range files {
589                 name := file.Name()
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.
592                         continue
593                 }
594                 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
595                         continue
596                 }
597                 f, err := os.Open(filepath.Join(dir, name))
598                 if err != nil {
599                         return nil, err
600                 }
601                 var imp []string
602                 data, err := readImports(f, false, &imp)
603                 f.Close()
604                 if err != nil {
605                         return nil, fmt.Errorf("reading %v: %v", name, err)
606                 }
607                 if bytes.Contains(data, buildIgnore) {
608                         continue
609                 }
610                 for _, quoted := range imp {
611                         path, err := strconv.Unquote(quoted)
612                         if err != nil {
613                                 continue
614                         }
615                         if !haveImport[path] {
616                                 haveImport[path] = true
617                                 imports = append(imports, path)
618                         }
619                 }
620         }
621         sort.Strings(imports)
622         return imports, nil
623 }
624
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{}
629
630         parseDepsRules(t, func(deps []string, op string, users []string) {
631                 if op == "!<" {
632                         disallowed = append(disallowed, [2][]string{deps, users})
633                         return
634                 }
635                 for _, u := range users {
636                         if allowed[u] != nil {
637                                 t.Errorf("multiple deps lists for %s", u)
638                         }
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)
643                                 }
644                                 allowed[u][d] = true
645                         }
646                 }
647         })
648
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)
654                         }
655                 }
656         }
657
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] {
663                                         if i == 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)
668                                         }
669                                         allowed[i][j] = true
670                                 }
671                         }
672                 }
673         }
674
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 {
680                                 if allowed[u][d] {
681                                         t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
682                                 }
683                         }
684                 }
685         }
686
687         if t.Failed() {
688                 t.FailNow()
689         }
690
691         return allowed
692 }
693
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}
699
700         var prev []string
701         var op string
702         for {
703                 list, tok := p.nextList()
704                 if tok == "" {
705                         if prev == nil {
706                                 break
707                         }
708                         p.syntaxError("unexpected EOF")
709                 }
710                 if prev != nil {
711                         save(prev, op, list)
712                 }
713                 prev = list
714                 if tok == ";" {
715                         prev = nil
716                         op = ""
717                         continue
718                 }
719                 if tok != "<" && tok != "!<" {
720                         p.syntaxError("missing <")
721                 }
722                 op = tok
723         }
724 }
725
726 // A depsParser parses the depsRules syntax described above.
727 type depsParser struct {
728         t        *testing.T
729         lineno   int
730         lastWord string
731         text     string
732 }
733
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)
737 }
738
739 // nextList parses and returns a comma-separated list of names.
740 func (p *depsParser) nextList() (list []string, token string) {
741         for {
742                 tok := p.nextToken()
743                 switch tok {
744                 case "":
745                         if len(list) == 0 {
746                                 return nil, ""
747                         }
748                         fallthrough
749                 case ",", "<", "!<", ";":
750                         p.syntaxError("bad list syntax")
751                 }
752                 list = append(list, tok)
753
754                 tok = p.nextToken()
755                 if tok != "," {
756                         return list, tok
757                 }
758         }
759 }
760
761 // nextToken returns the next token in the deps rules,
762 // one of ";" "," "<" "!<" or a name.
763 func (p *depsParser) nextToken() string {
764         for {
765                 if p.text == "" {
766                         return ""
767                 }
768                 switch p.text[0] {
769                 case ';', ',', '<':
770                         t := p.text[:1]
771                         p.text = p.text[1:]
772                         return t
773
774                 case '!':
775                         if len(p.text) < 2 || p.text[1] != '<' {
776                                 p.syntaxError("unexpected token !")
777                         }
778                         p.text = p.text[2:]
779                         return "!<"
780
781                 case '#':
782                         i := strings.Index(p.text, "\n")
783                         if i < 0 {
784                                 i = len(p.text)
785                         }
786                         p.text = p.text[i:]
787                         continue
788
789                 case '\n':
790                         p.lineno++
791                         fallthrough
792                 case ' ', '\t':
793                         p.text = p.text[1:]
794                         continue
795
796                 default:
797                         i := strings.IndexAny(p.text, "!;,<#\n \t")
798                         if i < 0 {
799                                 i = len(p.text)
800                         }
801                         t := p.text[:i]
802                         p.text = p.text[i:]
803                         p.lastWord = t
804                         return t
805                 }
806         }
807 }