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