File: stubs.go

package info (click to toggle)
golang-github-mmcloughlin-avo 0.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 15,024 kB
  • sloc: xml: 71,029; asm: 14,862; sh: 194; makefile: 21; ansic: 11
file content (61 lines) | stat: -rw-r--r-- 1,216 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package printer

import (
	"go/format"

	"github.com/mmcloughlin/avo/buildtags"
	"github.com/mmcloughlin/avo/internal/prnt"
	"github.com/mmcloughlin/avo/ir"
)

type stubs struct {
	cfg Config
	prnt.Generator
}

// NewStubs constructs a printer for writing stub function declarations.
func NewStubs(cfg Config) Printer {
	return &stubs{cfg: cfg}
}

func (s *stubs) Print(f *ir.File) ([]byte, error) {
	s.Comment(s.cfg.GeneratedWarning())

	if len(f.Constraints) > 0 {
		constraints, err := buildtags.Format(f.Constraints)
		if err != nil {
			s.AddError(err)
		}
		s.NL()
		s.Printf(constraints)
	}

	s.NL()
	s.Printf("package %s\n", s.cfg.Pkg)
	for _, fn := range f.Functions() {
		s.NL()
		s.Comment(fn.Doc...)
		for _, pragma := range fn.Pragmas {
			s.pragma(pragma)
		}
		s.Printf("%s\n", fn.Stub())
	}

	// Apply formatting to the result. This is the simplest way to ensure
	// comment formatting rules introduced in Go 1.19 are applied.  See
	// https://go.dev/doc/comment.
	src, err := s.Result()
	if err != nil {
		return nil, err
	}

	return format.Source(src)
}

func (s *stubs) pragma(p ir.Pragma) {
	s.Printf("//go:%s", p.Directive)
	for _, arg := range p.Arguments {
		s.Printf(" %s", arg)
	}
	s.NL()
}