| 1 | // Copyright 2013 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 | // Package buildtag defines an Analyzer that checks build tags. |
| 6 | package buildtag |
| 7 | |
| 8 | import ( |
| 9 | "go/ast" |
| 10 | "go/build/constraint" |
| 11 | "go/parser" |
| 12 | "go/token" |
| 13 | "strings" |
| 14 | "unicode" |
| 15 | |
| 16 | "golang.org/x/tools/go/analysis" |
| 17 | "golang.org/x/tools/internal/analysis/analyzerutil" |
| 18 | ) |
| 19 | |
| 20 | const Doc = "check //go:build and // +build directives" |
| 21 | |
| 22 | var Analyzer = &analysis.Analyzer{ |
| 23 | Name: "buildtag", |
| 24 | Doc: Doc, |
| 25 | URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/buildtag", |
| 26 | Run: runBuildTag, |
| 27 | } |
| 28 | |
| 29 | func runBuildTag(pass *analysis.Pass) (any, error) { |
| 30 | for _, f := range pass.Files { |
| 31 | checkGoFile(pass, f) |
| 32 | } |
| 33 | for _, name := range pass.OtherFiles { |
| 34 | if err := checkOtherFile(pass, name); err != nil { |
| 35 | return nil, err |
| 36 | } |
| 37 | } |
| 38 | for _, name := range pass.IgnoredFiles { |
| 39 | if strings.HasSuffix(name, ".go") { |
| 40 | f, err := parser.ParseFile(pass.Fset, name, nil, parser.ParseComments|parser.SkipObjectResolution) |
| 41 | if err != nil { |
| 42 | // Not valid Go source code - not our job to diagnose, so ignore. |
| 43 | return nil, nil |
| 44 | } |
| 45 | checkGoFile(pass, f) |
| 46 | } else { |
| 47 | if err := checkOtherFile(pass, name); err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | return nil, nil |
| 53 | } |
| 54 | |
| 55 | func checkGoFile(pass *analysis.Pass, f *ast.File) { |
| 56 | var check checker |
| 57 | check.init(pass) |
| 58 | defer check.finish() |
| 59 | |
| 60 | for _, group := range f.Comments { |
| 61 | // A +build comment is ignored after or adjoining the package declaration. |
| 62 | if group.End()+1 >= f.Package { |
| 63 | check.plusBuildOK = false |
| 64 | } |
| 65 | // A //go:build comment is ignored after the package declaration |
| 66 | // (but adjoining it is OK, in contrast to +build comments). |
| 67 | if group.Pos() >= f.Package { |
| 68 | check.goBuildOK = false |
| 69 | } |
| 70 | |
| 71 | // Check each line of a //-comment. |
| 72 | for _, c := range group.List { |
| 73 | // "+build" is ignored within or after a /*...*/ comment. |
| 74 | if !strings.HasPrefix(c.Text, "//") { |
| 75 | check.plusBuildOK = false |
| 76 | } |
| 77 | check.comment(c.Slash, c.Text) |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | func checkOtherFile(pass *analysis.Pass, filename string) error { |
| 83 | var check checker |
| 84 | check.init(pass) |
| 85 | defer check.finish() |
| 86 | |
| 87 | // We cannot use the Go parser, since this may not be a Go source file. |
| 88 | // Read the raw bytes instead. |
| 89 | content, tf, err := analyzerutil.ReadFile(pass, filename) |
| 90 | if err != nil { |
| 91 | return err |
| 92 | } |
| 93 | |
| 94 | check.file(token.Pos(tf.Base()), string(content)) |
| 95 | return nil |
| 96 | } |
| 97 | |
| 98 | type checker struct { |
| 99 | pass *analysis.Pass |
| 100 | plusBuildOK bool // "+build" lines still OK |
| 101 | goBuildOK bool // "go:build" lines still OK |
| 102 | crossCheck bool // cross-check go:build and +build lines when done reading file |
| 103 | inStar bool // currently in a /* */ comment |
| 104 | goBuildPos token.Pos // position of first go:build line found |
| 105 | plusBuildPos token.Pos // position of first "+build" line found |
| 106 | goBuild constraint.Expr // go:build constraint found |
| 107 | plusBuild constraint.Expr // AND of +build constraints found |
| 108 | } |
| 109 | |
| 110 | func (check *checker) init(pass *analysis.Pass) { |
| 111 | check.pass = pass |
| 112 | check.goBuildOK = true |
| 113 | check.plusBuildOK = true |
| 114 | check.crossCheck = true |
| 115 | } |
| 116 | |
| 117 | func (check *checker) file(pos token.Pos, text string) { |
| 118 | // Determine cutpoint where +build comments are no longer valid. |
| 119 | // They are valid in leading // comments in the file followed by |
| 120 | // a blank line. |
| 121 | // |
| 122 | // This must be done as a separate pass because of the |
| 123 | // requirement that the comment be followed by a blank line. |
| 124 | var plusBuildCutoff int |
| 125 | fullText := text |
| 126 | for text != "" { |
| 127 | i := strings.Index(text, "\n") |
| 128 | if i < 0 { |
| 129 | i = len(text) |
| 130 | } else { |
| 131 | i++ |
| 132 | } |
| 133 | offset := len(fullText) - len(text) |
| 134 | line := text[:i] |
| 135 | text = text[i:] |
| 136 | line = strings.TrimSpace(line) |
| 137 | if !strings.HasPrefix(line, "//") && line != "" { |
| 138 | break |
| 139 | } |
| 140 | if line == "" { |
| 141 | plusBuildCutoff = offset |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | // Process each line. |
| 146 | // Must stop once we hit goBuildOK == false |
| 147 | text = fullText |
| 148 | check.inStar = false |
| 149 | for text != "" { |
| 150 | i := strings.Index(text, "\n") |
| 151 | if i < 0 { |
| 152 | i = len(text) |
| 153 | } else { |
| 154 | i++ |
| 155 | } |
| 156 | offset := len(fullText) - len(text) |
| 157 | line := text[:i] |
| 158 | text = text[i:] |
| 159 | check.plusBuildOK = offset < plusBuildCutoff |
| 160 | |
| 161 | if strings.HasPrefix(line, "//") { |
| 162 | check.comment(pos+token.Pos(offset), line) |
| 163 | continue |
| 164 | } |
| 165 | |
| 166 | // Keep looking for the point at which //go:build comments |
| 167 | // stop being allowed. Skip over, cut out any /* */ comments. |
| 168 | for { |
| 169 | line = strings.TrimSpace(line) |
| 170 | if check.inStar { |
| 171 | i := strings.Index(line, "*/") |
| 172 | if i < 0 { |
| 173 | line = "" |
| 174 | break |
| 175 | } |
| 176 | line = line[i+len("*/"):] |
| 177 | check.inStar = false |
| 178 | continue |
| 179 | } |
| 180 | if strings.HasPrefix(line, "/*") { |
| 181 | check.inStar = true |
| 182 | line = line[len("/*"):] |
| 183 | continue |
| 184 | } |
| 185 | break |
| 186 | } |
| 187 | if line != "" { |
| 188 | // Found non-comment non-blank line. |
| 189 | // Ends space for valid //go:build comments, |
| 190 | // but also ends the fraction of the file we can |
| 191 | // reliably parse. From this point on we might |
| 192 | // incorrectly flag "comments" inside multiline |
| 193 | // string constants or anything else (this might |
| 194 | // not even be a Go program). So stop. |
| 195 | break |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | func (check *checker) comment(pos token.Pos, text string) { |
| 201 | if strings.HasPrefix(text, "//") { |
| 202 | if strings.Contains(text, "+build") { |
| 203 | check.plusBuildLine(pos, text) |
| 204 | } |
| 205 | if strings.Contains(text, "//go:build") { |
| 206 | check.goBuildLine(pos, text) |
| 207 | } |
| 208 | } |
| 209 | if strings.HasPrefix(text, "/*") { |
| 210 | if i := strings.Index(text, "\n"); i >= 0 { |
| 211 | // multiline /* */ comment - process interior lines |
| 212 | check.inStar = true |
| 213 | i++ |
| 214 | pos += token.Pos(i) |
| 215 | text = text[i:] |
| 216 | for text != "" { |
| 217 | i := strings.Index(text, "\n") |
| 218 | if i < 0 { |
| 219 | i = len(text) |
| 220 | } else { |
| 221 | i++ |
| 222 | } |
| 223 | line := text[:i] |
| 224 | if strings.HasPrefix(line, "//") { |
| 225 | check.comment(pos, line) |
| 226 | } |
| 227 | pos += token.Pos(i) |
| 228 | text = text[i:] |
| 229 | } |
| 230 | check.inStar = false |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | func (check *checker) goBuildLine(pos token.Pos, line string) { |
| 236 | if !constraint.IsGoBuild(line) { |
| 237 | if !strings.HasPrefix(line, "//go:build") && constraint.IsGoBuild("//"+strings.TrimSpace(line[len("//"):])) { |
| 238 | check.pass.Reportf(pos, "malformed //go:build line (space between // and go:build)") |
| 239 | } |
| 240 | return |
| 241 | } |
| 242 | if !check.goBuildOK || check.inStar { |
| 243 | check.pass.Reportf(pos, "misplaced //go:build comment") |
| 244 | check.crossCheck = false |
| 245 | return |
| 246 | } |
| 247 | |
| 248 | if check.goBuildPos == token.NoPos { |
| 249 | check.goBuildPos = pos |
| 250 | } else { |
| 251 | check.pass.Reportf(pos, "unexpected extra //go:build line") |
| 252 | check.crossCheck = false |
| 253 | } |
| 254 | |
| 255 | // testing hack: stop at // ERROR |
| 256 | if i := strings.Index(line, " // ERROR "); i >= 0 { |
| 257 | line = line[:i] |
| 258 | } |
| 259 | |
| 260 | x, err := constraint.Parse(line) |
| 261 | if err != nil { |
| 262 | check.pass.Reportf(pos, "%v", err) |
| 263 | check.crossCheck = false |
| 264 | return |
| 265 | } |
| 266 | |
| 267 | check.tags(pos, x) |
| 268 | |
| 269 | if check.goBuild == nil { |
| 270 | check.goBuild = x |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | func (check *checker) plusBuildLine(pos token.Pos, line string) { |
| 275 | line = strings.TrimSpace(line) |
| 276 | if !constraint.IsPlusBuild(line) { |
| 277 | // Comment with +build but not at beginning. |
| 278 | // Only report early in file. |
| 279 | if check.plusBuildOK && !strings.HasPrefix(line, "// want") { |
| 280 | check.pass.Reportf(pos, "possible malformed +build comment") |
| 281 | } |
| 282 | return |
| 283 | } |
| 284 | if !check.plusBuildOK { // inStar implies !plusBuildOK |
| 285 | check.pass.Reportf(pos, "misplaced +build comment") |
| 286 | check.crossCheck = false |
| 287 | } |
| 288 | |
| 289 | if check.plusBuildPos == token.NoPos { |
| 290 | check.plusBuildPos = pos |
| 291 | } |
| 292 | |
| 293 | // testing hack: stop at // ERROR |
| 294 | if i := strings.Index(line, " // ERROR "); i >= 0 { |
| 295 | line = line[:i] |
| 296 | } |
| 297 | |
| 298 | fields := strings.Fields(line[len("//"):]) |
| 299 | // IsPlusBuildConstraint check above implies fields[0] == "+build" |
| 300 | for _, arg := range fields[1:] { |
| 301 | for elem := range strings.SplitSeq(arg, ",") { |
| 302 | if strings.HasPrefix(elem, "!!") { |
| 303 | check.pass.Reportf(pos, "invalid double negative in build constraint: %s", arg) |
| 304 | check.crossCheck = false |
| 305 | continue |
| 306 | } |
| 307 | elem = strings.TrimPrefix(elem, "!") |
| 308 | for _, c := range elem { |
| 309 | if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' { |
| 310 | check.pass.Reportf(pos, "invalid non-alphanumeric build constraint: %s", arg) |
| 311 | check.crossCheck = false |
| 312 | break |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | if check.crossCheck { |
| 319 | y, err := constraint.Parse(line) |
| 320 | if err != nil { |
| 321 | // Should never happen - constraint.Parse never rejects a // +build line. |
| 322 | // Also, we just checked the syntax above. |
| 323 | // Even so, report. |
| 324 | check.pass.Reportf(pos, "%v", err) |
| 325 | check.crossCheck = false |
| 326 | return |
| 327 | } |
| 328 | check.tags(pos, y) |
| 329 | |
| 330 | if check.plusBuild == nil { |
| 331 | check.plusBuild = y |
| 332 | } else { |
| 333 | check.plusBuild = &constraint.AndExpr{X: check.plusBuild, Y: y} |
| 334 | } |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | func (check *checker) finish() { |
| 339 | if !check.crossCheck || check.plusBuildPos == token.NoPos || check.goBuildPos == token.NoPos { |
| 340 | return |
| 341 | } |
| 342 | |
| 343 | // Have both //go:build and // +build, |
| 344 | // with no errors found (crossCheck still true). |
| 345 | // Check they match. |
| 346 | var want constraint.Expr |
| 347 | lines, err := constraint.PlusBuildLines(check.goBuild) |
| 348 | if err != nil { |
| 349 | check.pass.Reportf(check.goBuildPos, "%v", err) |
| 350 | return |
| 351 | } |
| 352 | for _, line := range lines { |
| 353 | y, err := constraint.Parse(line) |
| 354 | if err != nil { |
| 355 | // Definitely should not happen, but not the user's fault. |
| 356 | // Do not report. |
| 357 | return |
| 358 | } |
| 359 | if want == nil { |
| 360 | want = y |
| 361 | } else { |
| 362 | want = &constraint.AndExpr{X: want, Y: y} |
| 363 | } |
| 364 | } |
| 365 | if want.String() != check.plusBuild.String() { |
| 366 | check.pass.Reportf(check.plusBuildPos, "+build lines do not match //go:build condition") |
| 367 | return |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | // tags reports issues in go versions in tags within the expression e. |
| 372 | func (check *checker) tags(pos token.Pos, e constraint.Expr) { |
| 373 | // Use Eval to visit each tag. |
| 374 | _ = e.Eval(func(tag string) bool { |
| 375 | if malformedGoTag(tag) { |
| 376 | check.pass.Reportf(pos, "invalid go version %q in build constraint", tag) |
| 377 | } |
| 378 | return false // result is immaterial as Eval does not short-circuit |
| 379 | }) |
| 380 | } |
| 381 | |
| 382 | // malformedGoTag returns true if a tag is likely to be a malformed |
| 383 | // go version constraint. |
| 384 | func malformedGoTag(tag string) bool { |
| 385 | // Not a go version? |
| 386 | if !strings.HasPrefix(tag, "go1") { |
| 387 | // Check for close misspellings of the "go1." prefix. |
| 388 | for _, pre := range []string{"go.", "g1.", "go"} { |
| 389 | suffix := strings.TrimPrefix(tag, pre) |
| 390 | if suffix != tag && validGoVersion("go1."+suffix) { |
| 391 | return true |
| 392 | } |
| 393 | } |
| 394 | return false |
| 395 | } |
| 396 | |
| 397 | // The tag starts with "go1" so it is almost certainly a GoVersion. |
| 398 | // Report it if it is not a valid build constraint. |
| 399 | return !validGoVersion(tag) |
| 400 | } |
| 401 | |
| 402 | // validGoVersion reports when a tag is a valid go version. |
| 403 | func validGoVersion(tag string) bool { |
| 404 | return constraint.GoVersion(&constraint.TagExpr{Tag: tag}) != "" |
| 405 | } |