]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/build/deps_test.go
internal/pkgbits: extract unified IR coding-level logic
[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/testenv"
15         "io/fs"
16         "os"
17         "path/filepath"
18         "runtime"
19         "sort"
20         "strings"
21         "testing"
22 )
23
24 // depsRules defines the expected dependencies between packages in
25 // the Go source tree. It is a statement of policy.
26 //
27 // DO NOT CHANGE THIS DATA TO FIX BUILDS.
28 // Existing packages should not have their constraints relaxed
29 // without prior discussion.
30 // Negative assertions should almost never be removed.
31 //
32 // The general syntax of a rule is:
33 //
34 //              a, b < c, d;
35 //
36 // which means c and d come after a and b in the partial order
37 // (that is, c and d can import a and b),
38 // but doesn't provide a relative order between a vs b or c vs d.
39 //
40 // The rules can chain together, as in:
41 //
42 //              e < f, g < h;
43 //
44 // which is equivalent to
45 //
46 //              e < f, g;
47 //              f, g < h;
48 //
49 // Except for the special bottom element "NONE", each name
50 // must appear exactly once on the right-hand side of a rule.
51 // That rule serves as the definition of the allowed dependencies
52 // for that name. The definition must appear before any uses
53 // of the name on the left-hand side of a rule. (That is, the
54 // rules themselves must be ordered according to the partial
55 // order, for easier reading by people.)
56 //
57 // Negative assertions double-check the partial order:
58 //
59 //              i !< j
60 //
61 // means that it must NOT be the case that i < j.
62 // Negative assertions may appear anywhere in the rules,
63 // even before i and j have been defined.
64 //
65 // Comments begin with #.
66 //
67 // All-caps names are pseudo-names for specific points
68 // in the dependency lattice.
69 //
70 var depsRules = `
71         # No dependencies allowed for any of these packages.
72         NONE
73         < constraints, container/list, container/ring,
74           internal/cfg, internal/cpu, internal/goarch,
75           internal/goexperiment, internal/goos,
76           internal/goversion, internal/nettrace,
77           unicode/utf8, unicode/utf16, unicode,
78           unsafe;
79
80         # These packages depend only on internal/goarch and unsafe.
81         internal/goarch, unsafe
82         < internal/abi;
83
84         # RUNTIME is the core runtime group of packages, all of them very light-weight.
85         internal/abi, internal/cpu, internal/goarch,
86         internal/goexperiment, internal/goos, unsafe
87         < internal/bytealg
88         < internal/itoa
89         < internal/unsafeheader
90         < runtime/internal/sys
91         < runtime/internal/syscall
92         < runtime/internal/atomic
93         < runtime/internal/math
94         < runtime
95         < sync/atomic
96         < internal/race
97         < sync
98         < internal/reflectlite
99         < errors
100         < internal/oserror, math/bits
101         < RUNTIME;
102
103         RUNTIME
104         < sort
105         < container/heap;
106
107         RUNTIME
108         < io;
109
110         syscall !< io;
111         reflect !< sort;
112
113         RUNTIME, unicode/utf8
114         < path;
115
116         unicode !< path;
117
118         # SYSCALL is RUNTIME plus the packages necessary for basic system calls.
119         RUNTIME, unicode/utf8, unicode/utf16
120         < internal/syscall/windows/sysdll, syscall/js
121         < syscall
122         < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
123         < internal/syscall/execenv
124         < SYSCALL;
125
126         # TIME is SYSCALL plus the core packages about time, including context.
127         SYSCALL
128         < time/tzdata
129         < time
130         < context
131         < TIME;
132
133         TIME, io, path, sort
134         < io/fs;
135
136         # MATH is RUNTIME plus the basic math packages.
137         RUNTIME
138         < math
139         < MATH;
140
141         unicode !< math;
142
143         MATH
144         < math/cmplx;
145
146         MATH
147         < math/rand;
148
149         MATH
150         < runtime/metrics;
151
152         MATH, unicode/utf8
153         < strconv;
154
155         unicode !< strconv;
156
157         # STR is basic string and buffer manipulation.
158         RUNTIME, io, unicode/utf8, unicode/utf16, unicode
159         < bytes, strings
160         < bufio;
161
162         bufio, path, strconv
163         < STR;
164
165         # OS is basic OS access, including helpers (path/filepath, os/exec, etc).
166         # OS includes string routines, but those must be layered above package os.
167         # OS does not include reflection.
168         io/fs
169         < internal/testlog
170         < internal/poll
171         < os
172         < os/signal;
173
174         io/fs
175         < embed;
176
177         unicode, fmt !< net, os, os/signal;
178
179         os/signal, STR
180         < path/filepath
181         < io/ioutil, os/exec;
182
183         io/ioutil, os/exec, os/signal
184         < OS;
185
186         reflect !< OS;
187
188         OS
189         < golang.org/x/sys/cpu;
190
191         os < internal/godebug;
192
193         # FMT is OS (which includes string routines) plus reflect and fmt.
194         # It does not include package log, which should be avoided in core packages.
195         strconv, unicode
196         < reflect;
197
198         os, reflect
199         < internal/fmtsort
200         < fmt;
201
202         OS, fmt
203         < FMT;
204
205         log !< FMT;
206
207         OS, FMT
208         < internal/execabs;
209
210         OS, internal/execabs
211         < internal/goroot;
212
213         # Misc packages needing only FMT.
214         FMT
215         < flag,
216           html,
217           mime/quotedprintable,
218           net/internal/socktest,
219           net/url,
220           runtime/trace,
221           text/scanner,
222           text/tabwriter;
223
224         # encodings
225         # core ones do not use fmt.
226         io, strconv
227         < encoding;
228
229         encoding, reflect
230         < encoding/binary
231         < encoding/base32, encoding/base64;
232
233         fmt !< encoding/base32, encoding/base64;
234
235         FMT, encoding/base32, encoding/base64
236         < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
237           encoding/json, encoding/pem, encoding/xml, mime;
238
239         # hashes
240         io
241         < hash
242         < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
243
244         # math/big
245         FMT, encoding/binary, math/rand
246         < math/big;
247
248         # compression
249         FMT, encoding/binary, hash/adler32, hash/crc32
250         < compress/bzip2, compress/flate, compress/lzw
251         < archive/zip, compress/gzip, compress/zlib;
252
253         # templates
254         FMT
255         < text/template/parse;
256
257         net/url, text/template/parse
258         < text/template
259         < internal/lazytemplate;
260
261         encoding/json, html, text/template
262         < html/template;
263
264         # regexp
265         FMT
266         < regexp/syntax
267         < regexp
268         < internal/lazyregexp;
269
270         # suffix array
271         encoding/binary, regexp
272         < index/suffixarray;
273
274         # executable parsing
275         FMT, encoding/binary, compress/zlib
276         < runtime/debug
277         < debug/dwarf
278         < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
279         < debug/buildinfo
280         < DEBUG;
281
282         # go parser and friends.
283         FMT
284         < go/token
285         < go/scanner
286         < go/ast
287         < go/internal/typeparams
288         < go/parser;
289
290         FMT
291         < go/build/constraint;
292
293         go/build/constraint, go/parser, text/tabwriter
294         < go/printer
295         < go/format;
296
297         go/parser, internal/lazyregexp, text/template
298         < go/doc;
299
300         math/big, go/token
301         < go/constant;
302
303         container/heap, go/constant, go/parser, regexp
304         < go/types;
305
306         FMT, internal/goexperiment
307         < internal/buildcfg;
308
309         go/build/constraint, go/doc, go/parser, internal/buildcfg, internal/goroot, internal/goversion
310         < go/build;
311
312         DEBUG, go/build, go/types, text/scanner
313   < internal/pkgbits
314         < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
315         < go/importer;
316
317         # databases
318         FMT
319         < database/sql/internal
320         < database/sql/driver
321         < database/sql;
322
323         # images
324         FMT, compress/lzw, compress/zlib
325         < image/color
326         < image, image/color/palette
327         < image/internal/imageutil
328         < image/draw
329         < image/gif, image/jpeg, image/png;
330
331         # cgo, delayed as long as possible.
332         # If you add a dependency on CGO, you must add the package
333         # to cgoPackages in cmd/dist/test.go as well.
334         RUNTIME
335         < C
336         < runtime/cgo
337         < CGO
338         < runtime/race, runtime/msan, runtime/asan;
339
340         # Bulk of the standard library must not use cgo.
341         # The prohibition stops at net and os/user.
342         C !< fmt, go/types, CRYPTO-MATH;
343
344         CGO, OS
345         < plugin;
346
347         CGO, FMT
348         < os/user
349         < archive/tar;
350
351         sync
352         < internal/singleflight;
353
354         os
355         < golang.org/x/net/dns/dnsmessage,
356           golang.org/x/net/lif,
357           golang.org/x/net/route;
358
359         os, runtime, strconv, sync, unsafe,
360         internal/godebug
361         < internal/intern;
362
363         internal/bytealg, internal/intern, internal/itoa, math/bits, sort, strconv
364         < net/netip;
365
366         # net is unavoidable when doing any networking,
367         # so large dependencies must be kept out.
368         # This is a long-looking list but most of these
369         # are small with few dependencies.
370         CGO,
371         golang.org/x/net/dns/dnsmessage,
372         golang.org/x/net/lif,
373         golang.org/x/net/route,
374         internal/godebug,
375         internal/nettrace,
376         internal/poll,
377         internal/singleflight,
378         internal/race,
379         net/netip,
380         os
381         < net;
382
383         fmt, unicode !< net;
384         math/rand !< net; # net uses runtime instead
385
386         # NET is net plus net-helper packages.
387         FMT, net
388         < net/textproto;
389
390         mime, net/textproto, net/url
391         < NET;
392
393         # logging - most packages should not import; http and up is allowed
394         FMT
395         < log;
396
397         log !< crypto/tls, database/sql, go/importer, testing;
398
399         FMT, log, net
400         < log/syslog;
401
402         NET, log
403         < net/mail;
404
405         # CRYPTO is core crypto algorithms - no cgo, fmt, net.
406         # Unfortunately, stuck with reflect via encoding/binary.
407         encoding/binary, golang.org/x/sys/cpu, hash
408         < crypto
409         < crypto/subtle
410         < crypto/internal/subtle
411         < crypto/elliptic/internal/fiat
412         < crypto/elliptic/internal/nistec
413         < crypto/ed25519/internal/edwards25519/field, golang.org/x/crypto/curve25519/internal/field
414         < crypto/ed25519/internal/edwards25519
415         < crypto/cipher
416         < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
417           crypto/sha1, crypto/sha256, crypto/sha512
418         < CRYPTO;
419
420         CGO, fmt, net !< CRYPTO;
421
422         # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
423         CRYPTO, FMT, math/big, embed
424         < crypto/rand
425         < crypto/internal/randutil
426         < crypto/ed25519
427         < encoding/asn1
428         < golang.org/x/crypto/cryptobyte/asn1
429         < golang.org/x/crypto/cryptobyte
430         < golang.org/x/crypto/curve25519
431         < crypto/dsa, crypto/elliptic, crypto/rsa
432         < crypto/ecdsa
433         < CRYPTO-MATH;
434
435         CGO, net !< CRYPTO-MATH;
436
437         # TLS, Prince of Dependencies.
438         CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
439         < golang.org/x/crypto/internal/subtle
440         < golang.org/x/crypto/chacha20
441         < golang.org/x/crypto/internal/poly1305
442         < golang.org/x/crypto/chacha20poly1305
443         < golang.org/x/crypto/hkdf
444         < crypto/x509/internal/macos
445         < crypto/x509/pkix
446         < crypto/x509
447         < crypto/tls;
448
449         # crypto-aware packages
450
451         NET, crypto/rand, mime/quotedprintable
452         < mime/multipart;
453
454         crypto/tls
455         < net/smtp;
456
457         # HTTP, King of Dependencies.
458
459         FMT
460         < golang.org/x/net/http2/hpack
461         < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
462
463         FMT, NET, container/list, encoding/binary, log
464         < golang.org/x/text/transform
465         < golang.org/x/text/unicode/norm
466         < golang.org/x/text/unicode/bidi
467         < golang.org/x/text/secure/bidirule
468         < golang.org/x/net/idna
469         < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
470
471         NET, crypto/tls
472         < net/http/httptrace;
473
474         compress/gzip,
475         golang.org/x/net/http/httpguts,
476         golang.org/x/net/http/httpproxy,
477         golang.org/x/net/http2/hpack,
478         net/http/internal,
479         net/http/internal/ascii,
480         net/http/internal/testcert,
481         net/http/httptrace,
482         mime/multipart,
483         log
484         < net/http;
485
486         # HTTP-aware packages
487
488         encoding/json, net/http
489         < expvar;
490
491         net/http, net/http/internal/ascii
492         < net/http/cookiejar, net/http/httputil;
493
494         net/http, flag
495         < net/http/httptest;
496
497         net/http, regexp
498         < net/http/cgi
499         < net/http/fcgi;
500
501         # Profiling
502         FMT, compress/gzip, encoding/binary, text/tabwriter
503         < runtime/pprof;
504
505         OS, compress/gzip, regexp
506         < internal/profile;
507
508         html, internal/profile, net/http, runtime/pprof, runtime/trace
509         < net/http/pprof;
510
511         # RPC
512         encoding/gob, encoding/json, go/token, html/template, net/http
513         < net/rpc
514         < net/rpc/jsonrpc;
515
516         # System Information
517         internal/cpu, sync
518         < internal/sysinfo;
519
520         # Test-only
521         log
522         < testing/iotest
523         < testing/fstest;
524
525         FMT, flag, math/rand
526         < testing/quick;
527
528         FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
529         < testing;
530
531         FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
532         internal/godebug, math/rand, encoding/hex, crypto/sha256
533         < internal/fuzz;
534
535         internal/fuzz, internal/testlog, runtime/pprof, regexp
536         < testing/internal/testdeps;
537
538         OS, flag, testing, internal/cfg
539         < internal/testenv;
540
541         OS, encoding/base64
542         < internal/obscuretestdata;
543
544         CGO, OS, fmt
545         < os/signal/internal/pty;
546
547         NET, testing, math/rand
548         < golang.org/x/net/nettest;
549
550         syscall
551         < os/exec/internal/fdtest;
552
553         FMT, container/heap, math/rand
554         < internal/trace;
555 `
556
557 // listStdPkgs returns the same list of packages as "go list std".
558 func listStdPkgs(goroot string) ([]string, error) {
559         // Based on cmd/go's matchPackages function.
560         var pkgs []string
561
562         src := filepath.Join(goroot, "src") + string(filepath.Separator)
563         walkFn := func(path string, d fs.DirEntry, err error) error {
564                 if err != nil || !d.IsDir() || path == src {
565                         return nil
566                 }
567
568                 base := filepath.Base(path)
569                 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
570                         return filepath.SkipDir
571                 }
572
573                 name := filepath.ToSlash(path[len(src):])
574                 if name == "builtin" || name == "cmd" {
575                         return filepath.SkipDir
576                 }
577
578                 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
579                 return nil
580         }
581         if err := filepath.WalkDir(src, walkFn); err != nil {
582                 return nil, err
583         }
584         return pkgs, nil
585 }
586
587 func TestDependencies(t *testing.T) {
588         if !testenv.HasSrc() {
589                 // Tests run in a limited file system and we do not
590                 // provide access to every source file.
591                 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
592         }
593
594         ctxt := Default
595         all, err := listStdPkgs(ctxt.GOROOT)
596         if err != nil {
597                 t.Fatal(err)
598         }
599         sort.Strings(all)
600
601         sawImport := map[string]map[string]bool{} // from package => to package => true
602         policy := depsPolicy(t)
603
604         for _, pkg := range all {
605                 imports, err := findImports(pkg)
606                 if err != nil {
607                         t.Error(err)
608                         continue
609                 }
610                 if sawImport[pkg] == nil {
611                         sawImport[pkg] = map[string]bool{}
612                 }
613                 ok := policy[pkg]
614                 var bad []string
615                 for _, imp := range imports {
616                         sawImport[pkg][imp] = true
617                         if !ok[imp] {
618                                 bad = append(bad, imp)
619                         }
620                 }
621                 if bad != nil {
622                         t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
623                 }
624         }
625
626         // depPath returns the path between the given from and to packages.
627         // It returns the empty string if there's no dependency path.
628         var depPath func(string, string) string
629         depPath = func(from, to string) string {
630                 if sawImport[from][to] {
631                         return from + " => " + to
632                 }
633                 for pkg := range sawImport[from] {
634                         if p := depPath(pkg, to); p != "" {
635                                 return from + " => " + p
636                         }
637                 }
638                 return ""
639         }
640 }
641
642 var buildIgnore = []byte("\n//go:build ignore")
643
644 func findImports(pkg string) ([]string, error) {
645         vpkg := pkg
646         if strings.HasPrefix(pkg, "golang.org") {
647                 vpkg = "vendor/" + pkg
648         }
649         dir := filepath.Join(Default.GOROOT, "src", vpkg)
650         files, err := os.ReadDir(dir)
651         if err != nil {
652                 return nil, err
653         }
654         var imports []string
655         var haveImport = map[string]bool{}
656         fset := token.NewFileSet()
657         for _, file := range files {
658                 name := file.Name()
659                 if name == "slice_go14.go" || name == "slice_go18.go" {
660                         // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
661                         continue
662                 }
663                 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
664                         continue
665                 }
666                 info := fileInfo{
667                         name: filepath.Join(dir, name),
668                         fset: fset,
669                 }
670                 f, err := os.Open(info.name)
671                 if err != nil {
672                         return nil, err
673                 }
674                 err = readGoInfo(f, &info)
675                 f.Close()
676                 if err != nil {
677                         return nil, fmt.Errorf("reading %v: %v", name, err)
678                 }
679                 if info.parsed.Name.Name == "main" {
680                         continue
681                 }
682                 if bytes.Contains(info.header, buildIgnore) {
683                         continue
684                 }
685                 for _, imp := range info.imports {
686                         path := imp.path
687                         if !haveImport[path] {
688                                 haveImport[path] = true
689                                 imports = append(imports, path)
690                         }
691                 }
692         }
693         sort.Strings(imports)
694         return imports, nil
695 }
696
697 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
698 func depsPolicy(t *testing.T) map[string]map[string]bool {
699         allowed := map[string]map[string]bool{"NONE": {}}
700         disallowed := [][2][]string{}
701
702         parseDepsRules(t, func(deps []string, op string, users []string) {
703                 if op == "!<" {
704                         disallowed = append(disallowed, [2][]string{deps, users})
705                         return
706                 }
707                 for _, u := range users {
708                         if allowed[u] != nil {
709                                 t.Errorf("multiple deps lists for %s", u)
710                         }
711                         allowed[u] = make(map[string]bool)
712                         for _, d := range deps {
713                                 if allowed[d] == nil {
714                                         t.Errorf("use of %s before its deps list", d)
715                                 }
716                                 allowed[u][d] = true
717                         }
718                 }
719         })
720
721         // Check for missing deps info.
722         for _, deps := range allowed {
723                 for d := range deps {
724                         if allowed[d] == nil {
725                                 t.Errorf("missing deps list for %s", d)
726                         }
727                 }
728         }
729
730         // Complete transitive allowed deps.
731         for k := range allowed {
732                 for i := range allowed {
733                         for j := range allowed {
734                                 if i != k && k != j && allowed[i][k] && allowed[k][j] {
735                                         if i == j {
736                                                 // Can only happen along with a "use of X before deps" error above,
737                                                 // but this error is more specific - it makes clear that reordering the
738                                                 // rules will not be enough to fix the problem.
739                                                 t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
740                                         }
741                                         allowed[i][j] = true
742                                 }
743                         }
744                 }
745         }
746
747         // Check negative assertions against completed allowed deps.
748         for _, bad := range disallowed {
749                 deps, users := bad[0], bad[1]
750                 for _, d := range deps {
751                         for _, u := range users {
752                                 if allowed[u][d] {
753                                         t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
754                                 }
755                         }
756                 }
757         }
758
759         if t.Failed() {
760                 t.FailNow()
761         }
762
763         return allowed
764 }
765
766 // parseDepsRules parses depsRules, calling save(deps, op, users)
767 // for each deps < users or deps !< users rule
768 // (op is "<" or "!<").
769 func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
770         p := &depsParser{t: t, lineno: 1, text: depsRules}
771
772         var prev []string
773         var op string
774         for {
775                 list, tok := p.nextList()
776                 if tok == "" {
777                         if prev == nil {
778                                 break
779                         }
780                         p.syntaxError("unexpected EOF")
781                 }
782                 if prev != nil {
783                         save(prev, op, list)
784                 }
785                 prev = list
786                 if tok == ";" {
787                         prev = nil
788                         op = ""
789                         continue
790                 }
791                 if tok != "<" && tok != "!<" {
792                         p.syntaxError("missing <")
793                 }
794                 op = tok
795         }
796 }
797
798 // A depsParser parses the depsRules syntax described above.
799 type depsParser struct {
800         t        *testing.T
801         lineno   int
802         lastWord string
803         text     string
804 }
805
806 // syntaxError reports a parsing error.
807 func (p *depsParser) syntaxError(msg string) {
808         p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
809 }
810
811 // nextList parses and returns a comma-separated list of names.
812 func (p *depsParser) nextList() (list []string, token string) {
813         for {
814                 tok := p.nextToken()
815                 switch tok {
816                 case "":
817                         if len(list) == 0 {
818                                 return nil, ""
819                         }
820                         fallthrough
821                 case ",", "<", "!<", ";":
822                         p.syntaxError("bad list syntax")
823                 }
824                 list = append(list, tok)
825
826                 tok = p.nextToken()
827                 if tok != "," {
828                         return list, tok
829                 }
830         }
831 }
832
833 // nextToken returns the next token in the deps rules,
834 // one of ";" "," "<" "!<" or a name.
835 func (p *depsParser) nextToken() string {
836         for {
837                 if p.text == "" {
838                         return ""
839                 }
840                 switch p.text[0] {
841                 case ';', ',', '<':
842                         t := p.text[:1]
843                         p.text = p.text[1:]
844                         return t
845
846                 case '!':
847                         if len(p.text) < 2 || p.text[1] != '<' {
848                                 p.syntaxError("unexpected token !")
849                         }
850                         p.text = p.text[2:]
851                         return "!<"
852
853                 case '#':
854                         i := strings.Index(p.text, "\n")
855                         if i < 0 {
856                                 i = len(p.text)
857                         }
858                         p.text = p.text[i:]
859                         continue
860
861                 case '\n':
862                         p.lineno++
863                         fallthrough
864                 case ' ', '\t':
865                         p.text = p.text[1:]
866                         continue
867
868                 default:
869                         i := strings.IndexAny(p.text, "!;,<#\n \t")
870                         if i < 0 {
871                                 i = len(p.text)
872                         }
873                         t := p.text[:i]
874                         p.text = p.text[i:]
875                         p.lastWord = t
876                         return t
877                 }
878         }
879 }
880
881 // TestStdlibLowercase tests that all standard library package names are
882 // lowercase. See Issue 40065.
883 func TestStdlibLowercase(t *testing.T) {
884         if !testenv.HasSrc() {
885                 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
886         }
887
888         ctxt := Default
889         all, err := listStdPkgs(ctxt.GOROOT)
890         if err != nil {
891                 t.Fatal(err)
892         }
893
894         for _, pkgname := range all {
895                 if strings.ToLower(pkgname) != pkgname {
896                         t.Errorf("package %q should not use upper-case path", pkgname)
897                 }
898         }
899 }
900
901 // TestFindImports tests that findImports works.  See #43249.
902 func TestFindImports(t *testing.T) {
903         imports, err := findImports("go/build")
904         if err != nil {
905                 t.Fatal(err)
906         }
907         t.Logf("go/build imports %q", imports)
908         want := []string{"bytes", "os", "path/filepath", "strings"}
909 wantLoop:
910         for _, w := range want {
911                 for _, imp := range imports {
912                         if imp == w {
913                                 continue wantLoop
914                         }
915                 }
916                 t.Errorf("expected to find %q in import list", w)
917         }
918 }