| 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 | package expect |
| 6 | |
| 7 | import ( |
| 8 | "fmt" |
| 9 | "go/ast" |
| 10 | "go/parser" |
| 11 | goscanner "go/scanner" |
| 12 | "go/token" |
| 13 | "os" |
| 14 | "path/filepath" |
| 15 | "regexp" |
| 16 | "strconv" |
| 17 | "strings" |
| 18 | "text/scanner" |
| 19 | |
| 20 | "golang.org/x/mod/modfile" |
| 21 | ) |
| 22 | |
| 23 | const commentStart = "@" |
| 24 | const commentStartLen = len(commentStart) |
| 25 | |
| 26 | // Identifier is the type for an identifier in a Note argument list. |
| 27 | type Identifier string |
| 28 | |
| 29 | // Parse collects all the notes present in a file. |
| 30 | // If content is nil, the filename specified is read and parsed, otherwise the |
| 31 | // content is used and the filename is used for positions and error messages. |
| 32 | // Each comment whose text starts with @ is parsed as a comma-separated |
| 33 | // sequence of notes. |
| 34 | // See the package documentation for details about the syntax of those |
| 35 | // notes. |
| 36 | func Parse(fset *token.FileSet, filename string, content []byte) ([]*Note, error) { |
| 37 | if content == nil { |
| 38 | data, err := os.ReadFile(filename) |
| 39 | if err != nil { |
| 40 | return nil, err |
| 41 | } |
| 42 | content = data |
| 43 | } |
| 44 | |
| 45 | switch filepath.Ext(filename) { |
| 46 | case ".s": |
| 47 | // The assembler uses a custom scanner, |
| 48 | // but the go/scanner package is close |
| 49 | // enough: we only want the comments. |
| 50 | file := fset.AddFile(filename, -1, len(content)) |
| 51 | var scan goscanner.Scanner |
| 52 | scan.Init(file, content, nil, goscanner.ScanComments) |
| 53 | |
| 54 | var notes []*Note |
| 55 | for { |
| 56 | pos, tok, lit := scan.Scan() |
| 57 | if tok == token.EOF { |
| 58 | break |
| 59 | } |
| 60 | if tok == token.COMMENT { |
| 61 | text, adjust := getAdjustedNote(lit) |
| 62 | if text == "" { |
| 63 | continue |
| 64 | } |
| 65 | parsed, err := parse(file, pos+token.Pos(adjust), text) |
| 66 | if err != nil { |
| 67 | return nil, err |
| 68 | } |
| 69 | notes = append(notes, parsed...) |
| 70 | } |
| 71 | } |
| 72 | return notes, nil |
| 73 | |
| 74 | case ".go": |
| 75 | // TODO: We should write this in terms of the scanner, like the .s case above. |
| 76 | // there are ways you can break the parser such that it will not add all the |
| 77 | // comments to the ast, which may result in files where the tests are silently |
| 78 | // not run. |
| 79 | file, err := parser.ParseFile(fset, filename, content, parser.ParseComments|parser.AllErrors|parser.SkipObjectResolution) |
| 80 | if file == nil { |
| 81 | return nil, err |
| 82 | } |
| 83 | return ExtractGo(fset.File(file.Pos()), file) |
| 84 | |
| 85 | case ".mod": |
| 86 | file, err := modfile.Parse(filename, content, nil) |
| 87 | if err != nil { |
| 88 | return nil, err |
| 89 | } |
| 90 | f := fset.AddFile(filename, -1, len(content)) |
| 91 | f.SetLinesForContent(content) |
| 92 | notes, err := extractModWork(fset, file.Syntax.Stmt) |
| 93 | if err != nil { |
| 94 | return nil, err |
| 95 | } |
| 96 | // Since modfile.Parse does not return an *ast, we need to add the offset |
| 97 | // within the file's contents to the file's base relative to the fileset. |
| 98 | for _, note := range notes { |
| 99 | note.Pos += token.Pos(f.Base()) |
| 100 | } |
| 101 | return notes, nil |
| 102 | |
| 103 | case ".work": |
| 104 | file, err := modfile.ParseWork(filename, content, nil) |
| 105 | if err != nil { |
| 106 | return nil, err |
| 107 | } |
| 108 | f := fset.AddFile(filename, -1, len(content)) |
| 109 | f.SetLinesForContent(content) |
| 110 | notes, err := extractModWork(fset, file.Syntax.Stmt) |
| 111 | if err != nil { |
| 112 | return nil, err |
| 113 | } |
| 114 | // As with go.mod files, we need to compute a synthetic token.Pos. |
| 115 | for _, note := range notes { |
| 116 | note.Pos += token.Pos(f.Base()) |
| 117 | } |
| 118 | return notes, nil |
| 119 | } |
| 120 | return nil, nil |
| 121 | } |
| 122 | |
| 123 | // extractModWork collects all the notes present in a go.mod file or go.work |
| 124 | // file, by way of the shared modfile.Expr statement node. |
| 125 | // |
| 126 | // Each comment whose text starts with @ is parsed as a comma-separated |
| 127 | // sequence of notes. |
| 128 | // See the package documentation for details about the syntax of those |
| 129 | // notes. |
| 130 | // Only allow notes to appear with the following format: "//@mark()" or // @mark() |
| 131 | func extractModWork(fset *token.FileSet, exprs []modfile.Expr) ([]*Note, error) { |
| 132 | var notes []*Note |
| 133 | for _, stmt := range exprs { |
| 134 | comment := stmt.Comment() |
| 135 | if comment == nil { |
| 136 | continue |
| 137 | } |
| 138 | var allComments []modfile.Comment |
| 139 | allComments = append(allComments, comment.Before...) |
| 140 | allComments = append(allComments, comment.Suffix...) |
| 141 | for _, cmt := range allComments { |
| 142 | text, adjust := getAdjustedNote(cmt.Token) |
| 143 | if text == "" { |
| 144 | continue |
| 145 | } |
| 146 | pos := token.Pos(int(cmt.Start.Byte) + adjust) |
| 147 | parsed, err := parse(fset.File(pos), pos, text) |
| 148 | if err != nil { |
| 149 | return nil, err |
| 150 | } |
| 151 | notes = append(notes, parsed...) |
| 152 | } |
| 153 | } |
| 154 | return notes, nil |
| 155 | } |
| 156 | |
| 157 | // ExtractGo collects all the notes present in an AST. |
| 158 | // Each comment whose text starts with @ is parsed as a comma-separated |
| 159 | // sequence of notes. |
| 160 | // See the package documentation for details about the syntax of those |
| 161 | // notes. |
| 162 | func ExtractGo(tokFile *token.File, file *ast.File) ([]*Note, error) { |
| 163 | var notes []*Note |
| 164 | for _, g := range file.Comments { |
| 165 | for _, c := range g.List { |
| 166 | text, adjust := getAdjustedNote(c.Text) |
| 167 | if text == "" { |
| 168 | continue |
| 169 | } |
| 170 | parsed, err := parse(tokFile, token.Pos(int(c.Pos())+adjust), text) |
| 171 | if err != nil { |
| 172 | return nil, err |
| 173 | } |
| 174 | notes = append(notes, parsed...) |
| 175 | } |
| 176 | } |
| 177 | return notes, nil |
| 178 | } |
| 179 | |
| 180 | func getAdjustedNote(text string) (string, int) { |
| 181 | if strings.HasPrefix(text, "/*") { |
| 182 | text = strings.TrimSuffix(text, "*/") |
| 183 | } |
| 184 | text = text[2:] // remove "//" or "/*" prefix |
| 185 | |
| 186 | // Allow notes to appear within comments. |
| 187 | // For example: |
| 188 | // "// //@mark()" is valid. |
| 189 | // "// @mark()" is not valid. |
| 190 | // "// /*@mark()*/" is not valid. |
| 191 | var adjust int |
| 192 | if i := strings.Index(text, commentStart); i > 2 { |
| 193 | // Get the text before the commentStart. |
| 194 | pre := text[i-2 : i] |
| 195 | if pre != "//" { |
| 196 | return "", 0 |
| 197 | } |
| 198 | text = text[i:] |
| 199 | adjust = i |
| 200 | } |
| 201 | if !strings.HasPrefix(text, commentStart) { |
| 202 | return "", 0 |
| 203 | } |
| 204 | text = text[commentStartLen:] |
| 205 | return text, commentStartLen + adjust + 1 |
| 206 | } |
| 207 | |
| 208 | const invalidToken rune = 0 |
| 209 | |
| 210 | type tokens struct { |
| 211 | scanner scanner.Scanner |
| 212 | current rune |
| 213 | err error |
| 214 | base token.Pos |
| 215 | } |
| 216 | |
| 217 | func (t *tokens) Init(base token.Pos, text string) *tokens { |
| 218 | t.base = base |
| 219 | t.scanner.Init(strings.NewReader(text)) |
| 220 | t.scanner.Mode = scanner.GoTokens |
| 221 | t.scanner.Whitespace ^= 1 << '\n' // don't skip new lines |
| 222 | t.scanner.Error = func(s *scanner.Scanner, msg string) { |
| 223 | t.Errorf("%v", msg) |
| 224 | } |
| 225 | return t |
| 226 | } |
| 227 | |
| 228 | func (t *tokens) Consume() string { |
| 229 | t.current = invalidToken |
| 230 | return t.scanner.TokenText() |
| 231 | } |
| 232 | |
| 233 | func (t *tokens) Token() rune { |
| 234 | if t.err != nil { |
| 235 | return scanner.EOF |
| 236 | } |
| 237 | if t.current == invalidToken { |
| 238 | t.current = t.scanner.Scan() |
| 239 | } |
| 240 | return t.current |
| 241 | } |
| 242 | |
| 243 | func (t *tokens) Skip(r rune) int { |
| 244 | i := 0 |
| 245 | for t.Token() == '\n' { |
| 246 | t.Consume() |
| 247 | i++ |
| 248 | } |
| 249 | return i |
| 250 | } |
| 251 | |
| 252 | func (t *tokens) TokenString() string { |
| 253 | return scanner.TokenString(t.Token()) |
| 254 | } |
| 255 | |
| 256 | func (t *tokens) Pos() token.Pos { |
| 257 | return t.base + token.Pos(t.scanner.Position.Offset) |
| 258 | } |
| 259 | |
| 260 | func (t *tokens) Errorf(msg string, args ...any) { |
| 261 | if t.err != nil { |
| 262 | return |
| 263 | } |
| 264 | t.err = fmt.Errorf(msg, args...) |
| 265 | } |
| 266 | |
| 267 | func parse(tokFile *token.File, base token.Pos, text string) ([]*Note, error) { |
| 268 | t := new(tokens).Init(base, text) |
| 269 | notes := parseComment(t) |
| 270 | if t.err != nil { |
| 271 | return nil, fmt.Errorf("%v: %s", tokFile.Position(t.Pos()), t.err) |
| 272 | } |
| 273 | return notes, nil |
| 274 | } |
| 275 | |
| 276 | func parseComment(t *tokens) []*Note { |
| 277 | var notes []*Note |
| 278 | for { |
| 279 | t.Skip('\n') |
| 280 | switch t.Token() { |
| 281 | case scanner.EOF: |
| 282 | return notes |
| 283 | case scanner.Ident: |
| 284 | notes = append(notes, parseNote(t)) |
| 285 | default: |
| 286 | t.Errorf("unexpected %s parsing comment, expect identifier", t.TokenString()) |
| 287 | return nil |
| 288 | } |
| 289 | switch t.Token() { |
| 290 | case scanner.EOF: |
| 291 | return notes |
| 292 | case ',', '\n': |
| 293 | t.Consume() |
| 294 | default: |
| 295 | t.Errorf("unexpected %s parsing comment, expect separator", t.TokenString()) |
| 296 | return nil |
| 297 | } |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | func parseNote(t *tokens) *Note { |
| 302 | n := &Note{ |
| 303 | Pos: t.Pos(), |
| 304 | Name: t.Consume(), |
| 305 | } |
| 306 | |
| 307 | switch t.Token() { |
| 308 | case ',', '\n', scanner.EOF: |
| 309 | // no argument list present |
| 310 | return n |
| 311 | case '(': |
| 312 | n.Args, n.NamedArgs = parseArgumentList(t) |
| 313 | return n |
| 314 | default: |
| 315 | t.Errorf("unexpected %s parsing note", t.TokenString()) |
| 316 | return nil |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | func parseArgumentList(t *tokens) (args []any, named map[string]any) { |
| 321 | args = []any{} // @name() is represented by a non-nil empty slice. |
| 322 | t.Consume() // '(' |
| 323 | t.Skip('\n') |
| 324 | for t.Token() != ')' { |
| 325 | name, arg := parseArgument(t) |
| 326 | if name != "" { |
| 327 | // f(k=v) |
| 328 | if named == nil { |
| 329 | named = make(map[string]any) |
| 330 | } |
| 331 | if _, dup := named[name]; dup { |
| 332 | t.Errorf("duplicate named argument %q", name) |
| 333 | return nil, nil |
| 334 | } |
| 335 | named[name] = arg |
| 336 | } else { |
| 337 | // f(v) |
| 338 | if named != nil { |
| 339 | t.Errorf("positional argument follows named argument") |
| 340 | return nil, nil |
| 341 | } |
| 342 | args = append(args, arg) |
| 343 | } |
| 344 | if t.Token() != ',' { |
| 345 | break |
| 346 | } |
| 347 | t.Consume() |
| 348 | t.Skip('\n') |
| 349 | } |
| 350 | if t.Token() != ')' { |
| 351 | t.Errorf("unexpected %s parsing argument list", t.TokenString()) |
| 352 | return nil, nil |
| 353 | } |
| 354 | t.Consume() // ')' |
| 355 | return args, named |
| 356 | } |
| 357 | |
| 358 | // parseArgument returns the value of the argument ("f(value)"), |
| 359 | // and its name if named "f(name=value)". |
| 360 | func parseArgument(t *tokens) (name string, value any) { |
| 361 | again: |
| 362 | switch t.Token() { |
| 363 | case scanner.Ident: |
| 364 | v := t.Consume() |
| 365 | switch v { |
| 366 | case "true": |
| 367 | value = true |
| 368 | case "false": |
| 369 | value = false |
| 370 | case "nil": |
| 371 | value = nil |
| 372 | case "re": |
| 373 | if t.Token() != scanner.String && t.Token() != scanner.RawString { |
| 374 | t.Errorf("re must be followed by string, got %s", t.TokenString()) |
| 375 | return |
| 376 | } |
| 377 | pattern, _ := strconv.Unquote(t.Consume()) // can't fail |
| 378 | re, err := regexp.Compile(pattern) |
| 379 | if err != nil { |
| 380 | t.Errorf("invalid regular expression %s: %v", pattern, err) |
| 381 | return |
| 382 | } |
| 383 | value = re |
| 384 | default: |
| 385 | // f(name=value)? |
| 386 | if name == "" && t.Token() == '=' { |
| 387 | t.Consume() // '=' |
| 388 | name = v |
| 389 | goto again |
| 390 | } |
| 391 | value = Identifier(v) |
| 392 | } |
| 393 | |
| 394 | case scanner.String, scanner.RawString: |
| 395 | value, _ = strconv.Unquote(t.Consume()) // can't fail |
| 396 | |
| 397 | case scanner.Int: |
| 398 | s := t.Consume() |
| 399 | v, err := strconv.ParseInt(s, 0, 0) |
| 400 | if err != nil { |
| 401 | t.Errorf("cannot convert %v to int: %v", s, err) |
| 402 | } |
| 403 | value = v |
| 404 | |
| 405 | case scanner.Float: |
| 406 | s := t.Consume() |
| 407 | v, err := strconv.ParseFloat(s, 64) |
| 408 | if err != nil { |
| 409 | t.Errorf("cannot convert %v to float: %v", s, err) |
| 410 | } |
| 411 | value = v |
| 412 | |
| 413 | case '-': |
| 414 | t.Consume() |
| 415 | switch t.Token() { |
| 416 | case scanner.Int: |
| 417 | s := "-" + t.Consume() |
| 418 | v, err := strconv.ParseInt(s, 0, 0) |
| 419 | if err != nil { |
| 420 | t.Errorf("cannot convert %v to int: %v", s, err) |
| 421 | } |
| 422 | value = v |
| 423 | |
| 424 | case scanner.Float: |
| 425 | s := "-" + t.Consume() |
| 426 | v, err := strconv.ParseFloat(s, 64) |
| 427 | if err != nil { |
| 428 | t.Errorf("cannot convert %v to float: %v", s, err) |
| 429 | } |
| 430 | value = v |
| 431 | |
| 432 | default: |
| 433 | t.Errorf("unexpected '-' not followed by number, got %s", t.TokenString()) |
| 434 | } |
| 435 | |
| 436 | case scanner.Char: |
| 437 | t.Errorf("unexpected char literal %s", t.Consume()) |
| 438 | |
| 439 | default: |
| 440 | t.Errorf("unexpected %s parsing argument", t.TokenString()) |
| 441 | } |
| 442 | return |
| 443 | } |