Skip to content

Commit

Permalink
Refactor. Clean up import rendering in codegen.
Browse files Browse the repository at this point in the history
  • Loading branch information
lthibault committed Aug 5, 2022
1 parent 4c15fd3 commit 6334ac6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 20 deletions.
10 changes: 5 additions & 5 deletions capnpc-go/capnpc-go.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,12 @@ type generator struct {

func newGenerator(fileID uint64, nodes nodeMap, opts genoptions) *generator {
g := &generator{
r: &templateRenderer{t: templates},
fileID: fileID,
nodes: nodes,
opts: opts,
r: &templateRenderer{t: templates},
fileID: fileID,
nodes: nodes,
imports: newImports(),
opts: opts,
}
g.imports.init()
g.data.init(fileID)
return g
}
Expand Down
43 changes: 28 additions & 15 deletions capnpc-go/fileparts.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,25 @@ import (
"capnproto.org/go/capnp/v3"
)

var (
capnpImportSpec = importSpec{path: capnpImport, name: "capnp"}
importList = []importSpec{
capnpImportSpec,

// capnp subpackage imports
{path: schemasImport, name: "schemas"},
{path: serverImport, name: "server"},
{path: textImport, name: "text"},
{path: flowcontrolImport, name: "fc"},

// stdlib imports
{path: "fmt", name: "fmt"},
{path: "context", name: "context"},
{path: "math", name: "math"},
{path: "strconv", name: "strconv"},
}
)

type staticData struct {
name string
buf []byte
Expand Down Expand Up @@ -57,22 +76,12 @@ type imports struct {
used map[string]bool // keyed on import path
}

var capnpImportSpec = importSpec{path: capnpImport, name: "capnp"}

func (i *imports) init() {
i.specs = nil
i.used = make(map[string]bool)

i.reserve(capnpImportSpec)
i.reserve(importSpec{path: schemasImport, name: "schemas"})
i.reserve(importSpec{path: serverImport, name: "server"})
i.reserve(importSpec{path: textImport, name: "text"})
i.reserve(importSpec{path: flowcontrolImport, name: "fc"})
func newImports() (i imports) {
for _, spec := range importList {
i.reserve(spec)
}

i.reserve(importSpec{path: "fmt", name: "fmt"})
i.reserve(importSpec{path: "context", name: "context"})
i.reserve(importSpec{path: "math", name: "math"})
i.reserve(importSpec{path: "strconv", name: "strconv"})
return
}

func (i *imports) Capnp() string {
Expand Down Expand Up @@ -140,6 +149,10 @@ func (i *imports) byName(name string) (spec importSpec, ok bool) {
}

func (i *imports) add(spec importSpec) (name string) {
if i.used == nil {
i.used = make(map[string]bool)
}

name = i.reserve(spec)
i.used[spec.path] = true
return name
Expand Down

0 comments on commit 6334ac6

Please sign in to comment.