Source file 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  	< go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
   314  	< go/importer;
   315  
   316  	# databases
   317  	FMT
   318  	< database/sql/internal
   319  	< database/sql/driver
   320  	< database/sql;
   321  
   322  	# images
   323  	FMT, compress/lzw, compress/zlib
   324  	< image/color
   325  	< image, image/color/palette
   326  	< image/internal/imageutil
   327  	< image/draw
   328  	< image/gif, image/jpeg, image/png;
   329  
   330  	# cgo, delayed as long as possible.
   331  	# If you add a dependency on CGO, you must add the package
   332  	# to cgoPackages in cmd/dist/test.go as well.
   333  	RUNTIME
   334  	< C
   335  	< runtime/cgo
   336  	< CGO
   337  	< runtime/race, runtime/msan, runtime/asan;
   338  
   339  	# Bulk of the standard library must not use cgo.
   340  	# The prohibition stops at net and os/user.
   341  	C !< fmt, go/types, CRYPTO-MATH;
   342  
   343  	CGO, OS
   344  	< plugin;
   345  
   346  	CGO, FMT
   347  	< os/user
   348  	< archive/tar;
   349  
   350  	sync
   351  	< internal/singleflight;
   352  
   353  	os
   354  	< golang.org/x/net/dns/dnsmessage,
   355  	  golang.org/x/net/lif,
   356  	  golang.org/x/net/route;
   357  
   358  	os, runtime, strconv, sync, unsafe,
   359  	internal/godebug
   360  	< internal/intern;
   361  
   362  	internal/bytealg, internal/intern, internal/itoa, math/bits, sort, strconv
   363  	< net/netip;
   364  
   365  	# net is unavoidable when doing any networking,
   366  	# so large dependencies must be kept out.
   367  	# This is a long-looking list but most of these
   368  	# are small with few dependencies.
   369  	CGO,
   370  	golang.org/x/net/dns/dnsmessage,
   371  	golang.org/x/net/lif,
   372  	golang.org/x/net/route,
   373  	internal/godebug,
   374  	internal/nettrace,
   375  	internal/poll,
   376  	internal/singleflight,
   377  	internal/race,
   378  	net/netip,
   379  	os
   380  	< net;
   381  
   382  	fmt, unicode !< net;
   383  	math/rand !< net; # net uses runtime instead
   384  
   385  	# NET is net plus net-helper packages.
   386  	FMT, net
   387  	< net/textproto;
   388  
   389  	mime, net/textproto, net/url
   390  	< NET;
   391  
   392  	# logging - most packages should not import; http and up is allowed
   393  	FMT
   394  	< log;
   395  
   396  	log !< crypto/tls, database/sql, go/importer, testing;
   397  
   398  	FMT, log, net
   399  	< log/syslog;
   400  
   401  	NET, log
   402  	< net/mail;
   403  
   404  	# CRYPTO is core crypto algorithms - no cgo, fmt, net.
   405  	# Unfortunately, stuck with reflect via encoding/binary.
   406  	encoding/binary, golang.org/x/sys/cpu, hash
   407  	< crypto
   408  	< crypto/subtle
   409  	< crypto/internal/subtle
   410  	< crypto/elliptic/internal/fiat
   411  	< crypto/elliptic/internal/nistec
   412  	< crypto/ed25519/internal/edwards25519/field, golang.org/x/crypto/curve25519/internal/field
   413  	< crypto/ed25519/internal/edwards25519
   414  	< crypto/cipher
   415  	< crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
   416  	  crypto/sha1, crypto/sha256, crypto/sha512
   417  	< CRYPTO;
   418  
   419  	CGO, fmt, net !< CRYPTO;
   420  
   421  	# CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
   422  	CRYPTO, FMT, math/big, embed
   423  	< crypto/rand
   424  	< crypto/internal/randutil
   425  	< crypto/ed25519
   426  	< encoding/asn1
   427  	< golang.org/x/crypto/cryptobyte/asn1
   428  	< golang.org/x/crypto/cryptobyte
   429  	< golang.org/x/crypto/curve25519
   430  	< crypto/dsa, crypto/elliptic, crypto/rsa
   431  	< crypto/ecdsa
   432  	< CRYPTO-MATH;
   433  
   434  	CGO, net !< CRYPTO-MATH;
   435  
   436  	# TLS, Prince of Dependencies.
   437  	CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
   438  	< golang.org/x/crypto/internal/subtle
   439  	< golang.org/x/crypto/chacha20
   440  	< golang.org/x/crypto/internal/poly1305
   441  	< golang.org/x/crypto/chacha20poly1305
   442  	< golang.org/x/crypto/hkdf
   443  	< crypto/x509/internal/macos
   444  	< crypto/x509/pkix
   445  	< crypto/x509
   446  	< crypto/tls;
   447  
   448  	# crypto-aware packages
   449  
   450  	NET, crypto/rand, mime/quotedprintable
   451  	< mime/multipart;
   452  
   453  	crypto/tls
   454  	< net/smtp;
   455  
   456  	# HTTP, King of Dependencies.
   457  
   458  	FMT
   459  	< golang.org/x/net/http2/hpack
   460  	< net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
   461  
   462  	FMT, NET, container/list, encoding/binary, log
   463  	< golang.org/x/text/transform
   464  	< golang.org/x/text/unicode/norm
   465  	< golang.org/x/text/unicode/bidi
   466  	< golang.org/x/text/secure/bidirule
   467  	< golang.org/x/net/idna
   468  	< golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
   469  
   470  	NET, crypto/tls
   471  	< net/http/httptrace;
   472  
   473  	compress/gzip,
   474  	golang.org/x/net/http/httpguts,
   475  	golang.org/x/net/http/httpproxy,
   476  	golang.org/x/net/http2/hpack,
   477  	net/http/internal,
   478  	net/http/internal/ascii,
   479  	net/http/internal/testcert,
   480  	net/http/httptrace,
   481  	mime/multipart,
   482  	log
   483  	< net/http;
   484  
   485  	# HTTP-aware packages
   486  
   487  	encoding/json, net/http
   488  	< expvar;
   489  
   490  	net/http, net/http/internal/ascii
   491  	< net/http/cookiejar, net/http/httputil;
   492  
   493  	net/http, flag
   494  	< net/http/httptest;
   495  
   496  	net/http, regexp
   497  	< net/http/cgi
   498  	< net/http/fcgi;
   499  
   500  	# Profiling
   501  	FMT, compress/gzip, encoding/binary, text/tabwriter
   502  	< runtime/pprof;
   503  
   504  	OS, compress/gzip, regexp
   505  	< internal/profile;
   506  
   507  	html, internal/profile, net/http, runtime/pprof, runtime/trace
   508  	< net/http/pprof;
   509  
   510  	# RPC
   511  	encoding/gob, encoding/json, go/token, html/template, net/http
   512  	< net/rpc
   513  	< net/rpc/jsonrpc;
   514  
   515  	# System Information
   516  	internal/cpu, sync
   517  	< internal/sysinfo;
   518  
   519  	# Test-only
   520  	log
   521  	< testing/iotest
   522  	< testing/fstest;
   523  
   524  	FMT, flag, math/rand
   525  	< testing/quick;
   526  
   527  	FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
   528  	< testing;
   529  
   530  	FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
   531  	internal/godebug, math/rand, encoding/hex, crypto/sha256
   532  	< internal/fuzz;
   533  
   534  	internal/fuzz, internal/testlog, runtime/pprof, regexp
   535  	< testing/internal/testdeps;
   536  
   537  	OS, flag, testing, internal/cfg
   538  	< internal/testenv;
   539  
   540  	OS, encoding/base64
   541  	< internal/obscuretestdata;
   542  
   543  	CGO, OS, fmt
   544  	< os/signal/internal/pty;
   545  
   546  	NET, testing, math/rand
   547  	< golang.org/x/net/nettest;
   548  
   549  	syscall
   550  	< os/exec/internal/fdtest;
   551  
   552  	FMT, container/heap, math/rand
   553  	< internal/trace;
   554  `
   555  
   556  // listStdPkgs returns the same list of packages as "go list std".
   557  func listStdPkgs(goroot string) ([]string, error) {
   558  	// Based on cmd/go's matchPackages function.
   559  	var pkgs []string
   560  
   561  	src := filepath.Join(goroot, "src") + string(filepath.Separator)
   562  	walkFn := func(path string, d fs.DirEntry, err error) error {
   563  		if err != nil || !d.IsDir() || path == src {
   564  			return nil
   565  		}
   566  
   567  		base := filepath.Base(path)
   568  		if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
   569  			return filepath.SkipDir
   570  		}
   571  
   572  		name := filepath.ToSlash(path[len(src):])
   573  		if name == "builtin" || name == "cmd" {
   574  			return filepath.SkipDir
   575  		}
   576  
   577  		pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
   578  		return nil
   579  	}
   580  	if err := filepath.WalkDir(src, walkFn); err != nil {
   581  		return nil, err
   582  	}
   583  	return pkgs, nil
   584  }
   585  
   586  func TestDependencies(t *testing.T) {
   587  	if !testenv.HasSrc() {
   588  		// Tests run in a limited file system and we do not
   589  		// provide access to every source file.
   590  		t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
   591  	}
   592  
   593  	ctxt := Default
   594  	all, err := listStdPkgs(ctxt.GOROOT)
   595  	if err != nil {
   596  		t.Fatal(err)
   597  	}
   598  	sort.Strings(all)
   599  
   600  	sawImport := map[string]map[string]bool{} // from package => to package => true
   601  	policy := depsPolicy(t)
   602  
   603  	for _, pkg := range all {
   604  		imports, err := findImports(pkg)
   605  		if err != nil {
   606  			t.Error(err)
   607  			continue
   608  		}
   609  		if sawImport[pkg] == nil {
   610  			sawImport[pkg] = map[string]bool{}
   611  		}
   612  		ok := policy[pkg]
   613  		var bad []string
   614  		for _, imp := range imports {
   615  			sawImport[pkg][imp] = true
   616  			if !ok[imp] {
   617  				bad = append(bad, imp)
   618  			}
   619  		}
   620  		if bad != nil {
   621  			t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
   622  		}
   623  	}
   624  
   625  	// depPath returns the path between the given from and to packages.
   626  	// It returns the empty string if there's no dependency path.
   627  	var depPath func(string, string) string
   628  	depPath = func(from, to string) string {
   629  		if sawImport[from][to] {
   630  			return from + " => " + to
   631  		}
   632  		for pkg := range sawImport[from] {
   633  			if p := depPath(pkg, to); p != "" {
   634  				return from + " => " + p
   635  			}
   636  		}
   637  		return ""
   638  	}
   639  }
   640  
   641  var buildIgnore = []byte("\n//go:build ignore")
   642  
   643  func findImports(pkg string) ([]string, error) {
   644  	vpkg := pkg
   645  	if strings.HasPrefix(pkg, "golang.org") {
   646  		vpkg = "vendor/" + pkg
   647  	}
   648  	dir := filepath.Join(Default.GOROOT, "src", vpkg)
   649  	files, err := os.ReadDir(dir)
   650  	if err != nil {
   651  		return nil, err
   652  	}
   653  	var imports []string
   654  	var haveImport = map[string]bool{}
   655  	fset := token.NewFileSet()
   656  	for _, file := range files {
   657  		name := file.Name()
   658  		if name == "slice_go14.go" || name == "slice_go18.go" {
   659  			// These files are for compiler bootstrap with older versions of Go and not built in the standard build.
   660  			continue
   661  		}
   662  		if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
   663  			continue
   664  		}
   665  		info := fileInfo{
   666  			name: filepath.Join(dir, name),
   667  			fset: fset,
   668  		}
   669  		f, err := os.Open(info.name)
   670  		if err != nil {
   671  			return nil, err
   672  		}
   673  		err = readGoInfo(f, &info)
   674  		f.Close()
   675  		if err != nil {
   676  			return nil, fmt.Errorf("reading %v: %v", name, err)
   677  		}
   678  		if info.parsed.Name.Name == "main" {
   679  			continue
   680  		}
   681  		if bytes.Contains(info.header, buildIgnore) {
   682  			continue
   683  		}
   684  		for _, imp := range info.imports {
   685  			path := imp.path
   686  			if !haveImport[path] {
   687  				haveImport[path] = true
   688  				imports = append(imports, path)
   689  			}
   690  		}
   691  	}
   692  	sort.Strings(imports)
   693  	return imports, nil
   694  }
   695  
   696  // depsPolicy returns a map m such that m[p][d] == true when p can import d.
   697  func depsPolicy(t *testing.T) map[string]map[string]bool {
   698  	allowed := map[string]map[string]bool{"NONE": {}}
   699  	disallowed := [][2][]string{}
   700  
   701  	parseDepsRules(t, func(deps []string, op string, users []string) {
   702  		if op == "!<" {
   703  			disallowed = append(disallowed, [2][]string{deps, users})
   704  			return
   705  		}
   706  		for _, u := range users {
   707  			if allowed[u] != nil {
   708  				t.Errorf("multiple deps lists for %s", u)
   709  			}
   710  			allowed[u] = make(map[string]bool)
   711  			for _, d := range deps {
   712  				if allowed[d] == nil {
   713  					t.Errorf("use of %s before its deps list", d)
   714  				}
   715  				allowed[u][d] = true
   716  			}
   717  		}
   718  	})
   719  
   720  	// Check for missing deps info.
   721  	for _, deps := range allowed {
   722  		for d := range deps {
   723  			if allowed[d] == nil {
   724  				t.Errorf("missing deps list for %s", d)
   725  			}
   726  		}
   727  	}
   728  
   729  	// Complete transitive allowed deps.
   730  	for k := range allowed {
   731  		for i := range allowed {
   732  			for j := range allowed {
   733  				if i != k && k != j && allowed[i][k] && allowed[k][j] {
   734  					if i == j {
   735  						// Can only happen along with a "use of X before deps" error above,
   736  						// but this error is more specific - it makes clear that reordering the
   737  						// rules will not be enough to fix the problem.
   738  						t.Errorf("deps policy cycle: %s < %s < %s", j, k, i)
   739  					}
   740  					allowed[i][j] = true
   741  				}
   742  			}
   743  		}
   744  	}
   745  
   746  	// Check negative assertions against completed allowed deps.
   747  	for _, bad := range disallowed {
   748  		deps, users := bad[0], bad[1]
   749  		for _, d := range deps {
   750  			for _, u := range users {
   751  				if allowed[u][d] {
   752  					t.Errorf("deps policy incorrect: assertion failed: %s !< %s", d, u)
   753  				}
   754  			}
   755  		}
   756  	}
   757  
   758  	if t.Failed() {
   759  		t.FailNow()
   760  	}
   761  
   762  	return allowed
   763  }
   764  
   765  // parseDepsRules parses depsRules, calling save(deps, op, users)
   766  // for each deps < users or deps !< users rule
   767  // (op is "<" or "!<").
   768  func parseDepsRules(t *testing.T, save func(deps []string, op string, users []string)) {
   769  	p := &depsParser{t: t, lineno: 1, text: depsRules}
   770  
   771  	var prev []string
   772  	var op string
   773  	for {
   774  		list, tok := p.nextList()
   775  		if tok == "" {
   776  			if prev == nil {
   777  				break
   778  			}
   779  			p.syntaxError("unexpected EOF")
   780  		}
   781  		if prev != nil {
   782  			save(prev, op, list)
   783  		}
   784  		prev = list
   785  		if tok == ";" {
   786  			prev = nil
   787  			op = ""
   788  			continue
   789  		}
   790  		if tok != "<" && tok != "!<" {
   791  			p.syntaxError("missing <")
   792  		}
   793  		op = tok
   794  	}
   795  }
   796  
   797  // A depsParser parses the depsRules syntax described above.
   798  type depsParser struct {
   799  	t        *testing.T
   800  	lineno   int
   801  	lastWord string
   802  	text     string
   803  }
   804  
   805  // syntaxError reports a parsing error.
   806  func (p *depsParser) syntaxError(msg string) {
   807  	p.t.Fatalf("deps:%d: syntax error: %s near %s", p.lineno, msg, p.lastWord)
   808  }
   809  
   810  // nextList parses and returns a comma-separated list of names.
   811  func (p *depsParser) nextList() (list []string, token string) {
   812  	for {
   813  		tok := p.nextToken()
   814  		switch tok {
   815  		case "":
   816  			if len(list) == 0 {
   817  				return nil, ""
   818  			}
   819  			fallthrough
   820  		case ",", "<", "!<", ";":
   821  			p.syntaxError("bad list syntax")
   822  		}
   823  		list = append(list, tok)
   824  
   825  		tok = p.nextToken()
   826  		if tok != "," {
   827  			return list, tok
   828  		}
   829  	}
   830  }
   831  
   832  // nextToken returns the next token in the deps rules,
   833  // one of ";" "," "<" "!<" or a name.
   834  func (p *depsParser) nextToken() string {
   835  	for {
   836  		if p.text == "" {
   837  			return ""
   838  		}
   839  		switch p.text[0] {
   840  		case ';', ',', '<':
   841  			t := p.text[:1]
   842  			p.text = p.text[1:]
   843  			return t
   844  
   845  		case '!':
   846  			if len(p.text) < 2 || p.text[1] != '<' {
   847  				p.syntaxError("unexpected token !")
   848  			}
   849  			p.text = p.text[2:]
   850  			return "!<"
   851  
   852  		case '#':
   853  			i := strings.Index(p.text, "\n")
   854  			if i < 0 {
   855  				i = len(p.text)
   856  			}
   857  			p.text = p.text[i:]
   858  			continue
   859  
   860  		case '\n':
   861  			p.lineno++
   862  			fallthrough
   863  		case ' ', '\t':
   864  			p.text = p.text[1:]
   865  			continue
   866  
   867  		default:
   868  			i := strings.IndexAny(p.text, "!;,<#\n \t")
   869  			if i < 0 {
   870  				i = len(p.text)
   871  			}
   872  			t := p.text[:i]
   873  			p.text = p.text[i:]
   874  			p.lastWord = t
   875  			return t
   876  		}
   877  	}
   878  }
   879  
   880  // TestStdlibLowercase tests that all standard library package names are
   881  // lowercase. See Issue 40065.
   882  func TestStdlibLowercase(t *testing.T) {
   883  	if !testenv.HasSrc() {
   884  		t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
   885  	}
   886  
   887  	ctxt := Default
   888  	all, err := listStdPkgs(ctxt.GOROOT)
   889  	if err != nil {
   890  		t.Fatal(err)
   891  	}
   892  
   893  	for _, pkgname := range all {
   894  		if strings.ToLower(pkgname) != pkgname {
   895  			t.Errorf("package %q should not use upper-case path", pkgname)
   896  		}
   897  	}
   898  }
   899  
   900  // TestFindImports tests that findImports works.  See #43249.
   901  func TestFindImports(t *testing.T) {
   902  	imports, err := findImports("go/build")
   903  	if err != nil {
   904  		t.Fatal(err)
   905  	}
   906  	t.Logf("go/build imports %q", imports)
   907  	want := []string{"bytes", "os", "path/filepath", "strings"}
   908  wantLoop:
   909  	for _, w := range want {
   910  		for _, imp := range imports {
   911  			if imp == w {
   912  				continue wantLoop
   913  			}
   914  		}
   915  		t.Errorf("expected to find %q in import list", w)
   916  	}
   917  }
   918  

View as plain text