| 1 |
// Copyright 2025 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 |
//go:build ignore |
| 6 |
|
| 7 |
// AliasGen collects all top-level, exported declarations and |
| 8 |
// produces aliases that reference declarations in another package |
| 9 |
// that actually implements each declaration. |
| 10 |
// |
| 11 |
// Usage: |
| 12 |
// |
| 13 |
// go run alias_gen.go {TargetPkgPath} {WorkingDir} |
| 14 |
// |
| 15 |
// Where: |
| 16 |
// - TargetPkgPath is that package path that implements each declaration. |
| 17 |
// - WorkingDir is the directory that contains Go source files. |
| 18 |
// All top-level, exported declarations are collected and transformed |
| 19 |
// into aliases to the equivalent declaration in the target package |
| 20 |
// and written to an alias.go output file. |
| 21 |
package main |
| 22 |
|
| 23 |
import ( |
| 24 |
"bytes" |
| 25 |
"cmp" |
| 26 |
"fmt" |
| 27 |
"go/ast" |
| 28 |
"go/format" |
| 29 |
"go/parser" |
| 30 |
"go/token" |
| 31 |
"maps" |
| 32 |
"os" |
| 33 |
"path/filepath" |
| 34 |
"slices" |
| 35 |
"strconv" |
| 36 |
"strings" |
| 37 |
) |
| 38 |
|
| 39 |
func main() { |
| 40 |
targetPkgPath := os.Args[1] |
| 41 |
workingDir := os.Args[2] |
| 42 |
generateAliases(targetPkgPath, workingDir) |
| 43 |
} |
| 44 |
|
| 45 |
func generateAliases(targetPkgPath, workingDir string) { |
| 46 |
fset := token.NewFileSet() |
| 47 |
var files []*ast.File |
| 48 |
for _, fi := range mustGet(os.ReadDir(workingDir)) { |
| 49 |
if !strings.HasSuffix(fi.Name(), ".go") || strings.HasSuffix(fi.Name(), "_test.go") || fi.Name() == "alias.go" || fi.Name() == "alias_gen.go" { |
| 50 |
continue |
| 51 |
} |
| 52 |
b := mustGet(os.ReadFile(filepath.Join(workingDir, fi.Name()))) |
| 53 |
f := mustGet(parser.ParseFile(fset, fi.Name(), b, parser.ParseComments)) |
| 54 |
files = append(files, f) |
| 55 |
} |
| 56 |
slices.SortFunc(files, func(x, y *ast.File) int { |
| 57 |
return cmp.Compare(fset.File(x.Pos()).Name(), fset.File(y.Pos()).Name()) |
| 58 |
}) |
| 59 |
|
| 60 |
var aliasFile, aliasDecls bytes.Buffer |
| 61 |
|
| 62 |
// Print copyright. |
| 63 |
aliasFile.WriteString("// Copyright 2025 The Go Authors. All rights reserved.\n") |
| 64 |
aliasFile.WriteString("// Use of this source code is governed by a BSD-style\n") |
| 65 |
aliasFile.WriteString("// license that can be found in the LICENSE file.\n") |
| 66 |
aliasFile.WriteString("\n") |
| 67 |
|
| 68 |
// Print build tag. |
| 69 |
aliasFile.WriteString("// Code generated by alias_gen.go; DO NOT EDIT.\n") |
| 70 |
aliasFile.WriteString("\n") |
| 71 |
aliasFile.WriteString("//go:build goexperiment.jsonv2 && go1.25\n") |
| 72 |
aliasFile.WriteString("\n") |
| 73 |
|
| 74 |
// Print package docs. |
| 75 |
packageName := files[0].Name.String() |
| 76 |
for _, f := range files { |
| 77 |
writeComments(&aliasFile, f.Doc) |
| 78 |
} |
| 79 |
aliasFile.WriteString("package " + packageName + "\n") |
| 80 |
aliasFile.WriteString("\n") |
| 81 |
|
| 82 |
// Print the imports. |
| 83 |
imports := make(map[string]struct{}) |
| 84 |
writeType := func(expr ast.Expr) { |
| 85 |
ast.Walk(astVisitor(func(node ast.Node) bool { |
| 86 |
if sel, ok := node.(*ast.SelectorExpr); ok { |
| 87 |
if id, ok := sel.X.(*ast.Ident); ok { |
| 88 |
switch pkgName := id.String(); pkgName { |
| 89 |
case "io", "bytes": |
| 90 |
imports[pkgName] = struct{}{} |
| 91 |
case "jsontext": |
| 92 |
imports[`encoding/json/jsontext`] = struct{}{} |
| 93 |
default: |
| 94 |
panic(fmt.Sprintf("unknown package %q", id.String())) |
| 95 |
} |
| 96 |
} |
| 97 |
} |
| 98 |
return true |
| 99 |
}), expr) |
| 100 |
mustDo(format.Node(&aliasDecls, fset, expr)) |
| 101 |
} |
| 102 |
writeImports := func() { |
| 103 |
aliasFile.WriteString("import (\n") |
| 104 |
imports := append(slices.Collect(maps.Keys(imports)), targetPkgPath) |
| 105 |
slices.Sort(imports) |
| 106 |
for _, pkgPath := range imports { |
| 107 |
aliasFile.WriteString(strconv.Quote(pkgPath) + "\n") |
| 108 |
} |
| 109 |
aliasFile.WriteString(")\n") |
| 110 |
aliasFile.WriteString("\n") |
| 111 |
} |
| 112 |
|
| 113 |
// Print aliases to every exported top-level declaration. |
| 114 |
for _, f := range files { |
| 115 |
for _, d := range f.Decls { |
| 116 |
switch d := d.(type) { |
| 117 |
case *ast.GenDecl: |
| 118 |
switch d.Tok { |
| 119 |
case token.IMPORT: |
| 120 |
case token.CONST, token.VAR: |
| 121 |
// Check whether there any exported declarations. |
| 122 |
var hasExported bool |
| 123 |
for _, s := range d.Specs { |
| 124 |
for _, name := range s.(*ast.ValueSpec).Names { |
| 125 |
hasExported = hasExported || (name.IsExported() && name.String() != "Internal") |
| 126 |
} |
| 127 |
} |
| 128 |
if !hasExported { |
| 129 |
continue |
| 130 |
} |
| 131 |
|
| 132 |
// Print the declaration. |
| 133 |
writeComments(&aliasDecls, d.Doc) |
| 134 |
if d.Lparen > 0 { |
| 135 |
aliasDecls.WriteString(d.Tok.String()) |
| 136 |
aliasDecls.WriteString(" (\n") |
| 137 |
} |
| 138 |
for _, s := range d.Specs { |
| 139 |
s := s.(*ast.ValueSpec) |
| 140 |
writeComments(&aliasDecls, s.Doc) |
| 141 |
if d.Lparen == 0 { |
| 142 |
aliasDecls.WriteString(d.Tok.String()) |
| 143 |
aliasDecls.WriteByte(' ') |
| 144 |
} |
| 145 |
var hasExported bool |
| 146 |
for _, name := range s.Names { |
| 147 |
if name.IsExported() { |
| 148 |
aliasDecls.WriteString(name.String()) |
| 149 |
aliasDecls.WriteByte(',') |
| 150 |
hasExported = true |
| 151 |
} |
| 152 |
} |
| 153 |
if !hasExported { |
| 154 |
continue |
| 155 |
} |
| 156 |
trimRight(&aliasDecls, ",") |
| 157 |
aliasDecls.WriteByte('=') |
| 158 |
for _, name := range s.Names { |
| 159 |
if name.IsExported() { |
| 160 |
aliasDecls.WriteString(packageName) |
| 161 |
aliasDecls.WriteByte('.') |
| 162 |
aliasDecls.WriteString(name.String()) |
| 163 |
aliasDecls.WriteByte(',') |
| 164 |
} |
| 165 |
} |
| 166 |
trimRight(&aliasDecls, ",") |
| 167 |
aliasDecls.WriteString("\n") |
| 168 |
} |
| 169 |
if d.Rparen > 0 { |
| 170 |
aliasDecls.WriteString(")") |
| 171 |
} |
| 172 |
aliasDecls.WriteString("\n") |
| 173 |
case token.TYPE: |
| 174 |
for _, s := range d.Specs { |
| 175 |
s := s.(*ast.TypeSpec) |
| 176 |
if !s.Name.IsExported() { |
| 177 |
continue |
| 178 |
} |
| 179 |
writeComments(&aliasDecls, d.Doc) |
| 180 |
aliasDecls.WriteString(d.Tok.String()) |
| 181 |
aliasDecls.WriteByte(' ') |
| 182 |
aliasDecls.WriteString(s.Name.String()) |
| 183 |
aliasDecls.WriteByte('=') |
| 184 |
aliasDecls.WriteString(packageName) |
| 185 |
aliasDecls.WriteByte('.') |
| 186 |
aliasDecls.WriteString(s.Name.String()) |
| 187 |
aliasDecls.WriteString("\n") |
| 188 |
aliasDecls.WriteString("\n") |
| 189 |
} |
| 190 |
default: |
| 191 |
panic(fmt.Sprintf("unknown token.Token: %v", d.Tok)) |
| 192 |
} |
| 193 |
case *ast.FuncDecl: |
| 194 |
if !d.Name.IsExported() || d.Recv != nil { |
| 195 |
continue // ignore unexported functions or methods |
| 196 |
} |
| 197 |
|
| 198 |
// Print the comment. |
| 199 |
writeComments(&aliasDecls, d.Doc) |
| 200 |
aliasDecls.WriteString(token.FUNC.String()) |
| 201 |
aliasDecls.WriteByte(' ') |
| 202 |
aliasDecls.WriteString(d.Name.String()) |
| 203 |
writeFields := func(fields *ast.FieldList, leftDelim, rightDelim byte, withType bool) { |
| 204 |
if fields == nil { |
| 205 |
return |
| 206 |
} |
| 207 |
aliasDecls.WriteByte(leftDelim) |
| 208 |
for i, field := range fields.List { |
| 209 |
for j, name := range field.Names { |
| 210 |
aliasDecls.WriteString(name.String()) |
| 211 |
if j < len(field.Names)-1 { |
| 212 |
aliasDecls.WriteByte(',') |
| 213 |
} |
| 214 |
} |
| 215 |
if withType { |
| 216 |
aliasDecls.WriteByte(' ') |
| 217 |
writeType(field.Type) |
| 218 |
} else if _, ok := field.Type.(*ast.Ellipsis); ok { |
| 219 |
aliasDecls.WriteString("...") |
| 220 |
} |
| 221 |
if i < len(fields.List)-1 { |
| 222 |
aliasDecls.WriteByte(',') |
| 223 |
} |
| 224 |
} |
| 225 |
aliasDecls.WriteByte(rightDelim) |
| 226 |
} |
| 227 |
|
| 228 |
writeFields(d.Type.TypeParams, '[', ']', true) |
| 229 |
writeFields(d.Type.Params, '(', ')', true) |
| 230 |
writeFields(d.Type.Results, '(', ')', true) |
| 231 |
|
| 232 |
aliasDecls.WriteString("{\n") |
| 233 |
if d.Type.Results != nil { |
| 234 |
aliasDecls.WriteString(token.RETURN.String()) |
| 235 |
aliasDecls.WriteByte(' ') |
| 236 |
} |
| 237 |
aliasDecls.WriteString(packageName) |
| 238 |
aliasDecls.WriteByte('.') |
| 239 |
aliasDecls.WriteString(d.Name.String()) |
| 240 |
writeFields(d.Type.TypeParams, '[', ']', false) |
| 241 |
writeFields(d.Type.Params, '(', ')', false) |
| 242 |
aliasDecls.WriteString("\n") |
| 243 |
aliasDecls.WriteString("}\n") |
| 244 |
aliasDecls.WriteString("\n") |
| 245 |
default: |
| 246 |
panic(fmt.Sprintf("unknown ast.Decl type: %T", d)) |
| 247 |
} |
| 248 |
} |
| 249 |
} |
| 250 |
writeImports() |
| 251 |
aliasFile.Write(aliasDecls.Bytes()) |
| 252 |
|
| 253 |
// Write to the output file. |
| 254 |
b := mustGet(format.Source(aliasFile.Bytes())) |
| 255 |
mustDo(os.WriteFile(filepath.Join(workingDir, "alias.go"), b, 0664)) |
| 256 |
} |
| 257 |
|
| 258 |
func mustDo(err error) { |
| 259 |
if err != nil { |
| 260 |
panic(err) |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
func mustGet[T any](v T, err error) T { |
| 265 |
mustDo(err) |
| 266 |
return v |
| 267 |
} |
| 268 |
|
| 269 |
func writeComments(out *bytes.Buffer, comments *ast.CommentGroup) { |
| 270 |
for line := range strings.Lines(comments.Text()) { |
| 271 |
out.WriteString("// ") |
| 272 |
out.WriteString(line) |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
func trimRight(out *bytes.Buffer, cutset string) { |
| 277 |
out.Truncate(len(bytes.TrimRight(out.Bytes(), cutset))) |
| 278 |
} |
| 279 |
|
| 280 |
type astVisitor func(ast.Node) bool |
| 281 |
|
| 282 |
func (f astVisitor) Visit(node ast.Node) ast.Visitor { |
| 283 |
if !f(node) { |
| 284 |
return nil |
| 285 |
} |
| 286 |
return f |
| 287 |
} |