github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/src/go/printer/printer_test.go (about) 1 // Copyright 2009 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 printer 6 7 import ( 8 "bytes" 9 "errors" 10 "flag" 11 "fmt" 12 "go/ast" 13 "go/parser" 14 "go/token" 15 "io" 16 "io/ioutil" 17 "path/filepath" 18 "testing" 19 "time" 20 ) 21 22 const ( 23 dataDir = "testdata" 24 tabwidth = 8 25 ) 26 27 var update = flag.Bool("update", false, "update golden files") 28 29 var fset = token.NewFileSet() 30 31 type checkMode uint 32 33 const ( 34 export checkMode = 1 << iota 35 rawFormat 36 idempotent 37 ) 38 39 // format parses src, prints the corresponding AST, verifies the resulting 40 // src is syntactically correct, and returns the resulting src or an error 41 // if any. 42 func format(src []byte, mode checkMode) ([]byte, error) { 43 // parse src 44 f, err := parser.ParseFile(fset, "", src, parser.ParseComments) 45 if err != nil { 46 return nil, fmt.Errorf("parse: %s\n%s", err, src) 47 } 48 49 // filter exports if necessary 50 if mode&export != 0 { 51 ast.FileExports(f) // ignore result 52 f.Comments = nil // don't print comments that are not in AST 53 } 54 55 // determine printer configuration 56 cfg := Config{Tabwidth: tabwidth} 57 if mode&rawFormat != 0 { 58 cfg.Mode |= RawFormat 59 } 60 61 // print AST 62 var buf bytes.Buffer 63 if err := cfg.Fprint(&buf, fset, f); err != nil { 64 return nil, fmt.Errorf("print: %s", err) 65 } 66 67 // make sure formatted output is syntactically correct 68 res := buf.Bytes() 69 if _, err := parser.ParseFile(fset, "", res, 0); err != nil { 70 return nil, fmt.Errorf("re-parse: %s\n%s", err, buf.Bytes()) 71 } 72 73 return res, nil 74 } 75 76 // lineAt returns the line in text starting at offset offs. 77 func lineAt(text []byte, offs int) []byte { 78 i := offs 79 for i < len(text) && text[i] != '\n' { 80 i++ 81 } 82 return text[offs:i] 83 } 84 85 // diff compares a and b. 86 func diff(aname, bname string, a, b []byte) error { 87 var buf bytes.Buffer // holding long error message 88 89 // compare lengths 90 if len(a) != len(b) { 91 fmt.Fprintf(&buf, "\nlength changed: len(%s) = %d, len(%s) = %d", aname, len(a), bname, len(b)) 92 } 93 94 // compare contents 95 line := 1 96 offs := 1 97 for i := 0; i < len(a) && i < len(b); i++ { 98 ch := a[i] 99 if ch != b[i] { 100 fmt.Fprintf(&buf, "\n%s:%d:%d: %s", aname, line, i-offs+1, lineAt(a, offs)) 101 fmt.Fprintf(&buf, "\n%s:%d:%d: %s", bname, line, i-offs+1, lineAt(b, offs)) 102 fmt.Fprintf(&buf, "\n\n") 103 break 104 } 105 if ch == '\n' { 106 line++ 107 offs = i + 1 108 } 109 } 110 111 if buf.Len() > 0 { 112 return errors.New(buf.String()) 113 } 114 return nil 115 } 116 117 func runcheck(t *testing.T, source, golden string, mode checkMode) { 118 src, err := ioutil.ReadFile(source) 119 if err != nil { 120 t.Error(err) 121 return 122 } 123 124 res, err := format(src, mode) 125 if err != nil { 126 t.Error(err) 127 return 128 } 129 130 // update golden files if necessary 131 if *update { 132 if err := ioutil.WriteFile(golden, res, 0644); err != nil { 133 t.Error(err) 134 } 135 return 136 } 137 138 // get golden 139 gld, err := ioutil.ReadFile(golden) 140 if err != nil { 141 t.Error(err) 142 return 143 } 144 145 // formatted source and golden must be the same 146 if err := diff(source, golden, res, gld); err != nil { 147 t.Error(err) 148 return 149 } 150 151 if mode&idempotent != 0 { 152 // formatting golden must be idempotent 153 // (This is very difficult to achieve in general and for now 154 // it is only checked for files explicitly marked as such.) 155 res, err = format(gld, mode) 156 if err := diff(golden, fmt.Sprintf("format(%s)", golden), gld, res); err != nil { 157 t.Errorf("golden is not idempotent: %s", err) 158 } 159 } 160 } 161 162 func check(t *testing.T, source, golden string, mode checkMode) { 163 // run the test 164 cc := make(chan int) 165 go func() { 166 runcheck(t, source, golden, mode) 167 cc <- 0 168 }() 169 170 // wait with timeout 171 select { 172 case <-time.After(10 * time.Second): // plenty of a safety margin, even for very slow machines 173 // test running past time out 174 t.Errorf("%s: running too slowly", source) 175 case <-cc: 176 // test finished within allotted time margin 177 } 178 } 179 180 type entry struct { 181 source, golden string 182 mode checkMode 183 } 184 185 // Use go test -update to create/update the respective golden files. 186 var data = []entry{ 187 {"empty.input", "empty.golden", idempotent}, 188 {"comments.input", "comments.golden", 0}, 189 {"comments.input", "comments.x", export}, 190 {"comments2.input", "comments2.golden", idempotent}, 191 {"linebreaks.input", "linebreaks.golden", idempotent}, 192 {"expressions.input", "expressions.golden", idempotent}, 193 {"expressions.input", "expressions.raw", rawFormat | idempotent}, 194 {"declarations.input", "declarations.golden", 0}, 195 {"statements.input", "statements.golden", 0}, 196 {"slow.input", "slow.golden", idempotent}, 197 } 198 199 func TestFiles(t *testing.T) { 200 for _, e := range data { 201 source := filepath.Join(dataDir, e.source) 202 golden := filepath.Join(dataDir, e.golden) 203 check(t, source, golden, e.mode) 204 // TODO(gri) check that golden is idempotent 205 //check(t, golden, golden, e.mode) 206 } 207 } 208 209 // TestLineComments, using a simple test case, checks that consecutive line 210 // comments are properly terminated with a newline even if the AST position 211 // information is incorrect. 212 // 213 func TestLineComments(t *testing.T) { 214 const src = `// comment 1 215 // comment 2 216 // comment 3 217 package main 218 ` 219 220 fset := token.NewFileSet() 221 f, err := parser.ParseFile(fset, "", src, parser.ParseComments) 222 if err != nil { 223 panic(err) // error in test 224 } 225 226 var buf bytes.Buffer 227 fset = token.NewFileSet() // use the wrong file set 228 Fprint(&buf, fset, f) 229 230 nlines := 0 231 for _, ch := range buf.Bytes() { 232 if ch == '\n' { 233 nlines++ 234 } 235 } 236 237 const expected = 3 238 if nlines < expected { 239 t.Errorf("got %d, expected %d\n", nlines, expected) 240 t.Errorf("result:\n%s", buf.Bytes()) 241 } 242 } 243 244 // Verify that the printer can be invoked during initialization. 245 func init() { 246 const name = "foobar" 247 var buf bytes.Buffer 248 if err := Fprint(&buf, fset, &ast.Ident{Name: name}); err != nil { 249 panic(err) // error in test 250 } 251 // in debug mode, the result contains additional information; 252 // ignore it 253 if s := buf.String(); !debug && s != name { 254 panic("got " + s + ", want " + name) 255 } 256 } 257 258 // Verify that the printer doesn't crash if the AST contains BadXXX nodes. 259 func TestBadNodes(t *testing.T) { 260 const src = "package p\n(" 261 const res = "package p\nBadDecl\n" 262 f, err := parser.ParseFile(fset, "", src, parser.ParseComments) 263 if err == nil { 264 t.Error("expected illegal program") // error in test 265 } 266 var buf bytes.Buffer 267 Fprint(&buf, fset, f) 268 if buf.String() != res { 269 t.Errorf("got %q, expected %q", buf.String(), res) 270 } 271 } 272 273 // testComment verifies that f can be parsed again after printing it 274 // with its first comment set to comment at any possible source offset. 275 func testComment(t *testing.T, f *ast.File, srclen int, comment *ast.Comment) { 276 f.Comments[0].List[0] = comment 277 var buf bytes.Buffer 278 for offs := 0; offs <= srclen; offs++ { 279 buf.Reset() 280 // Printing f should result in a correct program no 281 // matter what the (incorrect) comment position is. 282 if err := Fprint(&buf, fset, f); err != nil { 283 t.Error(err) 284 } 285 if _, err := parser.ParseFile(fset, "", buf.Bytes(), 0); err != nil { 286 t.Fatalf("incorrect program for pos = %d:\n%s", comment.Slash, buf.String()) 287 } 288 // Position information is just an offset. 289 // Move comment one byte down in the source. 290 comment.Slash++ 291 } 292 } 293 294 // Verify that the printer produces a correct program 295 // even if the position information of comments introducing newlines 296 // is incorrect. 297 func TestBadComments(t *testing.T) { 298 const src = ` 299 // first comment - text and position changed by test 300 package p 301 import "fmt" 302 const pi = 3.14 // rough circle 303 var ( 304 x, y, z int = 1, 2, 3 305 u, v float64 306 ) 307 func fibo(n int) { 308 if n < 2 { 309 return n /* seed values */ 310 } 311 return fibo(n-1) + fibo(n-2) 312 } 313 ` 314 315 f, err := parser.ParseFile(fset, "", src, parser.ParseComments) 316 if err != nil { 317 t.Error(err) // error in test 318 } 319 320 comment := f.Comments[0].List[0] 321 pos := comment.Pos() 322 if fset.Position(pos).Offset != 1 { 323 t.Error("expected offset 1") // error in test 324 } 325 326 testComment(t, f, len(src), &ast.Comment{Slash: pos, Text: "//-style comment"}) 327 testComment(t, f, len(src), &ast.Comment{Slash: pos, Text: "/*-style comment */"}) 328 testComment(t, f, len(src), &ast.Comment{Slash: pos, Text: "/*-style \n comment */"}) 329 testComment(t, f, len(src), &ast.Comment{Slash: pos, Text: "/*-style comment \n\n\n */"}) 330 } 331 332 type visitor chan *ast.Ident 333 334 func (v visitor) Visit(n ast.Node) (w ast.Visitor) { 335 if ident, ok := n.(*ast.Ident); ok { 336 v <- ident 337 } 338 return v 339 } 340 341 // idents is an iterator that returns all idents in f via the result channel. 342 func idents(f *ast.File) <-chan *ast.Ident { 343 v := make(visitor) 344 go func() { 345 ast.Walk(v, f) 346 close(v) 347 }() 348 return v 349 } 350 351 // identCount returns the number of identifiers found in f. 352 func identCount(f *ast.File) int { 353 n := 0 354 for range idents(f) { 355 n++ 356 } 357 return n 358 } 359 360 // Verify that the SourcePos mode emits correct //line comments 361 // by testing that position information for matching identifiers 362 // is maintained. 363 func TestSourcePos(t *testing.T) { 364 const src = ` 365 package p 366 import ( "go/printer"; "math" ) 367 const pi = 3.14; var x = 0 368 type t struct{ x, y, z int; u, v, w float32 } 369 func (t *t) foo(a, b, c int) int { 370 return a*t.x + b*t.y + 371 // two extra lines here 372 // ... 373 c*t.z 374 } 375 ` 376 377 // parse original 378 f1, err := parser.ParseFile(fset, "src", src, parser.ParseComments) 379 if err != nil { 380 t.Fatal(err) 381 } 382 383 // pretty-print original 384 var buf bytes.Buffer 385 err = (&Config{Mode: UseSpaces | SourcePos, Tabwidth: 8}).Fprint(&buf, fset, f1) 386 if err != nil { 387 t.Fatal(err) 388 } 389 390 // parse pretty printed original 391 // (//line comments must be interpreted even w/o parser.ParseComments set) 392 f2, err := parser.ParseFile(fset, "", buf.Bytes(), 0) 393 if err != nil { 394 t.Fatalf("%s\n%s", err, buf.Bytes()) 395 } 396 397 // At this point the position information of identifiers in f2 should 398 // match the position information of corresponding identifiers in f1. 399 400 // number of identifiers must be > 0 (test should run) and must match 401 n1 := identCount(f1) 402 n2 := identCount(f2) 403 if n1 == 0 { 404 t.Fatal("got no idents") 405 } 406 if n2 != n1 { 407 t.Errorf("got %d idents; want %d", n2, n1) 408 } 409 410 // verify that all identifiers have correct line information 411 i2range := idents(f2) 412 for i1 := range idents(f1) { 413 i2 := <-i2range 414 415 if i2.Name != i1.Name { 416 t.Errorf("got ident %s; want %s", i2.Name, i1.Name) 417 } 418 419 l1 := fset.Position(i1.Pos()).Line 420 l2 := fset.Position(i2.Pos()).Line 421 if l2 != l1 { 422 t.Errorf("got line %d; want %d for %s", l2, l1, i1.Name) 423 } 424 } 425 426 if t.Failed() { 427 t.Logf("\n%s", buf.Bytes()) 428 } 429 } 430 431 var decls = []string{ 432 `import "fmt"`, 433 "const pi = 3.1415\nconst e = 2.71828\n\nvar x = pi", 434 "func sum(x, y int) int\t{ return x + y }", 435 } 436 437 func TestDeclLists(t *testing.T) { 438 for _, src := range decls { 439 file, err := parser.ParseFile(fset, "", "package p;"+src, parser.ParseComments) 440 if err != nil { 441 panic(err) // error in test 442 } 443 444 var buf bytes.Buffer 445 err = Fprint(&buf, fset, file.Decls) // only print declarations 446 if err != nil { 447 panic(err) // error in test 448 } 449 450 out := buf.String() 451 if out != src { 452 t.Errorf("\ngot : %q\nwant: %q\n", out, src) 453 } 454 } 455 } 456 457 var stmts = []string{ 458 "i := 0", 459 "select {}\nvar a, b = 1, 2\nreturn a + b", 460 "go f()\ndefer func() {}()", 461 } 462 463 func TestStmtLists(t *testing.T) { 464 for _, src := range stmts { 465 file, err := parser.ParseFile(fset, "", "package p; func _() {"+src+"}", parser.ParseComments) 466 if err != nil { 467 panic(err) // error in test 468 } 469 470 var buf bytes.Buffer 471 err = Fprint(&buf, fset, file.Decls[0].(*ast.FuncDecl).Body.List) // only print statements 472 if err != nil { 473 panic(err) // error in test 474 } 475 476 out := buf.String() 477 if out != src { 478 t.Errorf("\ngot : %q\nwant: %q\n", out, src) 479 } 480 } 481 } 482 483 func TestBaseIndent(t *testing.T) { 484 // The testfile must not contain multi-line raw strings since those 485 // are not indented (because their values must not change) and make 486 // this test fail. 487 const filename = "printer.go" 488 src, err := ioutil.ReadFile(filename) 489 if err != nil { 490 panic(err) // error in test 491 } 492 493 file, err := parser.ParseFile(fset, filename, src, 0) 494 if err != nil { 495 panic(err) // error in test 496 } 497 498 var buf bytes.Buffer 499 for indent := 0; indent < 4; indent++ { 500 buf.Reset() 501 (&Config{Tabwidth: tabwidth, Indent: indent}).Fprint(&buf, fset, file) 502 // all code must be indented by at least 'indent' tabs 503 lines := bytes.Split(buf.Bytes(), []byte{'\n'}) 504 for i, line := range lines { 505 if len(line) == 0 { 506 continue // empty lines don't have indentation 507 } 508 n := 0 509 for j, b := range line { 510 if b != '\t' { 511 // end of indentation 512 n = j 513 break 514 } 515 } 516 if n < indent { 517 t.Errorf("line %d: got only %d tabs; want at least %d: %q", i, n, indent, line) 518 } 519 } 520 } 521 } 522 523 // TestFuncType tests that an ast.FuncType with a nil Params field 524 // can be printed (per go/ast specification). Test case for issue 3870. 525 func TestFuncType(t *testing.T) { 526 src := &ast.File{ 527 Name: &ast.Ident{Name: "p"}, 528 Decls: []ast.Decl{ 529 &ast.FuncDecl{ 530 Name: &ast.Ident{Name: "f"}, 531 Type: &ast.FuncType{}, 532 }, 533 }, 534 } 535 536 var buf bytes.Buffer 537 if err := Fprint(&buf, fset, src); err != nil { 538 t.Fatal(err) 539 } 540 got := buf.String() 541 542 const want = `package p 543 544 func f() 545 ` 546 547 if got != want { 548 t.Fatalf("got:\n%s\nwant:\n%s\n", got, want) 549 } 550 } 551 552 type limitWriter struct { 553 remaining int 554 errCount int 555 } 556 557 func (l *limitWriter) Write(buf []byte) (n int, err error) { 558 n = len(buf) 559 if n >= l.remaining { 560 n = l.remaining 561 err = io.EOF 562 l.errCount++ 563 } 564 l.remaining -= n 565 return n, err 566 } 567 568 // Test whether the printer stops writing after the first error 569 func TestWriteErrors(t *testing.T) { 570 const filename = "printer.go" 571 src, err := ioutil.ReadFile(filename) 572 if err != nil { 573 panic(err) // error in test 574 } 575 file, err := parser.ParseFile(fset, filename, src, 0) 576 if err != nil { 577 panic(err) // error in test 578 } 579 for i := 0; i < 20; i++ { 580 lw := &limitWriter{remaining: i} 581 err := (&Config{Mode: RawFormat}).Fprint(lw, fset, file) 582 if lw.errCount > 1 { 583 t.Fatal("Writes continued after first error returned") 584 } 585 // We expect errCount be 1 iff err is set 586 if (lw.errCount != 0) != (err != nil) { 587 t.Fatal("Expected err when errCount != 0") 588 } 589 } 590 } 591 592 // TextX is a skeleton test that can be filled in for debugging one-off cases. 593 // Do not remove. 594 func TestX(t *testing.T) { 595 const src = ` 596 package p 597 func _() {} 598 ` 599 _, err := format([]byte(src), 0) 600 if err != nil { 601 t.Error(err) 602 } 603 }