github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/src/go/doc/example.go (about) 1 // Copyright 2011 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 // Extract example functions from file ASTs. 6 7 package doc 8 9 import ( 10 "go/ast" 11 "go/token" 12 "path" 13 "regexp" 14 "sort" 15 "strconv" 16 "strings" 17 "unicode" 18 "unicode/utf8" 19 ) 20 21 // An Example represents an example function found in a source files. 22 type Example struct { 23 Name string // name of the item being exemplified 24 Doc string // example function doc string 25 Code ast.Node 26 Play *ast.File // a whole program version of the example 27 Comments []*ast.CommentGroup 28 Output string // expected output 29 Unordered bool 30 EmptyOutput bool // expect empty output 31 Order int // original source code order 32 } 33 34 // Examples returns the examples found in the files, sorted by Name field. 35 // The Order fields record the order in which the examples were encountered. 36 // 37 // Playable Examples must be in a package whose name ends in "_test". 38 // An Example is "playable" (the Play field is non-nil) in either of these 39 // circumstances: 40 // - The example function is self-contained: the function references only 41 // identifiers from other packages (or predeclared identifiers, such as 42 // "int") and the test file does not include a dot import. 43 // - The entire test file is the example: the file contains exactly one 44 // example function, zero test or benchmark functions, and at least one 45 // top-level function, type, variable, or constant declaration other 46 // than the example function. 47 func Examples(files ...*ast.File) []*Example { 48 var list []*Example 49 for _, file := range files { 50 hasTests := false // file contains tests or benchmarks 51 numDecl := 0 // number of non-import declarations in the file 52 var flist []*Example 53 for _, decl := range file.Decls { 54 if g, ok := decl.(*ast.GenDecl); ok && g.Tok != token.IMPORT { 55 numDecl++ 56 continue 57 } 58 f, ok := decl.(*ast.FuncDecl) 59 if !ok || f.Recv != nil { 60 continue 61 } 62 numDecl++ 63 name := f.Name.Name 64 if isTest(name, "Test") || isTest(name, "Benchmark") { 65 hasTests = true 66 continue 67 } 68 if !isTest(name, "Example") { 69 continue 70 } 71 if f.Body == nil { // ast.File.Body nil dereference (see issue 28044) 72 continue 73 } 74 var doc string 75 if f.Doc != nil { 76 doc = f.Doc.Text() 77 } 78 output, unordered, hasOutput := exampleOutput(f.Body, file.Comments) 79 flist = append(flist, &Example{ 80 Name: name[len("Example"):], 81 Doc: doc, 82 Code: f.Body, 83 Play: playExample(file, f), 84 Comments: file.Comments, 85 Output: output, 86 Unordered: unordered, 87 EmptyOutput: output == "" && hasOutput, 88 Order: len(flist), 89 }) 90 } 91 if !hasTests && numDecl > 1 && len(flist) == 1 { 92 // If this file only has one example function, some 93 // other top-level declarations, and no tests or 94 // benchmarks, use the whole file as the example. 95 flist[0].Code = file 96 flist[0].Play = playExampleFile(file) 97 } 98 list = append(list, flist...) 99 } 100 // sort by name 101 sort.Slice(list, func(i, j int) bool { 102 return list[i].Name < list[j].Name 103 }) 104 return list 105 } 106 107 var outputPrefix = regexp.MustCompile(`(?i)^[[:space:]]*(unordered )?output:`) 108 109 // Extracts the expected output and whether there was a valid output comment 110 func exampleOutput(b *ast.BlockStmt, comments []*ast.CommentGroup) (output string, unordered, ok bool) { 111 if _, last := lastComment(b, comments); last != nil { 112 // test that it begins with the correct prefix 113 text := last.Text() 114 if loc := outputPrefix.FindStringSubmatchIndex(text); loc != nil { 115 if loc[2] != -1 { 116 unordered = true 117 } 118 text = text[loc[1]:] 119 // Strip zero or more spaces followed by \n or a single space. 120 text = strings.TrimLeft(text, " ") 121 if len(text) > 0 && text[0] == '\n' { 122 text = text[1:] 123 } 124 return text, unordered, true 125 } 126 } 127 return "", false, false // no suitable comment found 128 } 129 130 // isTest tells whether name looks like a test, example, or benchmark. 131 // It is a Test (say) if there is a character after Test that is not a 132 // lower-case letter. (We don't want Testiness.) 133 func isTest(name, prefix string) bool { 134 if !strings.HasPrefix(name, prefix) { 135 return false 136 } 137 if len(name) == len(prefix) { // "Test" is ok 138 return true 139 } 140 rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) 141 return !unicode.IsLower(rune) 142 } 143 144 // playExample synthesizes a new *ast.File based on the provided 145 // file with the provided function body as the body of main. 146 func playExample(file *ast.File, f *ast.FuncDecl) *ast.File { 147 body := f.Body 148 149 if !strings.HasSuffix(file.Name.Name, "_test") { 150 // We don't support examples that are part of the 151 // greater package (yet). 152 return nil 153 } 154 155 // Collect top-level declarations in the file. 156 topDecls := make(map[*ast.Object]ast.Decl) 157 typMethods := make(map[string][]ast.Decl) 158 159 for _, decl := range file.Decls { 160 switch d := decl.(type) { 161 case *ast.FuncDecl: 162 if d.Recv == nil { 163 topDecls[d.Name.Obj] = d 164 } else { 165 if len(d.Recv.List) == 1 { 166 t := d.Recv.List[0].Type 167 tname, _ := baseTypeName(t) 168 typMethods[tname] = append(typMethods[tname], d) 169 } 170 } 171 case *ast.GenDecl: 172 for _, spec := range d.Specs { 173 switch s := spec.(type) { 174 case *ast.TypeSpec: 175 topDecls[s.Name.Obj] = d 176 case *ast.ValueSpec: 177 for _, name := range s.Names { 178 topDecls[name.Obj] = d 179 } 180 } 181 } 182 } 183 } 184 185 // Find unresolved identifiers and uses of top-level declarations. 186 unresolved := make(map[string]bool) 187 var depDecls []ast.Decl 188 hasDepDecls := make(map[ast.Decl]bool) 189 190 var inspectFunc func(ast.Node) bool 191 inspectFunc = func(n ast.Node) bool { 192 switch e := n.(type) { 193 case *ast.Ident: 194 if e.Obj == nil && e.Name != "_" { 195 unresolved[e.Name] = true 196 } else if d := topDecls[e.Obj]; d != nil { 197 if !hasDepDecls[d] { 198 hasDepDecls[d] = true 199 depDecls = append(depDecls, d) 200 } 201 } 202 return true 203 case *ast.SelectorExpr: 204 // For selector expressions, only inspect the left hand side. 205 // (For an expression like fmt.Println, only add "fmt" to the 206 // set of unresolved names, not "Println".) 207 ast.Inspect(e.X, inspectFunc) 208 return false 209 case *ast.KeyValueExpr: 210 // For key value expressions, only inspect the value 211 // as the key should be resolved by the type of the 212 // composite literal. 213 ast.Inspect(e.Value, inspectFunc) 214 return false 215 } 216 return true 217 } 218 ast.Inspect(body, inspectFunc) 219 for i := 0; i < len(depDecls); i++ { 220 switch d := depDecls[i].(type) { 221 case *ast.FuncDecl: 222 ast.Inspect(d.Body, inspectFunc) 223 case *ast.GenDecl: 224 for _, spec := range d.Specs { 225 switch s := spec.(type) { 226 case *ast.TypeSpec: 227 ast.Inspect(s.Type, inspectFunc) 228 229 depDecls = append(depDecls, typMethods[s.Name.Name]...) 230 case *ast.ValueSpec: 231 if s.Type != nil { 232 ast.Inspect(s.Type, inspectFunc) 233 } 234 for _, val := range s.Values { 235 ast.Inspect(val, inspectFunc) 236 } 237 } 238 } 239 } 240 } 241 242 // Remove predeclared identifiers from unresolved list. 243 for n := range unresolved { 244 if predeclaredTypes[n] || predeclaredConstants[n] || predeclaredFuncs[n] { 245 delete(unresolved, n) 246 } 247 } 248 249 // Use unresolved identifiers to determine the imports used by this 250 // example. The heuristic assumes package names match base import 251 // paths for imports w/o renames (should be good enough most of the time). 252 namedImports := make(map[string]string) // [name]path 253 var blankImports []ast.Spec // _ imports 254 for _, s := range file.Imports { 255 p, err := strconv.Unquote(s.Path.Value) 256 if err != nil { 257 continue 258 } 259 n := path.Base(p) 260 if s.Name != nil { 261 n = s.Name.Name 262 switch n { 263 case "_": 264 blankImports = append(blankImports, s) 265 continue 266 case ".": 267 // We can't resolve dot imports (yet). 268 return nil 269 } 270 } 271 if unresolved[n] { 272 namedImports[n] = p 273 delete(unresolved, n) 274 } 275 } 276 277 // If there are other unresolved identifiers, give up because this 278 // synthesized file is not going to build. 279 if len(unresolved) > 0 { 280 return nil 281 } 282 283 // Include documentation belonging to blank imports. 284 var comments []*ast.CommentGroup 285 for _, s := range blankImports { 286 if c := s.(*ast.ImportSpec).Doc; c != nil { 287 comments = append(comments, c) 288 } 289 } 290 291 // Include comments that are inside the function body. 292 for _, c := range file.Comments { 293 if body.Pos() <= c.Pos() && c.End() <= body.End() { 294 comments = append(comments, c) 295 } 296 } 297 298 // Strip the "Output:" or "Unordered output:" comment and adjust body 299 // end position. 300 body, comments = stripOutputComment(body, comments) 301 302 // Include documentation belonging to dependent declarations. 303 for _, d := range depDecls { 304 switch d := d.(type) { 305 case *ast.GenDecl: 306 if d.Doc != nil { 307 comments = append(comments, d.Doc) 308 } 309 case *ast.FuncDecl: 310 if d.Doc != nil { 311 comments = append(comments, d.Doc) 312 } 313 } 314 } 315 316 // Synthesize import declaration. 317 importDecl := &ast.GenDecl{ 318 Tok: token.IMPORT, 319 Lparen: 1, // Need non-zero Lparen and Rparen so that printer 320 Rparen: 1, // treats this as a factored import. 321 } 322 for n, p := range namedImports { 323 s := &ast.ImportSpec{Path: &ast.BasicLit{Value: strconv.Quote(p)}} 324 if path.Base(p) != n { 325 s.Name = ast.NewIdent(n) 326 } 327 importDecl.Specs = append(importDecl.Specs, s) 328 } 329 importDecl.Specs = append(importDecl.Specs, blankImports...) 330 331 // Synthesize main function. 332 funcDecl := &ast.FuncDecl{ 333 Name: ast.NewIdent("main"), 334 Type: f.Type, 335 Body: body, 336 } 337 338 decls := make([]ast.Decl, 0, 2+len(depDecls)) 339 decls = append(decls, importDecl) 340 decls = append(decls, depDecls...) 341 decls = append(decls, funcDecl) 342 343 sort.Slice(decls, func(i, j int) bool { 344 return decls[i].Pos() < decls[j].Pos() 345 }) 346 347 sort.Slice(comments, func(i, j int) bool { 348 return comments[i].Pos() < comments[j].Pos() 349 }) 350 351 // Synthesize file. 352 return &ast.File{ 353 Name: ast.NewIdent("main"), 354 Decls: decls, 355 Comments: comments, 356 } 357 } 358 359 // playExampleFile takes a whole file example and synthesizes a new *ast.File 360 // such that the example is function main in package main. 361 func playExampleFile(file *ast.File) *ast.File { 362 // Strip copyright comment if present. 363 comments := file.Comments 364 if len(comments) > 0 && strings.HasPrefix(comments[0].Text(), "Copyright") { 365 comments = comments[1:] 366 } 367 368 // Copy declaration slice, rewriting the ExampleX function to main. 369 var decls []ast.Decl 370 for _, d := range file.Decls { 371 if f, ok := d.(*ast.FuncDecl); ok && isTest(f.Name.Name, "Example") { 372 // Copy the FuncDecl, as it may be used elsewhere. 373 newF := *f 374 newF.Name = ast.NewIdent("main") 375 newF.Body, comments = stripOutputComment(f.Body, comments) 376 d = &newF 377 } 378 decls = append(decls, d) 379 } 380 381 // Copy the File, as it may be used elsewhere. 382 f := *file 383 f.Name = ast.NewIdent("main") 384 f.Decls = decls 385 f.Comments = comments 386 return &f 387 } 388 389 // stripOutputComment finds and removes the "Output:" or "Unordered output:" 390 // comment from body and comments, and adjusts the body block's end position. 391 func stripOutputComment(body *ast.BlockStmt, comments []*ast.CommentGroup) (*ast.BlockStmt, []*ast.CommentGroup) { 392 // Do nothing if there is no "Output:" or "Unordered output:" comment. 393 i, last := lastComment(body, comments) 394 if last == nil || !outputPrefix.MatchString(last.Text()) { 395 return body, comments 396 } 397 398 // Copy body and comments, as the originals may be used elsewhere. 399 newBody := &ast.BlockStmt{ 400 Lbrace: body.Lbrace, 401 List: body.List, 402 Rbrace: last.Pos(), 403 } 404 newComments := make([]*ast.CommentGroup, len(comments)-1) 405 copy(newComments, comments[:i]) 406 copy(newComments[i:], comments[i+1:]) 407 return newBody, newComments 408 } 409 410 // lastComment returns the last comment inside the provided block. 411 func lastComment(b *ast.BlockStmt, c []*ast.CommentGroup) (i int, last *ast.CommentGroup) { 412 pos, end := b.Pos(), b.End() 413 for j, cg := range c { 414 if cg.Pos() < pos { 415 continue 416 } 417 if cg.End() > end { 418 break 419 } 420 i, last = j, cg 421 } 422 return 423 }