| 1 |
// Copyright 2019 The Hugo Authors. All rights reserved. |
| 2 |
// Some functions in this file (see comments) is based on the Go source code, |
| 3 |
// copyright The Go Authors and governed by a BSD-style license. |
| 4 |
// |
| 5 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
// you may not use this file except in compliance with the License. |
| 7 |
// You may obtain a copy of the License at |
| 8 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
// |
| 10 |
// Unless required by applicable law or agreed to in writing, software |
| 11 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
// See the License for the specific language governing permissions and |
| 14 |
// limitations under the License. |
| 15 |
|
| 16 |
// Package codegen contains helpers for code generation. |
| 17 |
package codegen |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"go/ast" |
| 22 |
"go/parser" |
| 23 |
"go/token" |
| 24 |
"os" |
| 25 |
"path" |
| 26 |
"path/filepath" |
| 27 |
"reflect" |
| 28 |
"regexp" |
| 29 |
"slices" |
| 30 |
"sort" |
| 31 |
"strings" |
| 32 |
"sync" |
| 33 |
) |
| 34 |
|
| 35 |
// Make room for insertions |
| 36 |
const weightWidth = 1000 |
| 37 |
|
| 38 |
// NewInspector creates a new Inspector given a source root. |
| 39 |
func NewInspector(root string) *Inspector { |
| 40 |
return &Inspector{ProjectRootDir: root} |
| 41 |
} |
| 42 |
|
| 43 |
// Inspector provides methods to help code generation. It uses a combination |
| 44 |
// of reflection and source code AST to do the heavy lifting. |
| 45 |
type Inspector struct { |
| 46 |
ProjectRootDir string |
| 47 |
|
| 48 |
init sync.Once |
| 49 |
|
| 50 |
// Determines method order. Go's reflect sorts lexicographically, so |
| 51 |
// we must parse the source to preserve this order. |
| 52 |
methodWeight map[string]map[string]int |
| 53 |
} |
| 54 |
|
| 55 |
// MethodsFromTypes create a method set from the include slice, excluding any |
| 56 |
// method in exclude. |
| 57 |
func (c *Inspector) MethodsFromTypes(include []reflect.Type, exclude []reflect.Type) Methods { |
| 58 |
c.parseSource() |
| 59 |
|
| 60 |
var methods Methods |
| 61 |
|
| 62 |
excludes := make(map[string]bool) |
| 63 |
|
| 64 |
if len(exclude) > 0 { |
| 65 |
for _, m := range c.MethodsFromTypes(exclude, nil) { |
| 66 |
excludes[m.Name] = true |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
// There may be overlapping interfaces in types. Do a simple check for now. |
| 71 |
seen := make(map[string]bool) |
| 72 |
|
| 73 |
nameAndPackage := func(t reflect.Type) (string, string) { |
| 74 |
var name, pkg string |
| 75 |
|
| 76 |
isPointer := t.Kind() == reflect.Pointer |
| 77 |
|
| 78 |
if isPointer { |
| 79 |
t = t.Elem() |
| 80 |
} |
| 81 |
|
| 82 |
pkgPrefix := "" |
| 83 |
if pkgPath := t.PkgPath(); pkgPath != "" { |
| 84 |
pkgPath = strings.TrimSuffix(pkgPath, "/") |
| 85 |
_, shortPath := path.Split(pkgPath) |
| 86 |
pkgPrefix = shortPath + "." |
| 87 |
pkg = pkgPath |
| 88 |
} |
| 89 |
|
| 90 |
name = t.Name() |
| 91 |
if name == "" { |
| 92 |
// interface{} |
| 93 |
name = t.String() |
| 94 |
} |
| 95 |
|
| 96 |
if isPointer { |
| 97 |
pkgPrefix = "*" + pkgPrefix |
| 98 |
} |
| 99 |
|
| 100 |
name = pkgPrefix + name |
| 101 |
|
| 102 |
return name, pkg |
| 103 |
} |
| 104 |
|
| 105 |
for _, t := range include { |
| 106 |
for m := range t.Methods() { |
| 107 |
if excludes[m.Name] || seen[m.Name] { |
| 108 |
continue |
| 109 |
} |
| 110 |
|
| 111 |
seen[m.Name] = true |
| 112 |
|
| 113 |
if m.PkgPath != "" { |
| 114 |
// Not exported |
| 115 |
continue |
| 116 |
} |
| 117 |
|
| 118 |
numIn := m.Type.NumIn() |
| 119 |
|
| 120 |
ownerName, _ := nameAndPackage(t) |
| 121 |
|
| 122 |
method := Method{Owner: t, OwnerName: ownerName, Name: m.Name} |
| 123 |
|
| 124 |
for i := range numIn { |
| 125 |
in := m.Type.In(i) |
| 126 |
|
| 127 |
name, pkg := nameAndPackage(in) |
| 128 |
|
| 129 |
if pkg != "" { |
| 130 |
method.Imports = append(method.Imports, pkg) |
| 131 |
} |
| 132 |
|
| 133 |
method.In = append(method.In, name) |
| 134 |
} |
| 135 |
|
| 136 |
numOut := m.Type.NumOut() |
| 137 |
|
| 138 |
if numOut > 0 { |
| 139 |
for i := range numOut { |
| 140 |
out := m.Type.Out(i) |
| 141 |
name, pkg := nameAndPackage(out) |
| 142 |
|
| 143 |
if pkg != "" { |
| 144 |
method.Imports = append(method.Imports, pkg) |
| 145 |
} |
| 146 |
|
| 147 |
method.Out = append(method.Out, name) |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
methods = append(methods, method) |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
sort.SliceStable(methods, func(i, j int) bool { |
| 156 |
mi, mj := methods[i], methods[j] |
| 157 |
|
| 158 |
wi := c.methodWeight[mi.OwnerName][mi.Name] |
| 159 |
wj := c.methodWeight[mj.OwnerName][mj.Name] |
| 160 |
|
| 161 |
if wi == wj { |
| 162 |
return mi.Name < mj.Name |
| 163 |
} |
| 164 |
|
| 165 |
return wi < wj |
| 166 |
}) |
| 167 |
|
| 168 |
return methods |
| 169 |
} |
| 170 |
|
| 171 |
func (c *Inspector) parseSource() { |
| 172 |
c.init.Do(func() { |
| 173 |
if !strings.Contains(c.ProjectRootDir, "hugo") { |
| 174 |
panic("dir must be set to the Hugo root") |
| 175 |
} |
| 176 |
|
| 177 |
c.methodWeight = make(map[string]map[string]int) |
| 178 |
dirExcludes := regexp.MustCompile("docs|examples") |
| 179 |
fileExcludes := regexp.MustCompile("autogen") |
| 180 |
var filenames []string |
| 181 |
|
| 182 |
filepath.Walk(c.ProjectRootDir, func(path string, info os.FileInfo, err error) error { |
| 183 |
if info.IsDir() { |
| 184 |
if dirExcludes.MatchString(info.Name()) { |
| 185 |
return filepath.SkipDir |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
if !strings.HasSuffix(path, ".go") || fileExcludes.MatchString(path) { |
| 190 |
return nil |
| 191 |
} |
| 192 |
|
| 193 |
filenames = append(filenames, path) |
| 194 |
|
| 195 |
return nil |
| 196 |
}) |
| 197 |
|
| 198 |
for _, filename := range filenames { |
| 199 |
|
| 200 |
pkg := c.packageFromPath(filename) |
| 201 |
|
| 202 |
fset := token.NewFileSet() |
| 203 |
node, err := parser.ParseFile(fset, filename, nil, parser.ParseComments) |
| 204 |
if err != nil { |
| 205 |
panic(err) |
| 206 |
} |
| 207 |
|
| 208 |
ast.Inspect(node, func(n ast.Node) bool { |
| 209 |
switch t := n.(type) { |
| 210 |
case *ast.TypeSpec: |
| 211 |
if t.Name.IsExported() { |
| 212 |
switch it := t.Type.(type) { |
| 213 |
case *ast.InterfaceType: |
| 214 |
iface := pkg + "." + t.Name.Name |
| 215 |
methodNames := collectMethodsRecursive(pkg, it.Methods.List) |
| 216 |
weights := make(map[string]int) |
| 217 |
weight := weightWidth |
| 218 |
for _, name := range methodNames { |
| 219 |
weights[name] = weight |
| 220 |
weight += weightWidth |
| 221 |
} |
| 222 |
c.methodWeight[iface] = weights |
| 223 |
} |
| 224 |
} |
| 225 |
} |
| 226 |
return true |
| 227 |
}) |
| 228 |
|
| 229 |
} |
| 230 |
|
| 231 |
// Complement |
| 232 |
for _, v1 := range c.methodWeight { |
| 233 |
for k2, w := range v1 { |
| 234 |
if v, found := c.methodWeight[k2]; found { |
| 235 |
for k3, v3 := range v { |
| 236 |
v1[k3] = (v3 / weightWidth) + w |
| 237 |
} |
| 238 |
} |
| 239 |
} |
| 240 |
} |
| 241 |
}) |
| 242 |
} |
| 243 |
|
| 244 |
func (c *Inspector) packageFromPath(p string) string { |
| 245 |
p = filepath.ToSlash(p) |
| 246 |
base := path.Base(p) |
| 247 |
if !strings.Contains(base, ".") { |
| 248 |
return base |
| 249 |
} |
| 250 |
return path.Base(strings.TrimSuffix(p, base)) |
| 251 |
} |
| 252 |
|
| 253 |
// Method holds enough information about it to recreate it. |
| 254 |
type Method struct { |
| 255 |
// The interface we extracted this method from. |
| 256 |
Owner reflect.Type |
| 257 |
|
| 258 |
// String version of the above, on the form PACKAGE.NAME, e.g. |
| 259 |
// page.Page |
| 260 |
OwnerName string |
| 261 |
|
| 262 |
// Method name. |
| 263 |
Name string |
| 264 |
|
| 265 |
// Imports needed to satisfy the method signature. |
| 266 |
Imports []string |
| 267 |
|
| 268 |
// Argument types, including any package prefix, e.g. string, int, interface{}, |
| 269 |
// net.Url |
| 270 |
In []string |
| 271 |
|
| 272 |
// Return types. |
| 273 |
Out []string |
| 274 |
} |
| 275 |
|
| 276 |
// Declaration creates a method declaration (without any body) for the given receiver. |
| 277 |
func (m Method) Declaration(receiver string) string { |
| 278 |
return fmt.Sprintf("func (%s %s) %s%s %s", receiverShort(receiver), receiver, m.Name, m.inStr(), m.outStr()) |
| 279 |
} |
| 280 |
|
| 281 |
// DeclarationNamed creates a method declaration (without any body) for the given receiver |
| 282 |
// with named return values. |
| 283 |
func (m Method) DeclarationNamed(receiver string) string { |
| 284 |
return fmt.Sprintf("func (%s %s) %s%s %s", receiverShort(receiver), receiver, m.Name, m.inStr(), m.outStrNamed()) |
| 285 |
} |
| 286 |
|
| 287 |
// Delegate creates a delegate call string. |
| 288 |
func (m Method) Delegate(receiver, delegate string) string { |
| 289 |
ret := "" |
| 290 |
if len(m.Out) > 0 { |
| 291 |
ret = "return " |
| 292 |
} |
| 293 |
return fmt.Sprintf("%s%s.%s.%s%s", ret, receiverShort(receiver), delegate, m.Name, m.inOutStr()) |
| 294 |
} |
| 295 |
|
| 296 |
func (m Method) String() string { |
| 297 |
return m.Name + m.inStr() + " " + m.outStr() + "\n" |
| 298 |
} |
| 299 |
|
| 300 |
func (m Method) inOutStr() string { |
| 301 |
if len(m.In) == 0 { |
| 302 |
return "()" |
| 303 |
} |
| 304 |
|
| 305 |
args := make([]string, len(m.In)) |
| 306 |
for i := range args { |
| 307 |
args[i] = fmt.Sprintf("arg%d", i) |
| 308 |
} |
| 309 |
return "(" + strings.Join(args, ", ") + ")" |
| 310 |
} |
| 311 |
|
| 312 |
func (m Method) inStr() string { |
| 313 |
if len(m.In) == 0 { |
| 314 |
return "()" |
| 315 |
} |
| 316 |
|
| 317 |
args := make([]string, len(m.In)) |
| 318 |
for i := range args { |
| 319 |
args[i] = fmt.Sprintf("arg%d %s", i, m.In[i]) |
| 320 |
} |
| 321 |
return "(" + strings.Join(args, ", ") + ")" |
| 322 |
} |
| 323 |
|
| 324 |
func (m Method) outStr() string { |
| 325 |
if len(m.Out) == 0 { |
| 326 |
return "" |
| 327 |
} |
| 328 |
if len(m.Out) == 1 { |
| 329 |
return m.Out[0] |
| 330 |
} |
| 331 |
|
| 332 |
return "(" + strings.Join(m.Out, ", ") + ")" |
| 333 |
} |
| 334 |
|
| 335 |
func (m Method) outStrNamed() string { |
| 336 |
if len(m.Out) == 0 { |
| 337 |
return "" |
| 338 |
} |
| 339 |
|
| 340 |
outs := make([]string, len(m.Out)) |
| 341 |
for i := range outs { |
| 342 |
outs[i] = fmt.Sprintf("o%d %s", i, m.Out[i]) |
| 343 |
} |
| 344 |
|
| 345 |
return "(" + strings.Join(outs, ", ") + ")" |
| 346 |
} |
| 347 |
|
| 348 |
// Methods represents a list of methods for one or more interfaces. |
| 349 |
// The order matches the defined order in their source file(s). |
| 350 |
type Methods []Method |
| 351 |
|
| 352 |
// Imports returns a sorted list of package imports needed to satisfy the |
| 353 |
// signatures of all methods. |
| 354 |
func (m Methods) Imports() []string { |
| 355 |
var pkgImports []string |
| 356 |
for _, method := range m { |
| 357 |
pkgImports = append(pkgImports, method.Imports...) |
| 358 |
} |
| 359 |
if len(pkgImports) > 0 { |
| 360 |
pkgImports = uniqueNonEmptyStrings(pkgImports) |
| 361 |
sort.Strings(pkgImports) |
| 362 |
} |
| 363 |
return pkgImports |
| 364 |
} |
| 365 |
|
| 366 |
// ToMarshalJSON creates a MarshalJSON method for these methods. Any method name |
| 367 |
// matching any of the regexps in excludes will be ignored. |
| 368 |
func (m Methods) ToMarshalJSON(receiver, pkgPath string, excludes ...string) (string, []string) { |
| 369 |
var sb strings.Builder |
| 370 |
|
| 371 |
r := receiverShort(receiver) |
| 372 |
what := firstToUpper(trimAsterisk(receiver)) |
| 373 |
pgkName := path.Base(pkgPath) |
| 374 |
|
| 375 |
fmt.Fprintf(&sb, "func Marshal%sToJSON(%s %s) ([]byte, error) {\n", what, r, receiver) |
| 376 |
|
| 377 |
var methods Methods |
| 378 |
excludeRes := make([]*regexp.Regexp, len(excludes)) |
| 379 |
|
| 380 |
for i, exclude := range excludes { |
| 381 |
excludeRes[i] = regexp.MustCompile(exclude) |
| 382 |
} |
| 383 |
|
| 384 |
for _, method := range m { |
| 385 |
// Exclude methods with arguments and incompatible return values |
| 386 |
if len(method.In) > 0 || len(method.Out) == 0 || len(method.Out) > 2 { |
| 387 |
continue |
| 388 |
} |
| 389 |
|
| 390 |
if len(method.Out) == 2 { |
| 391 |
if method.Out[1] != "error" { |
| 392 |
continue |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
for _, re := range excludeRes { |
| 397 |
if re.MatchString(method.Name) { |
| 398 |
continue |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
methods = append(methods, method) |
| 403 |
} |
| 404 |
|
| 405 |
for _, method := range methods { |
| 406 |
varn := varName(method.Name) |
| 407 |
if len(method.Out) == 1 { |
| 408 |
fmt.Fprintf(&sb, "\t%s := %s.%s()\n", varn, r, method.Name) |
| 409 |
} else { |
| 410 |
fmt.Fprintf(&sb, "\t%s, err := %s.%s()\n", varn, r, method.Name) |
| 411 |
fmt.Fprint(&sb, "\tif err != nil {\n\t\treturn nil, err\n\t}\n") |
| 412 |
} |
| 413 |
} |
| 414 |
|
| 415 |
fmt.Fprint(&sb, "\n\ts := struct {\n") |
| 416 |
|
| 417 |
for _, method := range methods { |
| 418 |
fmt.Fprintf(&sb, "\t\t%s %s\n", method.Name, typeName(method.Out[0], pgkName)) |
| 419 |
} |
| 420 |
|
| 421 |
fmt.Fprint(&sb, "\n\t}{\n") |
| 422 |
|
| 423 |
for _, method := range methods { |
| 424 |
varn := varName(method.Name) |
| 425 |
fmt.Fprintf(&sb, "\t\t%s: %s,\n", method.Name, varn) |
| 426 |
} |
| 427 |
|
| 428 |
fmt.Fprint(&sb, "\n\t}\n\n") |
| 429 |
fmt.Fprint(&sb, "\treturn json.Marshal(&s)\n}") |
| 430 |
|
| 431 |
pkgImports := append(methods.Imports(), "encoding/json") |
| 432 |
|
| 433 |
if pkgPath != "" { |
| 434 |
// Exclude self |
| 435 |
for i, pkgImp := range pkgImports { |
| 436 |
if pkgImp == pkgPath { |
| 437 |
pkgImports = slices.Delete(pkgImports, i, i+1) |
| 438 |
} |
| 439 |
} |
| 440 |
} |
| 441 |
|
| 442 |
return sb.String(), pkgImports |
| 443 |
} |
| 444 |
|
| 445 |
func collectMethodsRecursive(pkg string, f []*ast.Field) []string { |
| 446 |
var methodNames []string |
| 447 |
for _, m := range f { |
| 448 |
if m.Names != nil { |
| 449 |
methodNames = append(methodNames, m.Names[0].Name) |
| 450 |
continue |
| 451 |
} |
| 452 |
|
| 453 |
if ident, ok := m.Type.(*ast.Ident); ok && ident.Obj != nil { |
| 454 |
switch tt := ident.Obj.Decl.(*ast.TypeSpec).Type.(type) { |
| 455 |
case *ast.InterfaceType: |
| 456 |
// Embedded interface |
| 457 |
methodNames = append( |
| 458 |
methodNames, |
| 459 |
collectMethodsRecursive( |
| 460 |
pkg, |
| 461 |
tt.Methods.List)...) |
| 462 |
} |
| 463 |
} else { |
| 464 |
// Embedded, but in a different file/package. Return the |
| 465 |
// package.Name and deal with that later. |
| 466 |
name := packageName(m.Type) |
| 467 |
if !strings.Contains(name, ".") { |
| 468 |
// Assume current package |
| 469 |
name = pkg + "." + name |
| 470 |
} |
| 471 |
methodNames = append(methodNames, name) |
| 472 |
} |
| 473 |
} |
| 474 |
|
| 475 |
return methodNames |
| 476 |
} |
| 477 |
|
| 478 |
func firstToLower(name string) string { |
| 479 |
return strings.ToLower(name[:1]) + name[1:] |
| 480 |
} |
| 481 |
|
| 482 |
func firstToUpper(name string) string { |
| 483 |
return strings.ToUpper(name[:1]) + name[1:] |
| 484 |
} |
| 485 |
|
| 486 |
func packageName(e ast.Expr) string { |
| 487 |
switch tp := e.(type) { |
| 488 |
case *ast.Ident: |
| 489 |
return tp.Name |
| 490 |
case *ast.SelectorExpr: |
| 491 |
return fmt.Sprintf("%s.%s", packageName(tp.X), packageName(tp.Sel)) |
| 492 |
} |
| 493 |
return "" |
| 494 |
} |
| 495 |
|
| 496 |
func receiverShort(receiver string) string { |
| 497 |
return strings.ToLower(trimAsterisk(receiver))[:1] |
| 498 |
} |
| 499 |
|
| 500 |
func trimAsterisk(name string) string { |
| 501 |
return strings.TrimPrefix(name, "*") |
| 502 |
} |
| 503 |
|
| 504 |
func typeName(name, pkg string) string { |
| 505 |
return strings.TrimPrefix(name, pkg+".") |
| 506 |
} |
| 507 |
|
| 508 |
func uniqueNonEmptyStrings(s []string) []string { |
| 509 |
var unique []string |
| 510 |
set := map[string]any{} |
| 511 |
for _, val := range s { |
| 512 |
if val == "" { |
| 513 |
continue |
| 514 |
} |
| 515 |
if _, ok := set[val]; !ok { |
| 516 |
unique = append(unique, val) |
| 517 |
set[val] = val |
| 518 |
} |
| 519 |
} |
| 520 |
return unique |
| 521 |
} |
| 522 |
|
| 523 |
func varName(name string) string { |
| 524 |
name = firstToLower(name) |
| 525 |
|
| 526 |
// Adjust some reserved keywords, see https://golang.org/ref/spec#Keywords |
| 527 |
switch name { |
| 528 |
case "type": |
| 529 |
name = "typ" |
| 530 |
case "package": |
| 531 |
name = "pkg" |
| 532 |
// Not reserved, but syntax highlighters has it as a keyword. |
| 533 |
case "len": |
| 534 |
name = "length" |
| 535 |
} |
| 536 |
|
| 537 |
return name |
| 538 |
} |