2015-07-27 16:47:18 +00:00
|
|
|
// Copyright 2015 The go-python Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package bind
|
|
|
|
|
|
|
|
import (
|
2015-08-31 08:23:57 +00:00
|
|
|
"bytes"
|
2019-01-11 11:00:12 +00:00
|
|
|
"encoding/json"
|
2015-08-10 12:57:31 +00:00
|
|
|
"fmt"
|
2015-11-16 11:54:02 +00:00
|
|
|
"go/types"
|
2019-01-11 11:00:12 +00:00
|
|
|
"os"
|
2015-08-31 08:23:57 +00:00
|
|
|
"os/exec"
|
2019-09-12 16:37:54 +00:00
|
|
|
"path/filepath"
|
2021-03-26 08:16:11 +00:00
|
|
|
"reflect"
|
2015-08-31 08:23:57 +00:00
|
|
|
"regexp"
|
2017-05-06 16:00:07 +00:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2019-01-11 11:00:12 +00:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2015-07-27 16:47:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func isErrorType(typ types.Type) bool {
|
|
|
|
return typ == types.Universe.Lookup("error").Type()
|
|
|
|
}
|
2015-07-28 12:35:59 +00:00
|
|
|
|
|
|
|
func isStringer(obj types.Object) bool {
|
|
|
|
switch obj := obj.(type) {
|
|
|
|
case *types.Func:
|
|
|
|
if obj.Name() != "String" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
sig, ok := obj.Type().(*types.Signature)
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if sig.Recv() == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if sig.Params().Len() != 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
res := sig.Results()
|
|
|
|
if res.Len() != 1 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
ret := res.At(0).Type()
|
|
|
|
if ret != types.Universe.Lookup("string").Type() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
2015-08-10 12:57:31 +00:00
|
|
|
|
|
|
|
func hasError(sig *types.Signature) bool {
|
|
|
|
res := sig.Results()
|
|
|
|
if res == nil || res.Len() <= 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
nerr := 0
|
|
|
|
for i := 0; i < res.Len(); i++ {
|
|
|
|
ret := res.At(i)
|
|
|
|
if isErrorType(ret.Type()) {
|
|
|
|
nerr++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case nerr == 0:
|
|
|
|
return false
|
|
|
|
case nerr == 1:
|
|
|
|
return true
|
|
|
|
default:
|
|
|
|
panic(fmt.Errorf(
|
|
|
|
"gopy: invalid number of comma-errors (%d)",
|
|
|
|
nerr,
|
|
|
|
))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func isConstructor(sig *types.Signature) bool {
|
|
|
|
//TODO(sbinet)
|
|
|
|
return false
|
|
|
|
}
|
2015-08-31 08:23:57 +00:00
|
|
|
|
2020-10-27 03:37:07 +00:00
|
|
|
type PyConfig struct {
|
2022-03-29 00:40:14 +00:00
|
|
|
Version int
|
|
|
|
CFlags string
|
|
|
|
LdFlags string
|
|
|
|
LdDynamicFlags string
|
|
|
|
ExtSuffix string
|
2019-01-11 11:00:12 +00:00
|
|
|
}
|
|
|
|
|
2020-10-27 03:37:07 +00:00
|
|
|
// AllFlags returns CFlags + " " + LdFlags
|
|
|
|
func (pc *PyConfig) AllFlags() string {
|
|
|
|
return strings.TrimSpace(pc.CFlags) + " " + strings.TrimSpace(pc.LdFlags)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetPythonConfig returns the needed python configuration for the given
|
2019-01-11 11:00:12 +00:00
|
|
|
// python VM (python, python2, python3, pypy, etc...)
|
2020-10-27 03:37:07 +00:00
|
|
|
func GetPythonConfig(vm string) (PyConfig, error) {
|
2019-01-11 11:00:12 +00:00
|
|
|
code := `import sys
|
2023-03-31 16:55:29 +00:00
|
|
|
try:
|
|
|
|
import sysconfig as ds
|
|
|
|
def _get_python_inc():
|
|
|
|
return ds.get_path('include')
|
|
|
|
except ImportError:
|
|
|
|
import distutils.sysconfig as ds
|
|
|
|
_get_python_inc = ds.get_config_var
|
2019-01-11 11:00:12 +00:00
|
|
|
import json
|
2020-02-10 15:34:42 +00:00
|
|
|
import os
|
|
|
|
version=sys.version_info.major
|
|
|
|
|
2022-03-29 00:40:14 +00:00
|
|
|
def clear_ld_flags(s):
|
2022-07-09 20:11:27 +00:00
|
|
|
if s is None:
|
|
|
|
return ''
|
2022-03-29 00:40:14 +00:00
|
|
|
skip_first_word = s.split(' ', 1)[1] # skip compiler name
|
|
|
|
skip_bundle = skip_first_word.replace('-bundle', '') # cgo already passes -dynamiclib
|
|
|
|
return skip_bundle
|
|
|
|
|
|
|
|
|
2020-02-10 15:34:42 +00:00
|
|
|
if "GOPY_INCLUDE" in os.environ and "GOPY_LIBDIR" in os.environ and "GOPY_PYLIB" in os.environ:
|
|
|
|
print(json.dumps({
|
|
|
|
"version": version,
|
2021-08-30 05:32:08 +00:00
|
|
|
"minor": sys.version_info.minor,
|
2020-02-10 15:34:42 +00:00
|
|
|
"incdir": os.environ["GOPY_INCLUDE"],
|
|
|
|
"libdir": os.environ["GOPY_LIBDIR"],
|
|
|
|
"libpy": os.environ["GOPY_PYLIB"],
|
|
|
|
"shlibs": ds.get_config_var("SHLIBS"),
|
|
|
|
"syslibs": ds.get_config_var("SYSLIBS"),
|
|
|
|
"shlinks": ds.get_config_var("LINKFORSHARED"),
|
2022-03-29 00:40:14 +00:00
|
|
|
"shflags": clear_ld_flags(ds.get_config_var("LDSHARED")),
|
2021-03-18 07:45:28 +00:00
|
|
|
"extsuffix": ds.get_config_var("EXT_SUFFIX"),
|
2020-02-10 15:34:42 +00:00
|
|
|
}))
|
|
|
|
else:
|
|
|
|
print(json.dumps({
|
|
|
|
"version": sys.version_info.major,
|
2021-08-30 05:32:08 +00:00
|
|
|
"minor": sys.version_info.minor,
|
2023-03-31 16:55:29 +00:00
|
|
|
"incdir": _get_python_inc(),
|
2020-02-10 15:34:42 +00:00
|
|
|
"libdir": ds.get_config_var("LIBDIR"),
|
|
|
|
"libpy": ds.get_config_var("LIBRARY"),
|
|
|
|
"shlibs": ds.get_config_var("SHLIBS"),
|
|
|
|
"syslibs": ds.get_config_var("SYSLIBS"),
|
|
|
|
"shlinks": ds.get_config_var("LINKFORSHARED"),
|
2022-03-29 00:40:14 +00:00
|
|
|
"shflags": clear_ld_flags(ds.get_config_var("LDSHARED")),
|
2021-03-18 07:45:28 +00:00
|
|
|
"extsuffix": ds.get_config_var("EXT_SUFFIX"),
|
2019-01-11 11:00:12 +00:00
|
|
|
}))
|
|
|
|
`
|
|
|
|
|
2020-10-27 03:37:07 +00:00
|
|
|
var cfg PyConfig
|
2019-01-11 11:00:12 +00:00
|
|
|
bin, err := exec.LookPath(vm)
|
2015-08-31 08:23:57 +00:00
|
|
|
if err != nil {
|
2019-01-11 11:00:12 +00:00
|
|
|
return cfg, errors.Wrapf(err, "could not locate python vm %q", vm)
|
2015-08-31 08:23:57 +00:00
|
|
|
}
|
|
|
|
|
2019-01-11 11:00:12 +00:00
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
cmd := exec.Command(bin, "-c", code)
|
|
|
|
cmd.Stdin = os.Stdin
|
|
|
|
cmd.Stdout = buf
|
|
|
|
cmd.Stderr = os.Stderr
|
|
|
|
err = cmd.Run()
|
2015-08-31 08:23:57 +00:00
|
|
|
if err != nil {
|
2019-01-11 11:00:12 +00:00
|
|
|
return cfg, errors.Wrap(err, "could not run python-config script")
|
2015-08-31 08:23:57 +00:00
|
|
|
}
|
|
|
|
|
2019-01-11 11:00:12 +00:00
|
|
|
var raw struct {
|
2021-03-18 07:45:28 +00:00
|
|
|
Version int `json:"version"`
|
2021-08-30 05:32:08 +00:00
|
|
|
Minor int `json:"minor"`
|
2021-03-18 07:45:28 +00:00
|
|
|
IncDir string `json:"incdir"`
|
|
|
|
LibDir string `json:"libdir"`
|
|
|
|
LibPy string `json:"libpy"`
|
|
|
|
ShLibs string `json:"shlibs"`
|
|
|
|
SysLibs string `json:"syslibs"`
|
|
|
|
ExtSuffix string `json:"extsuffix"`
|
2022-03-29 00:40:14 +00:00
|
|
|
ShFlags string `json:"shflags"`
|
2015-08-31 08:23:57 +00:00
|
|
|
}
|
2019-01-11 11:00:12 +00:00
|
|
|
err = json.NewDecoder(buf).Decode(&raw)
|
2015-08-31 08:23:57 +00:00
|
|
|
if err != nil {
|
2019-01-11 11:00:12 +00:00
|
|
|
return cfg, errors.Wrapf(err, "could not decode JSON script output")
|
2015-08-31 08:23:57 +00:00
|
|
|
}
|
|
|
|
|
2019-09-12 16:37:54 +00:00
|
|
|
raw.IncDir = filepath.ToSlash(raw.IncDir)
|
2020-02-10 15:34:42 +00:00
|
|
|
raw.LibDir = filepath.ToSlash(raw.LibDir)
|
|
|
|
|
2021-08-30 05:32:08 +00:00
|
|
|
// on windows these can be empty -- use include dir which is usu good
|
2023-06-01 02:03:38 +00:00
|
|
|
// replace suffix case insensitive 'include' with 'libs'
|
2021-08-30 05:32:08 +00:00
|
|
|
if raw.LibDir == "" && raw.IncDir != "" {
|
2023-06-01 02:03:38 +00:00
|
|
|
regexInc := regexp.MustCompile(`(?i)\binclude$`)
|
|
|
|
raw.LibDir = regexInc.ReplaceAllString(raw.IncDir, "libs")
|
2021-08-30 05:32:08 +00:00
|
|
|
fmt.Printf("no LibDir -- copy from IncDir: %s\n", raw.LibDir)
|
|
|
|
}
|
|
|
|
|
|
|
|
if raw.LibPy == "" {
|
|
|
|
raw.LibPy = fmt.Sprintf("python%d%d", raw.Version, raw.Minor)
|
|
|
|
fmt.Printf("no LibPy -- set to: %s\n", raw.LibPy)
|
|
|
|
}
|
|
|
|
|
2019-01-11 11:00:12 +00:00
|
|
|
if strings.HasSuffix(raw.LibPy, ".a") {
|
|
|
|
raw.LibPy = raw.LibPy[:len(raw.LibPy)-len(".a")]
|
|
|
|
}
|
|
|
|
if strings.HasPrefix(raw.LibPy, "lib") {
|
|
|
|
raw.LibPy = raw.LibPy[len("lib"):]
|
2015-08-31 08:23:57 +00:00
|
|
|
}
|
|
|
|
|
2020-10-27 03:37:07 +00:00
|
|
|
cfg.Version = raw.Version
|
2021-03-18 07:45:28 +00:00
|
|
|
cfg.ExtSuffix = raw.ExtSuffix
|
2020-10-27 03:37:07 +00:00
|
|
|
cfg.CFlags = strings.Join([]string{
|
2024-04-22 22:31:34 +00:00
|
|
|
`"-I` + raw.IncDir + `"`,
|
2019-01-11 11:00:12 +00:00
|
|
|
}, " ")
|
2020-10-27 03:37:07 +00:00
|
|
|
cfg.LdFlags = strings.Join([]string{
|
2024-04-22 22:31:34 +00:00
|
|
|
`"-L` + raw.LibDir + `"`,
|
|
|
|
`"-l` + raw.LibPy + `"`,
|
2019-01-11 11:00:12 +00:00
|
|
|
raw.ShLibs,
|
|
|
|
raw.SysLibs,
|
|
|
|
}, " ")
|
2022-03-29 00:40:14 +00:00
|
|
|
cfg.LdDynamicFlags = raw.ShFlags
|
2019-01-11 11:00:12 +00:00
|
|
|
|
|
|
|
return cfg, nil
|
2015-08-31 08:23:57 +00:00
|
|
|
}
|
2017-05-06 16:00:07 +00:00
|
|
|
|
|
|
|
func getGoVersion(version string) (int64, int64, error) {
|
|
|
|
version_regex := regexp.MustCompile(`^go((\d+)(\.(\d+))*)`)
|
|
|
|
match := version_regex.FindStringSubmatch(version)
|
|
|
|
if match == nil {
|
|
|
|
return -1, -1, fmt.Errorf("gopy: invalid Go version information: %q", version)
|
|
|
|
}
|
|
|
|
version_info := strings.Split(match[1], ".")
|
|
|
|
major, _ := strconv.ParseInt(version_info[0], 10, 0)
|
|
|
|
minor, _ := strconv.ParseInt(version_info[1], 10, 0)
|
|
|
|
return major, minor, nil
|
2017-06-08 12:24:00 +00:00
|
|
|
}
|
2018-06-12 16:41:50 +00:00
|
|
|
|
2021-03-26 08:16:11 +00:00
|
|
|
var (
|
|
|
|
rxValidPythonName = regexp.MustCompile(`^[\pL_][\pL_\pN]+$`)
|
|
|
|
)
|
|
|
|
|
2018-06-12 16:41:50 +00:00
|
|
|
func extractPythonName(gname, gdoc string) (string, string, error) {
|
2021-03-26 08:16:11 +00:00
|
|
|
const (
|
|
|
|
PythonName = "gopy:name "
|
|
|
|
NLPythonName = "\n" + PythonName
|
|
|
|
)
|
|
|
|
i := -1
|
|
|
|
var tag string
|
|
|
|
// Check for either a doc string that starts with our tag,
|
|
|
|
// or as the first token of a newline
|
|
|
|
if strings.HasPrefix(gdoc, PythonName) {
|
|
|
|
i = 0
|
|
|
|
tag = PythonName
|
|
|
|
} else {
|
|
|
|
i = strings.Index(gdoc, NLPythonName)
|
|
|
|
tag = NLPythonName
|
|
|
|
}
|
2018-06-12 16:41:50 +00:00
|
|
|
if i < 0 {
|
|
|
|
return gname, gdoc, nil
|
|
|
|
}
|
2021-03-26 08:16:11 +00:00
|
|
|
s := gdoc[i+len(tag):]
|
2018-06-12 16:41:50 +00:00
|
|
|
if end := strings.Index(s, "\n"); end > 0 {
|
2021-03-26 08:16:11 +00:00
|
|
|
if !isValidPythonName(s[:end]) {
|
2018-06-12 16:41:50 +00:00
|
|
|
return "", "", fmt.Errorf("gopy: invalid identifier: %s", s[:end])
|
|
|
|
}
|
|
|
|
return s[:end], gdoc[:i] + s[end:], nil
|
|
|
|
}
|
|
|
|
return gname, gdoc, nil
|
|
|
|
}
|
2021-03-26 08:16:11 +00:00
|
|
|
|
|
|
|
// extractPythonNameFieldTag parses a struct field tag and returns
|
|
|
|
// a new python name. If the tag is not defined then the original
|
|
|
|
// name is returned.
|
|
|
|
// If the tag name is specified but is an invalid python identifier,
|
|
|
|
// then an error is returned.
|
|
|
|
func extractPythonNameFieldTag(gname, tag string) (string, error) {
|
|
|
|
const tagKey = "gopy"
|
|
|
|
if tag == "" {
|
|
|
|
return gname, nil
|
|
|
|
}
|
|
|
|
tagVal := reflect.StructTag(tag).Get(tagKey)
|
|
|
|
if tagVal == "" {
|
|
|
|
return gname, nil
|
|
|
|
}
|
|
|
|
if !isValidPythonName(tagVal) {
|
|
|
|
return "", fmt.Errorf("gopy: invalid identifier for struct field tag: %s", tagVal)
|
|
|
|
}
|
|
|
|
return tagVal, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// isValidPythonName returns true if the string is a valid
|
|
|
|
// python identifier name
|
|
|
|
func isValidPythonName(name string) bool {
|
|
|
|
if name == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return rxValidPythonName.MatchString(name)
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
rxMatchFirstCap = regexp.MustCompile("([A-Z])([A-Z][a-z])")
|
|
|
|
rxMatchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
|
|
|
|
)
|
|
|
|
|
|
|
|
// toSnakeCase converts the provided string to snake_case.
|
|
|
|
// Based on https://gist.github.com/stoewer/fbe273b711e6a06315d19552dd4d33e6
|
|
|
|
func toSnakeCase(input string) string {
|
|
|
|
output := rxMatchFirstCap.ReplaceAllString(input, "${1}_${2}")
|
|
|
|
output = rxMatchAllCap.ReplaceAllString(output, "${1}_${2}")
|
|
|
|
output = strings.ReplaceAll(output, "-", "_")
|
|
|
|
return strings.ToLower(output)
|
|
|
|
}
|