Source file src/cmd/go/internal/imports/build.go

     1  // Copyright 2018 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  // Copied from Go distribution src/go/build/build.go, syslist.go.
     6  // That package does not export the ability to process raw file data,
     7  // although we could fake it with an appropriate build.Context
     8  // and a lot of unwrapping.
     9  // More importantly, that package does not implement the tags["*"]
    10  // special case, in which both tag and !tag are considered to be true
    11  // for essentially all tags (except "ignore").
    12  //
    13  // If we added this API to go/build directly, we wouldn't need this
    14  // file anymore, but this API is not terribly general-purpose and we
    15  // don't really want to commit to any public form of it, nor do we
    16  // want to move the core parts of go/build into a top-level internal package.
    17  // These details change very infrequently, so the copy is fine.
    18  
    19  package imports
    20  
    21  import (
    22  	"bytes"
    23  	"cmd/go/internal/cfg"
    24  	"errors"
    25  	"fmt"
    26  	"go/build/constraint"
    27  	"internal/syslist"
    28  	"strings"
    29  	"unicode"
    30  )
    31  
    32  var (
    33  	bSlashSlash = []byte("//")
    34  	bStarSlash  = []byte("*/")
    35  	bSlashStar  = []byte("/*")
    36  	bPlusBuild  = []byte("+build")
    37  
    38  	goBuildComment = []byte("//go:build")
    39  
    40  	errMultipleGoBuild = errors.New("multiple //go:build comments")
    41  )
    42  
    43  func isGoBuildComment(line []byte) bool {
    44  	if !bytes.HasPrefix(line, goBuildComment) {
    45  		return false
    46  	}
    47  	line = bytes.TrimSpace(line)
    48  	rest := line[len(goBuildComment):]
    49  	return len(rest) == 0 || len(bytes.TrimSpace(rest)) < len(rest)
    50  }
    51  
    52  // ShouldBuild reports whether it is okay to use this file,
    53  // The rule is that in the file's leading run of // comments
    54  // and blank lines, which must be followed by a blank line
    55  // (to avoid including a Go package clause doc comment),
    56  // lines beginning with '// +build' are taken as build directives.
    57  //
    58  // The file is accepted only if each such line lists something
    59  // matching the file. For example:
    60  //
    61  //	// +build windows linux
    62  //
    63  // marks the file as applicable only on Windows and Linux.
    64  //
    65  // If tags["*"] is true, then ShouldBuild will consider every
    66  // build tag except "ignore" to be both true and false for
    67  // the purpose of satisfying build tags, in order to estimate
    68  // (conservatively) whether a file could ever possibly be used
    69  // in any build.
    70  func ShouldBuild(content []byte, tags map[string]bool) bool {
    71  	// Identify leading run of // comments and blank lines,
    72  	// which must be followed by a blank line.
    73  	// Also identify any //go:build comments.
    74  	content, goBuild, _, err := parseFileHeader(content)
    75  	if err != nil {
    76  		return false
    77  	}
    78  
    79  	// If //go:build line is present, it controls.
    80  	// Otherwise fall back to +build processing.
    81  	var shouldBuild bool
    82  	switch {
    83  	case goBuild != nil:
    84  		x, err := constraint.Parse(string(goBuild))
    85  		if err != nil {
    86  			return false
    87  		}
    88  		shouldBuild = eval(x, tags, true)
    89  
    90  	default:
    91  		shouldBuild = true
    92  		p := content
    93  		for len(p) > 0 {
    94  			line := p
    95  			if i := bytes.IndexByte(line, '\n'); i >= 0 {
    96  				line, p = line[:i], p[i+1:]
    97  			} else {
    98  				p = p[len(p):]
    99  			}
   100  			line = bytes.TrimSpace(line)
   101  			if !bytes.HasPrefix(line, bSlashSlash) || !bytes.Contains(line, bPlusBuild) {
   102  				continue
   103  			}
   104  			text := string(line)
   105  			if !constraint.IsPlusBuild(text) {
   106  				continue
   107  			}
   108  			if x, err := constraint.Parse(text); err == nil {
   109  				if !eval(x, tags, true) {
   110  					shouldBuild = false
   111  				}
   112  			}
   113  		}
   114  	}
   115  
   116  	return shouldBuild
   117  }
   118  
   119  func parseFileHeader(content []byte) (trimmed, goBuild []byte, sawBinaryOnly bool, err error) {
   120  	end := 0
   121  	p := content
   122  	ended := false       // found non-blank, non-// line, so stopped accepting // +build lines
   123  	inSlashStar := false // in /* */ comment
   124  
   125  Lines:
   126  	for len(p) > 0 {
   127  		line := p
   128  		if i := bytes.IndexByte(line, '\n'); i >= 0 {
   129  			line, p = line[:i], p[i+1:]
   130  		} else {
   131  			p = p[len(p):]
   132  		}
   133  		line = bytes.TrimSpace(line)
   134  		if len(line) == 0 && !ended { // Blank line
   135  			// Remember position of most recent blank line.
   136  			// When we find the first non-blank, non-// line,
   137  			// this "end" position marks the latest file position
   138  			// where a // +build line can appear.
   139  			// (It must appear _before_ a blank line before the non-blank, non-// line.
   140  			// Yes, that's confusing, which is part of why we moved to //go:build lines.)
   141  			// Note that ended==false here means that inSlashStar==false,
   142  			// since seeing a /* would have set ended==true.
   143  			end = len(content) - len(p)
   144  			continue Lines
   145  		}
   146  		if !bytes.HasPrefix(line, bSlashSlash) { // Not comment line
   147  			ended = true
   148  		}
   149  
   150  		if !inSlashStar && isGoBuildComment(line) {
   151  			if goBuild != nil {
   152  				return nil, nil, false, errMultipleGoBuild
   153  			}
   154  			goBuild = line
   155  		}
   156  
   157  	Comments:
   158  		for len(line) > 0 {
   159  			if inSlashStar {
   160  				if i := bytes.Index(line, bStarSlash); i >= 0 {
   161  					inSlashStar = false
   162  					line = bytes.TrimSpace(line[i+len(bStarSlash):])
   163  					continue Comments
   164  				}
   165  				continue Lines
   166  			}
   167  			if bytes.HasPrefix(line, bSlashSlash) {
   168  				continue Lines
   169  			}
   170  			if bytes.HasPrefix(line, bSlashStar) {
   171  				inSlashStar = true
   172  				line = bytes.TrimSpace(line[len(bSlashStar):])
   173  				continue Comments
   174  			}
   175  			// Found non-comment text.
   176  			break Lines
   177  		}
   178  	}
   179  
   180  	return content[:end], goBuild, sawBinaryOnly, nil
   181  }
   182  
   183  // matchTag reports whether the tag name is valid and tags[name] is true.
   184  // As a special case, if tags["*"] is true and name is not empty or ignore,
   185  // then matchTag will return prefer instead of the actual answer,
   186  // which allows the caller to pretend in that case that most tags are
   187  // both true and false.
   188  func matchTag(name string, tags map[string]bool, prefer bool) bool {
   189  	// Tags must be letters, digits, underscores or dots.
   190  	// Unlike in Go identifiers, all digits are fine (e.g., "386").
   191  	for _, c := range name {
   192  		if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' {
   193  			return false
   194  		}
   195  	}
   196  
   197  	if tags["*"] && name != "" && name != "ignore" {
   198  		// Special case for gathering all possible imports:
   199  		// if we put * in the tags map then all tags
   200  		// except "ignore" are considered both present and not
   201  		// (so we return true no matter how 'want' is set).
   202  		return prefer
   203  	}
   204  
   205  	if tags[name] {
   206  		return true
   207  	}
   208  
   209  	switch name {
   210  	case "linux":
   211  		return tags["android"]
   212  	case "solaris":
   213  		return tags["illumos"]
   214  	case "darwin":
   215  		return tags["ios"]
   216  	case "unix":
   217  		return syslist.UnixOS[cfg.BuildContext.GOOS]
   218  	default:
   219  		return false
   220  	}
   221  }
   222  
   223  // eval is like
   224  //
   225  //	x.Eval(func(tag string) bool { return matchTag(tag, tags) })
   226  //
   227  // except that it implements the special case for tags["*"] meaning
   228  // all tags are both true and false at the same time.
   229  func eval(x constraint.Expr, tags map[string]bool, prefer bool) bool {
   230  	switch x := x.(type) {
   231  	case *constraint.TagExpr:
   232  		return matchTag(x.Tag, tags, prefer)
   233  	case *constraint.NotExpr:
   234  		return !eval(x.X, tags, !prefer)
   235  	case *constraint.AndExpr:
   236  		return eval(x.X, tags, prefer) && eval(x.Y, tags, prefer)
   237  	case *constraint.OrExpr:
   238  		return eval(x.X, tags, prefer) || eval(x.Y, tags, prefer)
   239  	}
   240  	panic(fmt.Sprintf("unexpected constraint expression %T", x))
   241  }
   242  
   243  // Eval is like
   244  //
   245  //	x.Eval(func(tag string) bool { return matchTag(tag, tags) })
   246  //
   247  // except that it implements the special case for tags["*"] meaning
   248  // all tags are both true and false at the same time.
   249  func Eval(x constraint.Expr, tags map[string]bool, prefer bool) bool {
   250  	return eval(x, tags, prefer)
   251  }
   252  
   253  // MatchFile returns false if the name contains a $GOOS or $GOARCH
   254  // suffix which does not match the current system.
   255  // The recognized name formats are:
   256  //
   257  //	name_$(GOOS).*
   258  //	name_$(GOARCH).*
   259  //	name_$(GOOS)_$(GOARCH).*
   260  //	name_$(GOOS)_test.*
   261  //	name_$(GOARCH)_test.*
   262  //	name_$(GOOS)_$(GOARCH)_test.*
   263  //
   264  // Exceptions:
   265  //
   266  //	if GOOS=android, then files with GOOS=linux are also matched.
   267  //	if GOOS=illumos, then files with GOOS=solaris are also matched.
   268  //	if GOOS=ios, then files with GOOS=darwin are also matched.
   269  //
   270  // If tags["*"] is true, then MatchFile will consider all possible
   271  // GOOS and GOARCH to be available and will consequently
   272  // always return true.
   273  func MatchFile(name string, tags map[string]bool) bool {
   274  	if tags["*"] {
   275  		return true
   276  	}
   277  	if dot := strings.Index(name, "."); dot != -1 {
   278  		name = name[:dot]
   279  	}
   280  
   281  	// Before Go 1.4, a file called "linux.go" would be equivalent to having a
   282  	// build tag "linux" in that file. For Go 1.4 and beyond, we require this
   283  	// auto-tagging to apply only to files with a non-empty prefix, so
   284  	// "foo_linux.go" is tagged but "linux.go" is not. This allows new operating
   285  	// systems, such as android, to arrive without breaking existing code with
   286  	// innocuous source code in "android.go". The easiest fix: cut everything
   287  	// in the name before the initial _.
   288  	i := strings.Index(name, "_")
   289  	if i < 0 {
   290  		return true
   291  	}
   292  	name = name[i:] // ignore everything before first _
   293  
   294  	l := strings.Split(name, "_")
   295  	if n := len(l); n > 0 && l[n-1] == "test" {
   296  		l = l[:n-1]
   297  	}
   298  	n := len(l)
   299  	if n >= 2 && syslist.KnownOS[l[n-2]] && syslist.KnownArch[l[n-1]] {
   300  		return matchTag(l[n-2], tags, true) && matchTag(l[n-1], tags, true)
   301  	}
   302  	if n >= 1 && syslist.KnownOS[l[n-1]] {
   303  		return matchTag(l[n-1], tags, true)
   304  	}
   305  	if n >= 1 && syslist.KnownArch[l[n-1]] {
   306  		return matchTag(l[n-1], tags, true)
   307  	}
   308  	return true
   309  }
   310  

View as plain text