github.com/Filosottile/go@v0.0.0-20170906193555-dbed9972d994/src/cmd/cgo/ast.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 // Parse input AST and prepare Prog structure. 6 7 package main 8 9 import ( 10 "fmt" 11 "go/ast" 12 "go/parser" 13 "go/scanner" 14 "go/token" 15 "os" 16 "path/filepath" 17 "strings" 18 ) 19 20 func parse(name string, src []byte, flags parser.Mode) *ast.File { 21 ast1, err := parser.ParseFile(fset, name, src, flags) 22 if err != nil { 23 if list, ok := err.(scanner.ErrorList); ok { 24 // If err is a scanner.ErrorList, its String will print just 25 // the first error and then (+n more errors). 26 // Instead, turn it into a new Error that will return 27 // details for all the errors. 28 for _, e := range list { 29 fmt.Fprintln(os.Stderr, e) 30 } 31 os.Exit(2) 32 } 33 fatalf("parsing %s: %s", name, err) 34 } 35 return ast1 36 } 37 38 func sourceLine(n ast.Node) int { 39 return fset.Position(n.Pos()).Line 40 } 41 42 // ParseGo populates f with information learned from the Go source code 43 // which was read from the named file. It gathers the C preamble 44 // attached to the import "C" comment, a list of references to C.xxx, 45 // a list of exported functions, and the actual AST, to be rewritten and 46 // printed. 47 func (f *File) ParseGo(name string, src []byte) { 48 // Create absolute path for file, so that it will be used in error 49 // messages and recorded in debug line number information. 50 // This matches the rest of the toolchain. See golang.org/issue/5122. 51 if aname, err := filepath.Abs(name); err == nil { 52 name = aname 53 } 54 55 // Two different parses: once with comments, once without. 56 // The printer is not good enough at printing comments in the 57 // right place when we start editing the AST behind its back, 58 // so we use ast1 to look for the doc comments on import "C" 59 // and on exported functions, and we use ast2 for translating 60 // and reprinting. 61 ast1 := parse(name, src, parser.ParseComments) 62 ast2 := parse(name, src, 0) 63 64 f.Package = ast1.Name.Name 65 f.Name = make(map[string]*Name) 66 f.NamePos = make(map[*Name]token.Pos) 67 68 // In ast1, find the import "C" line and get any extra C preamble. 69 sawC := false 70 for _, decl := range ast1.Decls { 71 d, ok := decl.(*ast.GenDecl) 72 if !ok { 73 continue 74 } 75 for _, spec := range d.Specs { 76 s, ok := spec.(*ast.ImportSpec) 77 if !ok || s.Path.Value != `"C"` { 78 continue 79 } 80 sawC = true 81 if s.Name != nil { 82 error_(s.Path.Pos(), `cannot rename import "C"`) 83 } 84 cg := s.Doc 85 if cg == nil && len(d.Specs) == 1 { 86 cg = d.Doc 87 } 88 if cg != nil { 89 f.Preamble += fmt.Sprintf("#line %d %q\n", sourceLine(cg), name) 90 f.Preamble += commentText(cg) + "\n" 91 f.Preamble += "#line 1 \"cgo-generated-wrapper\"\n" 92 } 93 } 94 } 95 if !sawC { 96 error_(token.NoPos, `cannot find import "C"`) 97 } 98 99 // In ast2, strip the import "C" line. 100 w := 0 101 for _, decl := range ast2.Decls { 102 d, ok := decl.(*ast.GenDecl) 103 if !ok { 104 ast2.Decls[w] = decl 105 w++ 106 continue 107 } 108 ws := 0 109 for _, spec := range d.Specs { 110 s, ok := spec.(*ast.ImportSpec) 111 if !ok || s.Path.Value != `"C"` { 112 d.Specs[ws] = spec 113 ws++ 114 } 115 } 116 if ws == 0 { 117 continue 118 } 119 d.Specs = d.Specs[0:ws] 120 ast2.Decls[w] = d 121 w++ 122 } 123 ast2.Decls = ast2.Decls[0:w] 124 125 // Accumulate pointers to uses of C.x. 126 if f.Ref == nil { 127 f.Ref = make([]*Ref, 0, 8) 128 } 129 f.walk(ast2, "prog", (*File).saveExprs) 130 131 // Accumulate exported functions. 132 // The comments are only on ast1 but we need to 133 // save the function bodies from ast2. 134 // The first walk fills in ExpFunc, and the 135 // second walk changes the entries to 136 // refer to ast2 instead. 137 f.walk(ast1, "prog", (*File).saveExport) 138 f.walk(ast2, "prog", (*File).saveExport2) 139 140 f.Comments = ast1.Comments 141 f.AST = ast2 142 } 143 144 // Like ast.CommentGroup's Text method but preserves 145 // leading blank lines, so that line numbers line up. 146 func commentText(g *ast.CommentGroup) string { 147 if g == nil { 148 return "" 149 } 150 var pieces []string 151 for _, com := range g.List { 152 c := com.Text 153 // Remove comment markers. 154 // The parser has given us exactly the comment text. 155 switch c[1] { 156 case '/': 157 //-style comment (no newline at the end) 158 c = c[2:] + "\n" 159 case '*': 160 /*-style comment */ 161 c = c[2 : len(c)-2] 162 } 163 pieces = append(pieces, c) 164 } 165 return strings.Join(pieces, "") 166 } 167 168 // Save various references we are going to need later. 169 func (f *File) saveExprs(x interface{}, context string) { 170 switch x := x.(type) { 171 case *ast.Expr: 172 switch (*x).(type) { 173 case *ast.SelectorExpr: 174 f.saveRef(x, context) 175 } 176 case *ast.CallExpr: 177 f.saveCall(x, context) 178 } 179 } 180 181 // Save references to C.xxx for later processing. 182 func (f *File) saveRef(n *ast.Expr, context string) { 183 sel := (*n).(*ast.SelectorExpr) 184 // For now, assume that the only instance of capital C is when 185 // used as the imported package identifier. 186 // The parser should take care of scoping in the future, so 187 // that we will be able to distinguish a "top-level C" from a 188 // local C. 189 if l, ok := sel.X.(*ast.Ident); !ok || l.Name != "C" { 190 return 191 } 192 if context == "as2" { 193 context = "expr" 194 } 195 if context == "embed-type" { 196 error_(sel.Pos(), "cannot embed C type") 197 } 198 goname := sel.Sel.Name 199 if goname == "errno" { 200 error_(sel.Pos(), "cannot refer to errno directly; see documentation") 201 return 202 } 203 if goname == "_CMalloc" { 204 error_(sel.Pos(), "cannot refer to C._CMalloc; use C.malloc") 205 return 206 } 207 if goname == "malloc" { 208 goname = "_CMalloc" 209 } 210 name := f.Name[goname] 211 if name == nil { 212 name = &Name{ 213 Go: goname, 214 } 215 f.Name[goname] = name 216 f.NamePos[name] = sel.Pos() 217 } 218 f.Ref = append(f.Ref, &Ref{ 219 Name: name, 220 Expr: n, 221 Context: context, 222 }) 223 } 224 225 // Save calls to C.xxx for later processing. 226 func (f *File) saveCall(call *ast.CallExpr, context string) { 227 sel, ok := call.Fun.(*ast.SelectorExpr) 228 if !ok { 229 return 230 } 231 if l, ok := sel.X.(*ast.Ident); !ok || l.Name != "C" { 232 return 233 } 234 c := &Call{Call: call, Deferred: context == "defer"} 235 f.Calls = append(f.Calls, c) 236 } 237 238 // If a function should be exported add it to ExpFunc. 239 func (f *File) saveExport(x interface{}, context string) { 240 n, ok := x.(*ast.FuncDecl) 241 if !ok { 242 return 243 } 244 245 if n.Doc == nil { 246 return 247 } 248 for _, c := range n.Doc.List { 249 if !strings.HasPrefix(c.Text, "//export ") { 250 continue 251 } 252 253 name := strings.TrimSpace(c.Text[9:]) 254 if name == "" { 255 error_(c.Pos(), "export missing name") 256 } 257 258 if name != n.Name.Name { 259 error_(c.Pos(), "export comment has wrong name %q, want %q", name, n.Name.Name) 260 } 261 262 doc := "" 263 for _, c1 := range n.Doc.List { 264 if c1 != c { 265 doc += c1.Text + "\n" 266 } 267 } 268 269 f.ExpFunc = append(f.ExpFunc, &ExpFunc{ 270 Func: n, 271 ExpName: name, 272 Doc: doc, 273 }) 274 break 275 } 276 } 277 278 // Make f.ExpFunc[i] point at the Func from this AST instead of the other one. 279 func (f *File) saveExport2(x interface{}, context string) { 280 n, ok := x.(*ast.FuncDecl) 281 if !ok { 282 return 283 } 284 285 for _, exp := range f.ExpFunc { 286 if exp.Func.Name.Name == n.Name.Name { 287 exp.Func = n 288 break 289 } 290 } 291 } 292 293 // walk walks the AST x, calling visit(f, x, context) for each node. 294 func (f *File) walk(x interface{}, context string, visit func(*File, interface{}, string)) { 295 visit(f, x, context) 296 switch n := x.(type) { 297 case *ast.Expr: 298 f.walk(*n, context, visit) 299 300 // everything else just recurs 301 default: 302 error_(token.NoPos, "unexpected type %T in walk", x) 303 panic("unexpected type") 304 305 case nil: 306 307 // These are ordered and grouped to match ../../go/ast/ast.go 308 case *ast.Field: 309 if len(n.Names) == 0 && context == "field" { 310 f.walk(&n.Type, "embed-type", visit) 311 } else { 312 f.walk(&n.Type, "type", visit) 313 } 314 case *ast.FieldList: 315 for _, field := range n.List { 316 f.walk(field, context, visit) 317 } 318 case *ast.BadExpr: 319 case *ast.Ident: 320 case *ast.Ellipsis: 321 case *ast.BasicLit: 322 case *ast.FuncLit: 323 f.walk(n.Type, "type", visit) 324 f.walk(n.Body, "stmt", visit) 325 case *ast.CompositeLit: 326 f.walk(&n.Type, "type", visit) 327 f.walk(n.Elts, "expr", visit) 328 case *ast.ParenExpr: 329 f.walk(&n.X, context, visit) 330 case *ast.SelectorExpr: 331 f.walk(&n.X, "selector", visit) 332 case *ast.IndexExpr: 333 f.walk(&n.X, "expr", visit) 334 f.walk(&n.Index, "expr", visit) 335 case *ast.SliceExpr: 336 f.walk(&n.X, "expr", visit) 337 if n.Low != nil { 338 f.walk(&n.Low, "expr", visit) 339 } 340 if n.High != nil { 341 f.walk(&n.High, "expr", visit) 342 } 343 if n.Max != nil { 344 f.walk(&n.Max, "expr", visit) 345 } 346 case *ast.TypeAssertExpr: 347 f.walk(&n.X, "expr", visit) 348 f.walk(&n.Type, "type", visit) 349 case *ast.CallExpr: 350 if context == "as2" { 351 f.walk(&n.Fun, "call2", visit) 352 } else { 353 f.walk(&n.Fun, "call", visit) 354 } 355 f.walk(n.Args, "expr", visit) 356 case *ast.StarExpr: 357 f.walk(&n.X, context, visit) 358 case *ast.UnaryExpr: 359 f.walk(&n.X, "expr", visit) 360 case *ast.BinaryExpr: 361 f.walk(&n.X, "expr", visit) 362 f.walk(&n.Y, "expr", visit) 363 case *ast.KeyValueExpr: 364 f.walk(&n.Key, "expr", visit) 365 f.walk(&n.Value, "expr", visit) 366 367 case *ast.ArrayType: 368 f.walk(&n.Len, "expr", visit) 369 f.walk(&n.Elt, "type", visit) 370 case *ast.StructType: 371 f.walk(n.Fields, "field", visit) 372 case *ast.FuncType: 373 f.walk(n.Params, "param", visit) 374 if n.Results != nil { 375 f.walk(n.Results, "param", visit) 376 } 377 case *ast.InterfaceType: 378 f.walk(n.Methods, "field", visit) 379 case *ast.MapType: 380 f.walk(&n.Key, "type", visit) 381 f.walk(&n.Value, "type", visit) 382 case *ast.ChanType: 383 f.walk(&n.Value, "type", visit) 384 385 case *ast.BadStmt: 386 case *ast.DeclStmt: 387 f.walk(n.Decl, "decl", visit) 388 case *ast.EmptyStmt: 389 case *ast.LabeledStmt: 390 f.walk(n.Stmt, "stmt", visit) 391 case *ast.ExprStmt: 392 f.walk(&n.X, "expr", visit) 393 case *ast.SendStmt: 394 f.walk(&n.Chan, "expr", visit) 395 f.walk(&n.Value, "expr", visit) 396 case *ast.IncDecStmt: 397 f.walk(&n.X, "expr", visit) 398 case *ast.AssignStmt: 399 f.walk(n.Lhs, "expr", visit) 400 if len(n.Lhs) == 2 && len(n.Rhs) == 1 { 401 f.walk(n.Rhs, "as2", visit) 402 } else { 403 f.walk(n.Rhs, "expr", visit) 404 } 405 case *ast.GoStmt: 406 f.walk(n.Call, "expr", visit) 407 case *ast.DeferStmt: 408 f.walk(n.Call, "defer", visit) 409 case *ast.ReturnStmt: 410 f.walk(n.Results, "expr", visit) 411 case *ast.BranchStmt: 412 case *ast.BlockStmt: 413 f.walk(n.List, context, visit) 414 case *ast.IfStmt: 415 f.walk(n.Init, "stmt", visit) 416 f.walk(&n.Cond, "expr", visit) 417 f.walk(n.Body, "stmt", visit) 418 f.walk(n.Else, "stmt", visit) 419 case *ast.CaseClause: 420 if context == "typeswitch" { 421 context = "type" 422 } else { 423 context = "expr" 424 } 425 f.walk(n.List, context, visit) 426 f.walk(n.Body, "stmt", visit) 427 case *ast.SwitchStmt: 428 f.walk(n.Init, "stmt", visit) 429 f.walk(&n.Tag, "expr", visit) 430 f.walk(n.Body, "switch", visit) 431 case *ast.TypeSwitchStmt: 432 f.walk(n.Init, "stmt", visit) 433 f.walk(n.Assign, "stmt", visit) 434 f.walk(n.Body, "typeswitch", visit) 435 case *ast.CommClause: 436 f.walk(n.Comm, "stmt", visit) 437 f.walk(n.Body, "stmt", visit) 438 case *ast.SelectStmt: 439 f.walk(n.Body, "stmt", visit) 440 case *ast.ForStmt: 441 f.walk(n.Init, "stmt", visit) 442 f.walk(&n.Cond, "expr", visit) 443 f.walk(n.Post, "stmt", visit) 444 f.walk(n.Body, "stmt", visit) 445 case *ast.RangeStmt: 446 f.walk(&n.Key, "expr", visit) 447 f.walk(&n.Value, "expr", visit) 448 f.walk(&n.X, "expr", visit) 449 f.walk(n.Body, "stmt", visit) 450 451 case *ast.ImportSpec: 452 case *ast.ValueSpec: 453 f.walk(&n.Type, "type", visit) 454 if len(n.Names) == 2 && len(n.Values) == 1 { 455 f.walk(&n.Values[0], "as2", visit) 456 } else { 457 f.walk(n.Values, "expr", visit) 458 } 459 case *ast.TypeSpec: 460 f.walk(&n.Type, "type", visit) 461 462 case *ast.BadDecl: 463 case *ast.GenDecl: 464 f.walk(n.Specs, "spec", visit) 465 case *ast.FuncDecl: 466 if n.Recv != nil { 467 f.walk(n.Recv, "param", visit) 468 } 469 f.walk(n.Type, "type", visit) 470 if n.Body != nil { 471 f.walk(n.Body, "stmt", visit) 472 } 473 474 case *ast.File: 475 f.walk(n.Decls, "decl", visit) 476 477 case *ast.Package: 478 for _, file := range n.Files { 479 f.walk(file, "file", visit) 480 } 481 482 case []ast.Decl: 483 for _, d := range n { 484 f.walk(d, context, visit) 485 } 486 case []ast.Expr: 487 for i := range n { 488 f.walk(&n[i], context, visit) 489 } 490 case []ast.Stmt: 491 for _, s := range n { 492 f.walk(s, context, visit) 493 } 494 case []ast.Spec: 495 for _, s := range n { 496 f.walk(s, context, visit) 497 } 498 } 499 }