| 1 | /* |
| 2 | Package extract generates wrappers of package exported symbols. |
| 3 | */ |
| 4 | package extract |
| 5 | |
| 6 | import ( |
| 7 | "bufio" |
| 8 | "bytes" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "go/constant" |
| 12 | "go/format" |
| 13 | "go/importer" |
| 14 | "go/token" |
| 15 | "go/types" |
| 16 | "io" |
| 17 | "math/big" |
| 18 | "os" |
| 19 | "path" |
| 20 | "path/filepath" |
| 21 | "regexp" |
| 22 | "runtime" |
| 23 | "strconv" |
| 24 | "strings" |
| 25 | "text/template" |
| 26 | ) |
| 27 | |
| 28 | const model = `// Code generated by 'yaegi extract {{.ImportPath}}'. DO NOT EDIT. |
| 29 | |
| 30 | {{.License}} |
| 31 | |
| 32 | {{if .BuildTags}}// +build {{.BuildTags}}{{end}} |
| 33 | |
| 34 | package {{.Dest}} |
| 35 | |
| 36 | import ( |
| 37 | {{- range $key, $value := .Imports }} |
| 38 | {{- if $value}} |
| 39 | "{{$key}}" |
| 40 | {{- end}} |
| 41 | {{- end}} |
| 42 | {{- if or .Val .Typ }} |
| 43 | "{{.ImportPath}}" |
| 44 | {{- end}} |
| 45 | "reflect" |
| 46 | ) |
| 47 | |
| 48 | func init() { |
| 49 | Symbols["{{.PkgName}}"] = map[string]reflect.Value{ |
| 50 | {{- if .Val}} |
| 51 | // function, constant and variable definitions |
| 52 | {{range $key, $value := .Val -}} |
| 53 | {{- if $value.Addr -}} |
| 54 | "{{$key}}": reflect.ValueOf(&{{$value.Name}}).Elem(), |
| 55 | {{else -}} |
| 56 | "{{$key}}": reflect.ValueOf({{$value.Name}}), |
| 57 | {{end -}} |
| 58 | {{end}} |
| 59 | |
| 60 | {{- end}} |
| 61 | {{- if .Typ}} |
| 62 | // type definitions |
| 63 | {{range $key, $value := .Typ -}} |
| 64 | "{{$key}}": reflect.ValueOf((*{{$value}})(nil)), |
| 65 | {{end}} |
| 66 | |
| 67 | {{- end}} |
| 68 | {{- if .Wrap}} |
| 69 | // interface wrapper definitions |
| 70 | {{range $key, $value := .Wrap -}} |
| 71 | "_{{$key}}": reflect.ValueOf((*{{$value.Name}})(nil)), |
| 72 | {{end}} |
| 73 | {{- end}} |
| 74 | } |
| 75 | } |
| 76 | {{range $key, $value := .Wrap -}} |
| 77 | // {{$value.Name}} is an interface wrapper for {{$key}} type |
| 78 | type {{$value.Name}} struct { |
| 79 | IValue interface{} |
| 80 | {{range $m := $value.Method -}} |
| 81 | W{{$m.Name}} func{{$m.Param}} {{$m.Result}} |
| 82 | {{end}} |
| 83 | } |
| 84 | {{range $m := $value.Method -}} |
| 85 | func (W {{$value.Name}}) {{$m.Name}}{{$m.Param}} {{$m.Result}} { |
| 86 | {{- if eq $m.Name "String"}} |
| 87 | if W.WString == nil { |
| 88 | return "" |
| 89 | } |
| 90 | {{end}} |
| 91 | {{- $m.Ret}} W.W{{$m.Name}}{{$m.Arg -}} |
| 92 | } |
| 93 | {{end}} |
| 94 | {{end}} |
| 95 | ` |
| 96 | |
| 97 | // Val stores the value name and addressable status of symbols. |
| 98 | type Val struct { |
| 99 | Name string // "package.name" |
| 100 | Addr bool // true if symbol is a Var |
| 101 | } |
| 102 | |
| 103 | // Method stores information for generating interface wrapper method. |
| 104 | type Method struct { |
| 105 | Name, Param, Result, Arg, Ret string |
| 106 | } |
| 107 | |
| 108 | // Wrap stores information for generating interface wrapper. |
| 109 | type Wrap struct { |
| 110 | Name string |
| 111 | Method []Method |
| 112 | } |
| 113 | |
| 114 | // restricted map defines symbols for which a special implementation is provided. |
| 115 | var restricted = map[string]bool{ |
| 116 | "osExit": true, |
| 117 | "osFindProcess": true, |
| 118 | "logFatal": true, |
| 119 | "logFatalf": true, |
| 120 | "logFatalln": true, |
| 121 | "logLogger": true, |
| 122 | "logNew": true, |
| 123 | } |
| 124 | |
| 125 | func matchList(name string, list []string) (match bool, err error) { |
| 126 | for _, re := range list { |
| 127 | match, err = regexp.MatchString(re, name) |
| 128 | if err != nil || match { |
| 129 | return |
| 130 | } |
| 131 | } |
| 132 | return |
| 133 | } |
| 134 | |
| 135 | // Extractor creates a package with all the symbols from a dependency package. |
| 136 | type Extractor struct { |
| 137 | Dest string // The name of the created package. |
| 138 | License string // License text to be included in the created package, optional. |
| 139 | Exclude []string // Comma separated list of regexp matching symbols to exclude. |
| 140 | Include []string // Comma separated list of regexp matching symbols to include. |
| 141 | Tag []string // Comma separated of build tags to be added to the created package. |
| 142 | } |
| 143 | |
| 144 | func (e *Extractor) genContent(importPath string, p *types.Package) ([]byte, error) { |
| 145 | prefix := "_" + importPath + "_" |
| 146 | prefix = strings.NewReplacer("/", "_", "-", "_", ".", "_", "~", "_").Replace(prefix) |
| 147 | |
| 148 | typ := map[string]string{} |
| 149 | val := map[string]Val{} |
| 150 | wrap := map[string]Wrap{} |
| 151 | imports := map[string]bool{} |
| 152 | sc := p.Scope() |
| 153 | |
| 154 | for _, pkg := range p.Imports() { |
| 155 | imports[pkg.Path()] = false |
| 156 | } |
| 157 | qualify := func(pkg *types.Package) string { |
| 158 | if pkg.Path() != importPath { |
| 159 | imports[pkg.Path()] = true |
| 160 | } |
| 161 | return pkg.Name() |
| 162 | } |
| 163 | |
| 164 | for _, name := range sc.Names() { |
| 165 | o := sc.Lookup(name) |
| 166 | if !o.Exported() { |
| 167 | continue |
| 168 | } |
| 169 | |
| 170 | if len(e.Include) > 0 { |
| 171 | match, err := matchList(name, e.Include) |
| 172 | if err != nil { |
| 173 | return nil, err |
| 174 | } |
| 175 | if !match { |
| 176 | // Explicitly defined include expressions force non matching symbols to be skipped. |
| 177 | continue |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | match, err := matchList(name, e.Exclude) |
| 182 | if err != nil { |
| 183 | return nil, err |
| 184 | } |
| 185 | if match { |
| 186 | continue |
| 187 | } |
| 188 | |
| 189 | pname := p.Name() + "." + name |
| 190 | if rname := p.Name() + name; restricted[rname] { |
| 191 | // Restricted symbol, locally provided by stdlib wrapper. |
| 192 | pname = rname |
| 193 | } |
| 194 | |
| 195 | switch o := o.(type) { |
| 196 | case *types.Const: |
| 197 | if b, ok := o.Type().(*types.Basic); ok && (b.Info()&types.IsUntyped) != 0 { |
| 198 | // Convert untyped constant to right type to avoid overflow. |
| 199 | val[name] = Val{fixConst(pname, o.Val(), imports), false} |
| 200 | } else { |
| 201 | val[name] = Val{pname, false} |
| 202 | } |
| 203 | case *types.Func: |
| 204 | // Skip generic functions and methods. |
| 205 | if s := o.Type().(*types.Signature); s.TypeParams().Len() > 0 || s.RecvTypeParams().Len() > 0 { |
| 206 | continue |
| 207 | } |
| 208 | val[name] = Val{pname, false} |
| 209 | case *types.Var: |
| 210 | val[name] = Val{pname, true} |
| 211 | case *types.TypeName: |
| 212 | // Skip type if it is generic. |
| 213 | if t, ok := o.Type().(*types.Named); ok && t.TypeParams().Len() > 0 { |
| 214 | continue |
| 215 | } |
| 216 | typ[name] = pname |
| 217 | if t, ok := o.Type().Underlying().(*types.Interface); ok { |
| 218 | if t.NumMethods() == 0 && t.NumEmbeddeds() != 0 { |
| 219 | // Skip interfaces used to implement constraints for generics. |
| 220 | delete(typ, name) |
| 221 | continue |
| 222 | } |
| 223 | var methods []Method |
| 224 | for i := 0; i < t.NumMethods(); i++ { |
| 225 | f := t.Method(i) |
| 226 | if !f.Exported() { |
| 227 | continue |
| 228 | } |
| 229 | |
| 230 | sign := f.Type().(*types.Signature) |
| 231 | args := make([]string, sign.Params().Len()) |
| 232 | params := make([]string, len(args)) |
| 233 | for j := range args { |
| 234 | v := sign.Params().At(j) |
| 235 | if args[j] = v.Name(); args[j] == "" { |
| 236 | args[j] = fmt.Sprintf("a%d", j) |
| 237 | } |
| 238 | // process interface method variadic parameter |
| 239 | if sign.Variadic() && j == len(args)-1 { // check is last arg |
| 240 | // only replace the first "[]" to "..." |
| 241 | at := types.TypeString(v.Type(), qualify)[2:] |
| 242 | params[j] = args[j] + " ..." + at |
| 243 | args[j] += "..." |
| 244 | } else { |
| 245 | params[j] = args[j] + " " + types.TypeString(v.Type(), qualify) |
| 246 | } |
| 247 | } |
| 248 | arg := "(" + strings.Join(args, ", ") + ")" |
| 249 | param := "(" + strings.Join(params, ", ") + ")" |
| 250 | |
| 251 | results := make([]string, sign.Results().Len()) |
| 252 | for j := range results { |
| 253 | v := sign.Results().At(j) |
| 254 | results[j] = v.Name() + " " + types.TypeString(v.Type(), qualify) |
| 255 | } |
| 256 | result := "(" + strings.Join(results, ", ") + ")" |
| 257 | |
| 258 | ret := "" |
| 259 | if sign.Results().Len() > 0 { |
| 260 | ret = "return" |
| 261 | } |
| 262 | |
| 263 | methods = append(methods, Method{f.Name(), param, result, arg, ret}) |
| 264 | } |
| 265 | wrap[name] = Wrap{prefix + name, methods} |
| 266 | } |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | // Generate buildTags with Go version only for stdlib packages. |
| 271 | // Third party packages do not depend on Go compiler version by default. |
| 272 | var buildTags string |
| 273 | if isInStdlib(importPath) { |
| 274 | var err error |
| 275 | buildTags, err = genBuildTags() |
| 276 | if err != nil { |
| 277 | return nil, err |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | base := template.New("extract") |
| 282 | parse, err := base.Parse(model) |
| 283 | if err != nil { |
| 284 | return nil, fmt.Errorf("template parsing error: %w", err) |
| 285 | } |
| 286 | |
| 287 | if importPath == "log/syslog" { |
| 288 | buildTags += ",!windows,!nacl,!plan9" |
| 289 | } |
| 290 | |
| 291 | if importPath == "syscall" { |
| 292 | // As per https://golang.org/cmd/go/#hdr-Build_constraints, |
| 293 | // using GOOS=android also matches tags and files for GOOS=linux, |
| 294 | // so exclude it explicitly to avoid collisions (issue #843). |
| 295 | // Also using GOOS=illumos matches tags and files for GOOS=solaris. |
| 296 | switch os.Getenv("GOOS") { |
| 297 | case "android": |
| 298 | buildTags += ",!linux" |
| 299 | case "illumos": |
| 300 | buildTags += ",!solaris" |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | for _, t := range e.Tag { |
| 305 | if t != "" { |
| 306 | buildTags += "," + t |
| 307 | } |
| 308 | } |
| 309 | if buildTags != "" && buildTags[0] == ',' { |
| 310 | buildTags = buildTags[1:] |
| 311 | } |
| 312 | |
| 313 | b := new(bytes.Buffer) |
| 314 | data := map[string]interface{}{ |
| 315 | "Dest": e.Dest, |
| 316 | "Imports": imports, |
| 317 | "ImportPath": importPath, |
| 318 | "PkgName": path.Join(importPath, p.Name()), |
| 319 | "Val": val, |
| 320 | "Typ": typ, |
| 321 | "Wrap": wrap, |
| 322 | "BuildTags": buildTags, |
| 323 | "License": e.License, |
| 324 | } |
| 325 | err = parse.Execute(b, data) |
| 326 | if err != nil { |
| 327 | return nil, fmt.Errorf("template error: %w", err) |
| 328 | } |
| 329 | |
| 330 | // gofmt |
| 331 | source, err := format.Source(b.Bytes()) |
| 332 | if err != nil { |
| 333 | return nil, fmt.Errorf("failed to format source: %w: %s", err, b.Bytes()) |
| 334 | } |
| 335 | return source, nil |
| 336 | } |
| 337 | |
| 338 | // fixConst checks untyped constant value, converting it if necessary to avoid overflow. |
| 339 | func fixConst(name string, val constant.Value, imports map[string]bool) string { |
| 340 | var ( |
| 341 | tok string |
| 342 | str string |
| 343 | ) |
| 344 | switch val.Kind() { |
| 345 | case constant.String: |
| 346 | tok = "STRING" |
| 347 | str = val.ExactString() |
| 348 | case constant.Int: |
| 349 | tok = "INT" |
| 350 | str = val.ExactString() |
| 351 | case constant.Float: |
| 352 | v := constant.Val(val) // v is *big.Rat or *big.Float |
| 353 | f, ok := v.(*big.Float) |
| 354 | if !ok { |
| 355 | f = new(big.Float).SetRat(v.(*big.Rat)) |
| 356 | } |
| 357 | |
| 358 | tok = "FLOAT" |
| 359 | str = f.Text('g', int(f.Prec())) |
| 360 | case constant.Complex: |
| 361 | // TODO: not sure how to parse this case |
| 362 | fallthrough //nolint:gocritic // Empty Fallthrough is expected. |
| 363 | default: |
| 364 | return name |
| 365 | } |
| 366 | |
| 367 | imports["go/constant"] = true |
| 368 | imports["go/token"] = true |
| 369 | |
| 370 | return fmt.Sprintf("constant.MakeFromLiteral(%q, token.%s, 0)", str, tok) |
| 371 | } |
| 372 | |
| 373 | // importPath checks whether pkgIdent is an existing directory relative to |
| 374 | // e.WorkingDir. If yes, it returns the actual import path of the Go package |
| 375 | // located in the directory. If it is definitely a relative path, but it does not |
| 376 | // exist, an error is returned. Otherwise, it is assumed to be an import path, and |
| 377 | // pkgIdent is returned. |
| 378 | func (e *Extractor) importPath(pkgIdent, importPath string) (string, error) { |
| 379 | wd, err := os.Getwd() |
| 380 | if err != nil { |
| 381 | return "", err |
| 382 | } |
| 383 | |
| 384 | dirPath := filepath.Join(wd, pkgIdent) |
| 385 | _, err = os.Stat(dirPath) |
| 386 | if err != nil && !os.IsNotExist(err) { |
| 387 | return "", err |
| 388 | } |
| 389 | if err != nil { |
| 390 | if pkgIdent != "" && pkgIdent[0] == '.' { |
| 391 | // pkgIdent is definitely a relative path, not a package name, and it does not exist |
| 392 | return "", err |
| 393 | } |
| 394 | // pkgIdent might be a valid stdlib package name. So we leave that responsibility to the caller now. |
| 395 | return pkgIdent, nil |
| 396 | } |
| 397 | |
| 398 | // local import |
| 399 | if importPath != "" { |
| 400 | return importPath, nil |
| 401 | } |
| 402 | |
| 403 | modPath := filepath.Join(dirPath, "go.mod") |
| 404 | _, err = os.Stat(modPath) |
| 405 | if os.IsNotExist(err) { |
| 406 | return "", errors.New("no go.mod found, and no import path specified") |
| 407 | } |
| 408 | if err != nil { |
| 409 | return "", err |
| 410 | } |
| 411 | f, err := os.Open(modPath) |
| 412 | if err != nil { |
| 413 | return "", err |
| 414 | } |
| 415 | defer func() { |
| 416 | _ = f.Close() |
| 417 | }() |
| 418 | sc := bufio.NewScanner(f) |
| 419 | var l string |
| 420 | for sc.Scan() { |
| 421 | l = sc.Text() |
| 422 | break |
| 423 | } |
| 424 | if sc.Err() != nil { |
| 425 | return "", err |
| 426 | } |
| 427 | parts := strings.Fields(l) |
| 428 | if len(parts) < 2 { |
| 429 | return "", errors.New(`invalid first line syntax in go.mod`) |
| 430 | } |
| 431 | if parts[0] != "module" { |
| 432 | return "", errors.New(`invalid first line in go.mod, no "module" found`) |
| 433 | } |
| 434 | |
| 435 | return parts[1], nil |
| 436 | } |
| 437 | |
| 438 | // Extract writes to rw a Go package with all the symbols found at pkgIdent. |
| 439 | // pkgIdent can be an import path, or a local path, relative to e.WorkingDir. In |
| 440 | // the latter case, Extract returns the actual import path of the package found at |
| 441 | // pkgIdent, otherwise it just returns pkgIdent. |
| 442 | // If pkgIdent is an import path, it is looked up in GOPATH. Vendoring is not |
| 443 | // supported yet, and the behavior is only defined for GO111MODULE=off. |
| 444 | func (e *Extractor) Extract(pkgIdent, importPath string, rw io.Writer) (string, error) { |
| 445 | ipp, err := e.importPath(pkgIdent, importPath) |
| 446 | if err != nil { |
| 447 | return "", err |
| 448 | } |
| 449 | |
| 450 | pkg, err := importer.ForCompiler(token.NewFileSet(), "source", nil).Import(pkgIdent) |
| 451 | if err != nil { |
| 452 | return "", err |
| 453 | } |
| 454 | |
| 455 | content, err := e.genContent(ipp, pkg) |
| 456 | if err != nil { |
| 457 | return "", err |
| 458 | } |
| 459 | |
| 460 | if _, err := rw.Write(content); err != nil { |
| 461 | return "", err |
| 462 | } |
| 463 | |
| 464 | return ipp, nil |
| 465 | } |
| 466 | |
| 467 | // GetMinor returns the minor part of the version number. |
| 468 | func GetMinor(part string) string { |
| 469 | minor := part |
| 470 | index := strings.Index(minor, "beta") |
| 471 | if index < 0 { |
| 472 | index = strings.Index(minor, "rc") |
| 473 | } |
| 474 | if index > 0 { |
| 475 | minor = minor[:index] |
| 476 | } |
| 477 | |
| 478 | return minor |
| 479 | } |
| 480 | |
| 481 | const defaultMinorVersion = 22 |
| 482 | |
| 483 | func genBuildTags() (string, error) { |
| 484 | version := runtime.Version() |
| 485 | if strings.HasPrefix(version, "devel") { |
| 486 | return "", fmt.Errorf("extracting only supported with stable releases of Go, not %v", version) |
| 487 | } |
| 488 | parts := strings.Split(version, ".") |
| 489 | |
| 490 | minorRaw := GetMinor(parts[1]) |
| 491 | |
| 492 | currentGoVersion := parts[0] + "." + minorRaw |
| 493 | |
| 494 | minor, err := strconv.Atoi(minorRaw) |
| 495 | if err != nil { |
| 496 | return "", fmt.Errorf("failed to parse version: %w", err) |
| 497 | } |
| 498 | |
| 499 | // Only append an upper bound if we are not on the latest go |
| 500 | if minor >= defaultMinorVersion { |
| 501 | return currentGoVersion, nil |
| 502 | } |
| 503 | |
| 504 | nextGoVersion := parts[0] + "." + strconv.Itoa(minor+1) |
| 505 | |
| 506 | return currentGoVersion + ",!" + nextGoVersion, nil |
| 507 | } |
| 508 | |
| 509 | func isInStdlib(path string) bool { return !strings.Contains(path, ".") } |