Source file
src/cmd/cgo/genbinding.go
1
2
3
4
5 package main
6
7 import (
8 "bytes"
9 "fmt"
10 "go/ast"
11 "go/format"
12 "go/parser"
13 "go/token"
14 "io"
15 "maps"
16 "slices"
17 "strconv"
18 "strings"
19 )
20
21
22 type genBindingFile struct {
23 src []byte
24 srcDir string
25 ast *ast.File
26 pragmas []cgoPragma
27
28
29 importsC bool
30
31
32
33 userDecls map[string]string
34 userPos map[string]token.Pos
35 valueRecv map[string]bool
36 }
37
38
39
40
41 func isAnonCtype(name string) bool {
42 for _, prefix := range []string{"_Ctype_struct___", "_Ctype_union___", "_Ctype_class___"} {
43 if n, ok := strings.CutPrefix(name, prefix); ok && n != "" && strings.Trim(n, "0123456789") == "" {
44 return true
45 }
46 }
47 return false
48 }
49
50 func exprUsesIdent(expr ast.Expr, name string) bool {
51 found := false
52 ast.Inspect(expr, func(n ast.Node) bool {
53 if found {
54 return false
55 }
56 if id, ok := n.(*ast.Ident); ok && id.Name == name {
57 found = true
58 return false
59 }
60 return true
61 })
62 return found
63 }
64
65
66
67
68 func genBindingImportsC(input string, src []byte) bool {
69 file, err := parser.ParseFile(token.NewFileSet(), input, src, parser.ImportsOnly)
70 return err != nil || hasImportCFile(file)
71 }
72
73
74
75
76
77
78 func (f *File) useGenBindingPragmas(input, origDir string, src []byte) {
79 file, err := parser.ParseFile(fset, input, src, parser.SkipObjectResolution|parser.ParseComments)
80 if err != nil {
81 fatalf("%s", err)
82 }
83 g := &genBindingFile{
84 src: src,
85 srcDir: origDir,
86 ast: file,
87 pragmas: parseCgoPragmas(fset, file),
88 importsC: hasImportCFile(file),
89 userDecls: make(map[string]string),
90 userPos: make(map[string]token.Pos),
91 valueRecv: make(map[string]bool),
92 }
93 f.gen = g
94
95 text := func(n ast.Node) string {
96 return string(src[fset.Position(n.Pos()).Offset:fset.Position(n.End()).Offset])
97 }
98
99
100 withDoc := func(doc *ast.CommentGroup, decl string) string {
101 if doc == nil {
102 return decl
103 }
104 var b strings.Builder
105 for _, c := range doc.List {
106 if !isCgoPragmaComment(c.Text) {
107 b.WriteString(c.Text + "\n")
108 }
109 }
110 return b.String() + decl
111 }
112 declare := func(name, decl string, pos token.Pos) {
113 g.userDecls[name] = decl
114 g.userPos[name] = pos
115 }
116 for _, decl := range file.Decls {
117 switch d := decl.(type) {
118 case *ast.FuncDecl:
119 name := d.Name.Name
120 if d.Recv != nil {
121
122 if len(d.Recv.List) != 1 {
123 continue
124 }
125 recv := d.Recv.List[0].Type
126 star, isPtr := recv.(*ast.StarExpr)
127 if isPtr {
128 recv = star.X
129 }
130 id, ok := recv.(*ast.Ident)
131 if !ok {
132 continue
133 }
134 name = id.Name + "." + name
135 g.valueRecv[name] = !isPtr
136 }
137 if d.Body != nil {
138 declare(name, "", d.Pos())
139 } else {
140 declare(name, withDoc(d.Doc, text(d)), d.Pos())
141 }
142 case *ast.GenDecl:
143 for _, spec := range d.Specs {
144 var doc *ast.CommentGroup
145 if !d.Lparen.IsValid() {
146 doc = d.Doc
147 }
148 switch s := spec.(type) {
149 case *ast.TypeSpec:
150 if s.Doc != nil {
151 doc = s.Doc
152 }
153 declare(s.Name.Name, withDoc(doc, "type "+text(s)), s.Pos())
154 case *ast.ValueSpec:
155 if s.Doc != nil {
156 doc = s.Doc
157 }
158 invalidConst := d.Tok == token.CONST && (len(s.Values) == 0 || slices.ContainsFunc(s.Values, func(e ast.Expr) bool { return exprUsesIdent(e, "iota") }))
159 for _, id := range s.Names {
160 if len(s.Names) != 1 || invalidConst {
161 declare(id.Name, "", s.Pos())
162 } else {
163 declare(id.Name, withDoc(doc, d.Tok.String()+" "+text(s)), s.Pos())
164 }
165 }
166 }
167 }
168 }
169 }
170
171 f.Ref = nil
172 f.Calls = nil
173 f.Name = make(map[string]*Name)
174 f.NamePos = make(map[*Name]token.Pos)
175 for _, pr := range g.pragmas {
176 if pr.Kind == "dynload" {
177 continue
178 }
179 if f.Name[pr.CName] == nil {
180 n := &Name{Go: pr.CName, C: cname(pr.CName)}
181 f.Name[pr.CName] = n
182 f.NamePos[n] = pr.TokPos
183 }
184 }
185 }
186
187
188
189
190
191 func (p *Package) writeBinding(w io.Writer) {
192
193 pkgName := p.genFiles[0].gen.ast.Name
194
195
196
197
198 var allPragmas []cgoPragma
199 userDecls := make(map[string]string)
200 userPos := make(map[string]token.Pos)
201 valueRecv := make(map[string]bool)
202 declaredTwice := make(map[string]bool)
203 otherDecls := make(map[string]bool)
204 for _, f := range p.genFiles {
205 g := f.gen
206 if g.ast.Name.Name != pkgName.Name {
207 error_(g.ast.Name.Pos(), "-gen-binding: package %s; expected package %s", g.ast.Name.Name, pkgName.Name)
208 }
209 allPragmas = append(allPragmas, g.pragmas...)
210 for name, decl := range g.userDecls {
211 if _, ok := userDecls[name]; ok {
212 declaredTwice[name] = true
213 }
214 userDecls[name] = decl
215 userPos[name] = g.userPos[name]
216 valueRecv[name] = g.valueRecv[name]
217 otherDecls[name] = !g.importsC
218 }
219 }
220
221 declKey := func(pr cgoPragma) string {
222 if pr.RecvType != "" {
223 return pr.RecvType + "." + pr.GoName
224 }
225 return pr.GoName
226 }
227
228
229
230
231 dynloadTypes := make(map[string]bool)
232 for _, pr := range allPragmas {
233 if pr.Kind == "dynload" {
234 dynloadTypes[pr.GoName] = true
235 }
236 }
237 boundGo := make(map[string]bool)
238 boundC := make(map[string]bool)
239 for _, pr := range allPragmas {
240 key := declKey(pr)
241 if pr.RecvType != "" && !dynloadTypes[pr.RecvType] {
242 error_(pr.TokPos, "//cgo:%s %s: %s is not declared with //cgo:dynload", pr.Kind, key, pr.RecvType)
243 }
244 if pr.BindC {
245 if boundC[pr.CName] {
246 error_(pr.TokPos, "C.%s is bound by more than one //cgo: pragma", pr.CName)
247 }
248 boundC[pr.CName] = true
249 }
250 if boundGo[key] {
251 error_(pr.TokPos, "%s is bound by more than one //cgo: pragma", key)
252 continue
253 }
254 boundGo[key] = true
255 if declaredTwice[key] {
256 error_(userPos[key], "-gen-binding: %s is declared more than once", key)
257 } else if decl, ok := userDecls[key]; ok && decl == "" {
258 error_(userPos[key], "-gen-binding: %s must be declared on its own (without a body, iota, or omitted const value), or not at all", key)
259 } else if ok && valueRecv[key] {
260 error_(userPos[key], "-gen-binding: //cgo:%s method %s must have a pointer receiver (*%s)", pr.Kind, pr.GoName, pr.RecvType)
261 }
262 }
263 if nerrors > 0 {
264 return
265 }
266
267
268 for _, pr := range allPragmas {
269 if pr.Kind == "dynload" {
270 continue
271 }
272 n := p.Name[pr.CName]
273 var ok bool
274 var want string
275 switch pr.Kind {
276 case "func":
277 ok, want = n != nil && n.FuncType != nil, "function"
278 case "var":
279 ok, want = n != nil && n.IsVar(), "variable"
280 case "type":
281 ok, want = n != nil && n.Kind == "type", "type"
282 case "const":
283 ok, want = n != nil && n.IsConst() && n.Const != "", "constant"
284 }
285 if !ok {
286 kind := "not declared"
287 if n != nil && n.Kind != "" {
288 kind = "a " + n.Kind
289 }
290 error_(pr.TokPos, "//cgo:%s %s: C.%s is %s, not a %s", pr.Kind, declKey(pr), pr.CName, kind, want)
291 }
292 }
293 if nerrors > 0 {
294 return
295 }
296
297
298
299 anonToName := make(map[string]string)
300 for _, name := range slices.Sorted(maps.Keys(typedef)) {
301 def := typedef[name]
302 if isAnonCtype(name) {
303 continue
304 }
305 if id, ok := def.Go.(*ast.Ident); ok && isAnonCtype(id.Name) {
306 if _, exists := anonToName[id.Name]; !exists {
307 anonToName[id.Name] = strings.TrimPrefix(name, "_Ctype_")
308 }
309 }
310 }
311
312
313
314 typeToGoName := make(map[string]string)
315 usedGoNames := make(map[string]bool)
316 for name, other := range otherDecls {
317 if other && !strings.Contains(name, ".") {
318 usedGoNames[name] = true
319 }
320 }
321 pragmaType := make(map[string]bool)
322 for _, pr := range allPragmas {
323 if pr.RecvType == "" {
324 usedGoNames[pr.GoName] = true
325 }
326 if pr.Kind != "type" {
327 continue
328 }
329 if id, ok := p.Name[pr.CName].Type.Go.(*ast.Ident); ok {
330 names := []string{id.Name}
331 if typedefName, ok := anonToName[id.Name]; ok {
332 names = append(names, "_Ctype_"+typedefName)
333 }
334 for _, name := range names {
335 typeToGoName[name] = pr.GoName
336 typeToGoName[strings.TrimPrefix(name, "_Ctype_")] = pr.GoName
337 pragmaType[name] = true
338 }
339 }
340 }
341 cOrdinaryNames := make(map[string]bool)
342 for _, key := range nameKeys(p.Name) {
343 n := p.Name[key]
344 if n.FuncType != nil || n.IsVar() || n.Const != "" {
345 cOrdinaryNames[n.C] = true
346 }
347 }
348 var typeKeys []string
349 for name := range typedef {
350 if _, ok := primitiveCtypeToGo(name); ok || pragmaType[name] {
351 continue
352 }
353 if isAnonCtype(name) {
354
355
356 continue
357 }
358 typeKeys = append(typeKeys, name)
359 }
360 slices.Sort(typeKeys)
361 for _, name := range typeKeys {
362 cleanName := strings.TrimPrefix(name, "_Ctype_")
363 goName := "_" + cleanName
364 if tag, ok := strings.CutPrefix(cleanName, "struct_"); ok {
365 if typedef["_Ctype_"+tag] == nil && !cOrdinaryNames[tag] && !usedGoNames["_"+tag] {
366 goName = "_" + tag
367 }
368 }
369 for usedGoNames[goName] {
370 goName += "_"
371 }
372 usedGoNames[goName] = true
373 typeToGoName[name] = goName
374 typeToGoName[cleanName] = goName
375 }
376 goType := func(expr ast.Expr) string {
377 return p.formatGoBindingTypeExpr(expr, anonToName, typeToGoName)
378 }
379
380
381
382 typeDecl := func(goName, name string) string {
383 def := typedef[name]
384 if def == nil {
385 if prim, ok := primitiveCtypeToGo(name); ok {
386 return fmt.Sprintf("type %s = %s", goName, prim)
387 }
388 return fmt.Sprintf("type %s = %s", goName, name)
389 }
390 actualDef := def.Go
391 isAlias := false
392 if id, ok := actualDef.(*ast.Ident); ok {
393 if targetDef, ok := typedef[id.Name]; ok && isAnonCtype(id.Name) {
394 actualDef = targetDef.Go
395 } else if strings.HasPrefix(id.Name, "_Ctype_") && !isAnonCtype(id.Name) {
396 isAlias = true
397 }
398 }
399 if isAlias {
400 return fmt.Sprintf("type %s = %s", goName, goType(actualDef))
401 }
402 return fmt.Sprintf("type %s %s", goName, goType(actualDef))
403 }
404
405 var pragmas, decls bytes.Buffer
406 for _, pr := range allPragmas {
407 pragmas.WriteString(pr.Text + "\n")
408 if decl, ok := userDecls[declKey(pr)]; ok {
409
410 if !otherDecls[declKey(pr)] {
411 decls.WriteString(decl + "\n\n")
412 }
413 continue
414 }
415 recv := ""
416 if pr.RecvType != "" {
417 recv = "(*" + pr.RecvType + ") "
418 }
419 n := p.Name[pr.CName]
420 switch pr.Kind {
421 case "dynload":
422 fmt.Fprintf(&decls, "type %s struct {\n\tcgo.Library\n}\n\n", pr.GoName)
423 case "type":
424 id, _ := n.Type.Go.(*ast.Ident)
425 if id == nil {
426 fmt.Fprintf(&decls, "type %s %s\n\n", pr.GoName, goType(n.Type.Go))
427 break
428 }
429 fmt.Fprintf(&decls, "%s\n\n", typeDecl(pr.GoName, id.Name))
430 case "const":
431 fmt.Fprintf(&decls, "const %s = %s\n\n", pr.GoName, n.Const)
432 case "var":
433 if recv != "" {
434 fmt.Fprintf(&decls, "func %s%s() *%s\n\n", recv, pr.GoName, goType(n.Type.Go))
435 break
436 }
437 fmt.Fprintf(&decls, "var %s %s\n\n", pr.GoName, goType(n.Type.Go))
438 case "func":
439 var params []string
440 for i, t := range n.FuncType.Params {
441 params = append(params, fmt.Sprintf("p%d %s", i, goType(t.Go)))
442 }
443 ret := ""
444 if n.FuncType.Result != nil {
445 ret = " " + goType(n.FuncType.Result.Go)
446 }
447 fmt.Fprintf(&decls, "func %s%s(%s)%s\n\n", recv, pr.GoName, strings.Join(params, ", "), ret)
448 }
449 }
450
451 var depPragmas bytes.Buffer
452 for _, name := range typeKeys {
453 goName := typeToGoName[name]
454 fmt.Fprintf(&depPragmas, "//cgo:type %s C.%s\n", goName, strings.TrimPrefix(name, "_Ctype_"))
455 fmt.Fprintf(&decls, "%s\n\n", typeDecl(goName, name))
456 }
457
458
459
460
461 var body bytes.Buffer
462 body.Write(pragmas.Bytes())
463 body.Write(depPragmas.Bytes())
464 body.WriteString("\n")
465 body.Write(decls.Bytes())
466
467
468
469 var preamble bytes.Buffer
470 seenPreamble := make(map[string]bool)
471 for _, f := range p.genFiles {
472 var buf bytes.Buffer
473 forEachImportC(f.gen.ast, func(_ *ast.GenDecl, _ *ast.ImportSpec, doc *ast.CommentGroup) {
474 if doc == nil || buf.Len() > 0 {
475 return
476 }
477 for _, c := range doc.List {
478 if !isCgoPragmaComment(c.Text) {
479 buf.WriteString(c.Text + "\n")
480 }
481 }
482 })
483 if text := buf.String(); text != "" && !seenPreamble[text] {
484 seenPreamble[text] = true
485 preamble.WriteString(text)
486 }
487 }
488
489
490
491 usedPkgs := make(map[string]bool)
492 if declAST, err := parser.ParseFile(token.NewFileSet(), "", "package "+pkgName.Name+"\n"+decls.String(), 0); err == nil {
493 ast.Inspect(declAST, func(n ast.Node) bool {
494 if sel, ok := n.(*ast.SelectorExpr); ok {
495 if id, ok := sel.X.(*ast.Ident); ok {
496 usedPkgs[id.Name] = true
497 }
498 }
499 return true
500 })
501 }
502 var imports []string
503 importedPaths := make(map[string]string)
504 for _, f := range p.genFiles {
505 g := f.gen
506 for _, imp := range g.ast.Imports {
507 path, _ := strconv.Unquote(imp.Path.Value)
508 if path == "C" {
509 continue
510 }
511 name := path[strings.LastIndex(path, "/")+1:]
512 if imp.Name != nil {
513 name = imp.Name.Name
514 }
515 if name == "_" || name == "." || !usedPkgs[name] {
516 continue
517 }
518 if prev, ok := importedPaths[name]; ok {
519 if prev != path {
520 error_(imp.Pos(), "-gen-binding: %s refers to both %q and %q in the input files", name, prev, path)
521 }
522 continue
523 }
524 imports = append(imports, strings.TrimSpace(string(g.src[fset.Position(imp.Pos()).Offset:fset.Position(imp.End()).Offset])))
525 importedPaths[name] = path
526 }
527 }
528 for _, std := range []string{"runtime/cgo", "structs", "unsafe"} {
529 name := std[strings.LastIndex(std, "/")+1:]
530 if _, ok := importedPaths[name]; usedPkgs[name] && !ok {
531 imports = append(imports, strconv.Quote(std))
532 importedPaths[name] = std
533 }
534 }
535
536 var out bytes.Buffer
537 fmt.Fprintf(&out, "// Code generated by cmd/cgo -gen-binding; DO NOT EDIT.\n\n")
538 fmt.Fprintf(&out, "//go:build %s && %s\n\n", goos, goarch)
539 fmt.Fprintf(&out, "package %s\n\n", pkgName.Name)
540 out.Write(preamble.Bytes())
541 fmt.Fprintf(&out, "import \"C\"\n\n")
542 for _, imp := range imports {
543 fmt.Fprintf(&out, "import %s\n", imp)
544 }
545 out.WriteString("\n")
546 out.Write(body.Bytes())
547
548 formatted, err := format.Source(out.Bytes())
549 if err != nil {
550 fatalf("-gen-binding: formatting output: %v\n%s", err, out.Bytes())
551 }
552 w.Write(formatted)
553 }
554
555 func (p *Package) formatGoBindingTypeExpr(expr ast.Expr, anonToName, typeToGoName map[string]string) string {
556 switch e := expr.(type) {
557 case *ast.Ident:
558 name := e.Name
559 if name == "_cgopackage.Incomplete" {
560 return "cgo.Incomplete"
561 }
562 if goType, ok := primitiveCtypeToGo(name); ok {
563 return goType
564 }
565 if typedefName, ok := anonToName[name]; ok {
566 if gName, ok := typeToGoName[typedefName]; ok {
567 return gName
568 }
569 return "_" + typedefName
570 }
571 if def := typedef[name]; def != nil && isAnonCtype(name) {
572
573
574
575 return p.formatGoBindingTypeExpr(def.Go, anonToName, typeToGoName)
576 }
577 if gName, ok := typeToGoName[name]; ok {
578 return gName
579 }
580 clean := strings.TrimPrefix(name, "_Ctype_")
581 if gName, ok := typeToGoName[clean]; ok {
582 return gName
583 }
584 if strings.HasPrefix(name, "_Ctype_") {
585 return "_" + clean
586 }
587 return name
588 case *ast.StarExpr:
589 return "*" + p.formatGoBindingTypeExpr(e.X, anonToName, typeToGoName)
590 case *ast.ArrayType:
591 lenStr := ""
592 if e.Len != nil {
593 var lenBuf bytes.Buffer
594 noSourceConf.Fprint(&lenBuf, p.fset, e.Len)
595 lenStr = lenBuf.String()
596 }
597 return "[" + lenStr + "]" + p.formatGoBindingTypeExpr(e.Elt, anonToName, typeToGoName)
598 case *ast.StructType:
599 var buf bytes.Buffer
600 buf.WriteString("struct {\n\t_ structs.HostLayout\n")
601 for _, fld := range e.Fields.List {
602 typeStr := p.formatGoBindingTypeExpr(fld.Type, anonToName, typeToGoName)
603 var names []string
604 for _, id := range fld.Names {
605 names = append(names, id.Name)
606 }
607 nameStr := strings.Join(names, ", ")
608 if nameStr == "" {
609 fmt.Fprintf(&buf, "\t%s\n", typeStr)
610 } else {
611 fmt.Fprintf(&buf, "\t%s %s\n", nameStr, typeStr)
612 }
613 }
614 buf.WriteString("}")
615 return buf.String()
616 default:
617 var buf bytes.Buffer
618 noSourceConf.Fprint(&buf, p.fset, expr)
619 return strings.ReplaceAll(buf.String(), "_cgopackage.Incomplete", "cgo.Incomplete")
620 }
621 }
622
View as plain text